{"doc_id": "00821847ab9598500cf0ae5398bbfe91", "text": "// WARMUP FROM https://codefellows.github.io/code-401-javascript-guide/curriculum/warm-ups/daily/\nconst people = ['Kookla','Fran','Ollie'];\n\nconst stuff = {\n tv: 'huge',\n radio: 'old',\n toothbrush: 'frayed',\n cars: ['Toyota','Mazda']\n}\n\n// let state = {};\n// let newPeople = [];\n// const newStuff = {};\nlet newState = {};\n\n// SPREAD DEMOS\n// [Oddie, Kookla, Fran, Ollie, Garfield]\nlet newPeople = ['Oddie', ...people, 'Garfield'];\nconsole.log(newPeople);\n\nlet newStuff = { ...stuff, cars:[...stuff.cars, 'GMC'] };\nconsole.log(newStuff);\n\n/*\nCreat a state object with keys of people and stuff that contain the people and stuff data.\nDo this using object destructuring assignment\n*/\nlet state = { stuff, people }\nconsole.log(state)\n\nconsole.log('============')\n\nlet bigState = {\n ...state,\n people: ['Oddie', ...people, 'Garfield'],\n stuff: \n { cars: [...stuff.cars, 'GMC'] }\n}\n\nconsole.log(bigState);\n\n\nfunction forLoop(arr) {\n for(let i = 0; i < arr.length; i++) {\n console.log(arr[i]);\n }\n}\n\nfunction whileLoop(arr) {\n // OG WAY\n // let i = 0;\n // // while( arr[i]) {\n // while (i < arr.length) {\n // console.log(arr[i]);\n // i++;\n\n // PASS BY REF / CLONE WAY\n let internalArray = [...arr];\n while (internalArray.length) {\n console.log(internalArray.shift());\n }\n}\n\nfunction mapLoop(arr) {\n let newArray = arr.map((val, idx) => {\n console.log(val);\n return { value: val };\n });\n\n console.log('NEWARRAY', newArray);\n}\n\nfunction map(arr, callbackFunction) {\n\n}\n\nfunction filter(arr, callbackFunction) {\n\n}\n \n\nconsole.log('forLoop')\nforLoop(people);\nconsole.log('=========')\n\nconsole.log('whileLoop')\nwhileLoop(people);\nconsole.log('=========')\n\nconsole.log('mapLoop')\nmapLoop(people);\nconsole.log('=========')\n\nconsole.log('map')\nlet mapped = map(people, (val, idx) => 'Rosie');\nconsole.log('map', mapped);\nconsole.log('=========')\n\nlet filtered = filter(people, (val, idx) => val === 'Kookla')\nconsole.log('filter');\nconsole.log(filtered);\nconsole.log('=========')\n\nconsole.log('PEOPLE', people);"} {"doc_id": "00a2b9d16ed3b9f8426723b494b337d8", "text": "// I paired [by myself] on this challenge.\n\n\n\n\n// Pseudocode\n// secretNumber equals 7\n// password equals a string called \"just open the door\"\n// allowedIn should be boolean value false\n// members should be an array that contains John as first and Mary as 4th element\n\n\n\n// __________________________________________\n// Write your code below.\n\nvar secretNumber = 7\nvar password = \"just open the door\"\nvar allowedIn = false\nvar members = [\"John\", \"Tom\", \"Aki\", \"Mary\"]\n\n\n\n\n// __________________________________________\n// Driver Code: Do not alter code below this line.\n\nfunction assert(test, message, test_number) {\n if (!test) {\n console.log(test_number + \"false\");\n throw \"ERROR: \" + message;\n }\n console.log(test_number + \"true\");\n return true;\n}\n\nassert(\n (typeof secretNumber === 'number'),\n \"The value of secretNumber should be a number.\",\n \"1. \"\n)\n\nassert(\n secretNumber === 7,\n \"The value of secretNumber should be 7.\",\n \"2. \"\n)\n\nassert(\n typeof password === 'string',\n \"The value of password should be a string.\",\n \"3. \"\n)\n\nassert(\n password === \"just open the door\",\n \"The value of password should be 'just open the door'.\",\n \"4. \"\n)\n\nassert(\n typeof allowedIn === 'boolean',\n \"The value of allowedIn should be a boolean.\",\n \"5. \"\n)\n\nassert(\n allowedIn === false,\n \"The value of allowedIn should be false.\",\n \"6. \"\n)\n\nassert(\n members instanceof Array,\n \"The value of members should be an array\",\n \"7. \"\n)\n\nassert(\n members[0] === \"John\",\n \"The first element in the value of members should be 'John'.\",\n \"8. \"\n)\n\nassert(\n members[3] === \"Mary\",\n \"The fourth element in the value of members should be 'Mary'.\",\n \"9. \"\n)\n\n\n\n\n\n// __________________________________________\n// Refactored Code: Include a refactored version (or justification of your original code) here. \n\n// I thought this generally looked good. Since it was obvious that it was a number, I shortened the variable name\nvar secretNum = 7\n// Password as a var name was too generic so i made it applicable to the member scenario\nvar memberPW = \"just open the door\"\n// This one felt weird as a boolean question so i framed the var as a validation question instead\nvar isAllowed = false\n// members felt too generic so I added some context at the end while keeping it plural to indicate an array\nvar membersList = [\"John\", \"Tom\", \"Aki\", \"Mary\"]\n\n// with the new variables, I could also choose to flatten them into one expression\n{var secretNum = 7; var memberPW = \"just open the door\"; var isAllowed = false; var membersList = [\"John\", \"Tom\", \"Aki\", \"Mary\"]}\n\n\n\n// __________________________________________\n// Reflection: Use the reflection guidelines to write a reflection here. \n\n// Framing the pseudocode was a bit confusing to me at first as they can look so similar to user stories. \n// I've internalized it in my head that user stories most importantly provide context and don't have to be mapped to code expressions line-by-line, but pseudocode can be looked at as tiny nibble size user stories that where best practice is to have each line of pseudo code translatable to an equivalent code experssion. \n\n// Refactoring was another point of interest for me. In the DRY concept, minimal duplication and avoiding waste were big concepts, and the 7+1 tips for naming variables was also possible. \n// I can see the beauty in providing context to people unfamiliar with your code in the most efficient way. \n// \n\n"} {"doc_id": "012cf0428e425070b53bc43f956d779e", "text": "// Assignment Code\nconst generateBtn = document.querySelector(\"#generate\");\n\n// Write password to the #password input\nfunction writePassword() {\n const password = generatePassword();\n const passwordText = document.querySelector(\"#password\");\n\n // Stops last generated password from clearing if a follow-up generator was cancelled\n if (password != null) { // Falsy check for null or undefined\n passwordText.value = password;\n console.log(\"\\nGenerated Password: \" + passwordText.value);\n }\n}\n\n// Generate random password function\nfunction generatePassword() {\n let isGenerated = false;\n let passwordLength = 0;\n let passwd = \"\";\n let charStr = \"\"; // Character string to be used for password generation\n const lower = \"abcdefghijklmnopqrstuvwxyz\";\n const upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const nums = \"0123456789\";\n const specialChars = \" !\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\";\n let charTypeLog = \"Input validated!\\nPassword will be generated with these character types:\\n\\n\";\n\n // Loop until password is cancelled or generated \n while (!isGenerated) {\n // Prompt user for password length and display boundaries for user.\n passwordLength = prompt(\n \"How many characters would you like your password to be?\\nMinimum: 8\\nMaximum: 128\"\n );\n // Check for valid input\n if (passwordLength == null) { // If generator is cancelled\n return;\n }\n else if (!Number.isInteger(Number(passwordLength)) || passwordLength.trim() === \"\") { // If NaN/floating points/empty string inputs are found.\n alert(\"Invalid input. Try again!\");\n }\n else if (passwordLength < 8 || passwordLength > 128) { // If invalid password length.\n alert(\"You must choose a password length of at least 8 characters and no more than 128 characters. Try again!\");\n }\n else { // Valid input, proceed.\n // Prompt user for character types to be used in password.\n while (charStr.length === 0) {\n // Ask to include lowercase letters\n if (confirm(\"Include lowercase letters?\")) {\n charStr += lower;\n charTypeLog += \"Lowercase\\n\";\n }\n // Ask to include uppercase letters\n if (confirm(\"Include uppercase letters?\")) {\n charStr += upper;\n charTypeLog += \"Uppercase\\n\";\n }\n // Ask to include numbers\n if (confirm(\"Include numbers?\")) {\n charStr += nums;\n charTypeLog += \"Numbers\\n\";\n }\n // Ask to include special characters\n if (confirm(\"Include special characters?\")) {\n charStr += specialChars;\n charTypeLog += \"Special Characters\\n\";\n }\n // Check if character type has been selected\n if (charStr.length > 0) {\n // Log for password criteria\n console.log(charTypeLog + \"\\n\");\n console.log(charStr + \"\\n\");\n } else {\n alert(\"At least one character type should be selected!\");\n }\n }\n // Generate Password\n for (let i = 0; i < passwordLength; i++) {\n // Append random character based on size of charStr\n passwd += charStr[Math.floor(Math.random() * charStr.length)];\n }\n // Set variable to exit loop\n isGenerated = true;\n }\n }\n // Return generated password\n return passwd;\n}\n\n// Add event listener to generate button\ngenerateBtn.addEventListener(\"click\", writePassword);"} {"doc_id": "017c68de09dade03909aae51f08a5bd9", "text": "/*\n

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

\n\n

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

\n\n

Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

\n\n

Note:

\n\n\n\n

Example 1:

\n\n
\nInput: \ngas  = [1,2,3,4,5]\ncost = [3,4,5,1,2]\n\nOutput: 3\n\nExplanation:\nStart at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.\n
\n\n

Example 2:

\n\n
\nInput: \ngas  = [2,3,4]\ncost = [3,4,3]\n\nOutput: -1\n\nExplanation:\nYou can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.\n
\n

\u5728\u4e00\u6761\u73af\u8def\u4e0a\u6709 N \u4e2a\u52a0\u6cb9\u7ad9\uff0c\u5176\u4e2d\u7b2c i \u4e2a\u52a0\u6cb9\u7ad9\u6709\u6c7d\u6cb9 gas[i] \u5347\u3002

\n\n

\u4f60\u6709\u4e00\u8f86\u6cb9\u7bb1\u5bb9\u91cf\u65e0\u9650\u7684\u7684\u6c7d\u8f66\uff0c\u4ece\u7b2c i \u4e2a\u52a0\u6cb9\u7ad9\u5f00\u5f80\u7b2c i+1 \u4e2a\u52a0\u6cb9\u7ad9\u9700\u8981\u6d88\u8017\u6c7d\u6cb9 cost[i] \u5347\u3002\u4f60\u4ece\u5176\u4e2d\u7684\u4e00\u4e2a\u52a0\u6cb9\u7ad9\u51fa\u53d1\uff0c\u5f00\u59cb\u65f6\u6cb9\u7bb1\u4e3a\u7a7a\u3002

\n\n

\u5982\u679c\u4f60\u53ef\u4ee5\u7ed5\u73af\u8def\u884c\u9a76\u4e00\u5468\uff0c\u5219\u8fd4\u56de\u51fa\u53d1\u65f6\u52a0\u6cb9\u7ad9\u7684\u7f16\u53f7\uff0c\u5426\u5219\u8fd4\u56de -1\u3002

\n\n

\u8bf4\u660e: 

\n\n\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: \ngas  = [1,2,3,4,5]\ncost = [3,4,5,1,2]\n\n\u8f93\u51fa: 3\n\n\u89e3\u91ca:\n\u4ece 3 \u53f7\u52a0\u6cb9\u7ad9(\u7d22\u5f15\u4e3a 3 \u5904)\u51fa\u53d1\uff0c\u53ef\u83b7\u5f97 4 \u5347\u6c7d\u6cb9\u3002\u6b64\u65f6\u6cb9\u7bb1\u6709 = 0 + 4 = 4 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 4 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 4 - 1 + 5 = 8 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 0 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 8 - 2 + 1 = 7 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 1 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 7 - 3 + 2 = 6 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 2 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 6 - 4 + 3 = 5 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 3 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u4f60\u9700\u8981\u6d88\u8017 5 \u5347\u6c7d\u6cb9\uff0c\u6b63\u597d\u8db3\u591f\u4f60\u8fd4\u56de\u5230 3 \u53f7\u52a0\u6cb9\u7ad9\u3002\n\u56e0\u6b64\uff0c3 \u53ef\u4e3a\u8d77\u59cb\u7d22\u5f15\u3002
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: \ngas  = [2,3,4]\ncost = [3,4,3]\n\n\u8f93\u51fa: -1\n\n\u89e3\u91ca:\n\u4f60\u4e0d\u80fd\u4ece 0 \u53f7\u6216 1 \u53f7\u52a0\u6cb9\u7ad9\u51fa\u53d1\uff0c\u56e0\u4e3a\u6ca1\u6709\u8db3\u591f\u7684\u6c7d\u6cb9\u53ef\u4ee5\u8ba9\u4f60\u884c\u9a76\u5230\u4e0b\u4e00\u4e2a\u52a0\u6cb9\u7ad9\u3002\n\u6211\u4eec\u4ece 2 \u53f7\u52a0\u6cb9\u7ad9\u51fa\u53d1\uff0c\u53ef\u4ee5\u83b7\u5f97 4 \u5347\u6c7d\u6cb9\u3002 \u6b64\u65f6\u6cb9\u7bb1\u6709 = 0 + 4 = 4 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 0 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 4 - 3 + 2 = 3 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 1 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 3 - 3 + 3 = 3 \u5347\u6c7d\u6cb9\n\u4f60\u65e0\u6cd5\u8fd4\u56de 2 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u56e0\u4e3a\u8fd4\u7a0b\u9700\u8981\u6d88\u8017 4 \u5347\u6c7d\u6cb9\uff0c\u4f46\u662f\u4f60\u7684\u6cb9\u7bb1\u53ea\u6709 3 \u5347\u6c7d\u6cb9\u3002\n\u56e0\u6b64\uff0c\u65e0\u8bba\u600e\u6837\uff0c\u4f60\u90fd\u4e0d\u53ef\u80fd\u7ed5\u73af\u8def\u884c\u9a76\u4e00\u5468\u3002
\n

\u5728\u4e00\u6761\u73af\u8def\u4e0a\u6709 N \u4e2a\u52a0\u6cb9\u7ad9\uff0c\u5176\u4e2d\u7b2c i \u4e2a\u52a0\u6cb9\u7ad9\u6709\u6c7d\u6cb9 gas[i] \u5347\u3002

\n\n

\u4f60\u6709\u4e00\u8f86\u6cb9\u7bb1\u5bb9\u91cf\u65e0\u9650\u7684\u7684\u6c7d\u8f66\uff0c\u4ece\u7b2c i \u4e2a\u52a0\u6cb9\u7ad9\u5f00\u5f80\u7b2c i+1 \u4e2a\u52a0\u6cb9\u7ad9\u9700\u8981\u6d88\u8017\u6c7d\u6cb9 cost[i] \u5347\u3002\u4f60\u4ece\u5176\u4e2d\u7684\u4e00\u4e2a\u52a0\u6cb9\u7ad9\u51fa\u53d1\uff0c\u5f00\u59cb\u65f6\u6cb9\u7bb1\u4e3a\u7a7a\u3002

\n\n

\u5982\u679c\u4f60\u53ef\u4ee5\u7ed5\u73af\u8def\u884c\u9a76\u4e00\u5468\uff0c\u5219\u8fd4\u56de\u51fa\u53d1\u65f6\u52a0\u6cb9\u7ad9\u7684\u7f16\u53f7\uff0c\u5426\u5219\u8fd4\u56de -1\u3002

\n\n

\u8bf4\u660e: 

\n\n\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: \ngas  = [1,2,3,4,5]\ncost = [3,4,5,1,2]\n\n\u8f93\u51fa: 3\n\n\u89e3\u91ca:\n\u4ece 3 \u53f7\u52a0\u6cb9\u7ad9(\u7d22\u5f15\u4e3a 3 \u5904)\u51fa\u53d1\uff0c\u53ef\u83b7\u5f97 4 \u5347\u6c7d\u6cb9\u3002\u6b64\u65f6\u6cb9\u7bb1\u6709 = 0 + 4 = 4 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 4 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 4 - 1 + 5 = 8 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 0 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 8 - 2 + 1 = 7 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 1 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 7 - 3 + 2 = 6 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 2 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 6 - 4 + 3 = 5 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 3 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u4f60\u9700\u8981\u6d88\u8017 5 \u5347\u6c7d\u6cb9\uff0c\u6b63\u597d\u8db3\u591f\u4f60\u8fd4\u56de\u5230 3 \u53f7\u52a0\u6cb9\u7ad9\u3002\n\u56e0\u6b64\uff0c3 \u53ef\u4e3a\u8d77\u59cb\u7d22\u5f15\u3002
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: \ngas  = [2,3,4]\ncost = [3,4,3]\n\n\u8f93\u51fa: -1\n\n\u89e3\u91ca:\n\u4f60\u4e0d\u80fd\u4ece 0 \u53f7\u6216 1 \u53f7\u52a0\u6cb9\u7ad9\u51fa\u53d1\uff0c\u56e0\u4e3a\u6ca1\u6709\u8db3\u591f\u7684\u6c7d\u6cb9\u53ef\u4ee5\u8ba9\u4f60\u884c\u9a76\u5230\u4e0b\u4e00\u4e2a\u52a0\u6cb9\u7ad9\u3002\n\u6211\u4eec\u4ece 2 \u53f7\u52a0\u6cb9\u7ad9\u51fa\u53d1\uff0c\u53ef\u4ee5\u83b7\u5f97 4 \u5347\u6c7d\u6cb9\u3002 \u6b64\u65f6\u6cb9\u7bb1\u6709 = 0 + 4 = 4 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 0 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 4 - 3 + 2 = 3 \u5347\u6c7d\u6cb9\n\u5f00\u5f80 1 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u6b64\u65f6\u6cb9\u7bb1\u6709 3 - 3 + 3 = 3 \u5347\u6c7d\u6cb9\n\u4f60\u65e0\u6cd5\u8fd4\u56de 2 \u53f7\u52a0\u6cb9\u7ad9\uff0c\u56e0\u4e3a\u8fd4\u7a0b\u9700\u8981\u6d88\u8017 4 \u5347\u6c7d\u6cb9\uff0c\u4f46\u662f\u4f60\u7684\u6cb9\u7bb1\u53ea\u6709 3 \u5347\u6c7d\u6cb9\u3002\n\u56e0\u6b64\uff0c\u65e0\u8bba\u600e\u6837\uff0c\u4f60\u90fd\u4e0d\u53ef\u80fd\u7ed5\u73af\u8def\u884c\u9a76\u4e00\u5468\u3002
\n*/\n\n\n/**\n * @param {number[]} gas\n * @param {number[]} cost\n * @return {number}\n */\nvar canCompleteCircuit = function(gas, cost) {\n \n};"} {"doc_id": "017f24be033ac3eb58824169b930b996", "text": "\n\n// create data structure to store the character set and random generation function\n// MODEL\n\nconst characterSet = {\n\n // all lower case alphabets\n lowerCase: \"abcdefghijklmnopqrstuvwxyz\",\n // all upper case alphabets\n upperCase: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n // all numbers\n numbers: \"0123456789\",\n // all special characters, list provided by the instructors\n specialCharacters: \"@%+\\\\/'!#$^?:,)(}{][~-_.\"\n\n};\n\n// save user choice\nvar includeLower;\nvar includeUpper;\nvar includeNumbers;\nvar includeSymbols;\nvar passwordLength;\n\n\n// Collect User Data, View\nfunction userInput() {\n \n\n // get user input\n // get the form element\n var formInput = document.getElementById('formInput');\n\n // store users selection\n includeLower = formInput.lower.checked;\n includeUpper = formInput.upper.checked;\n includeNumbers = formInput.number.checked;\n includeSymbols = formInput.symbols.checked;\n passwordLength = parseInt(formInput.passwordLength.value);\n\n // if user doesn't select any option, default to lower case\n if(!(includeLower || includeUpper || includeNumbers || includeSymbols)) {\n includeLower = true;\n } \n\n // store all options\n var option = \"\";\n if(includeLower) {\n option += characterSet.lowerCase;\n }\n if(includeUpper) {\n option += characterSet.upperCase;\n }\n if(includeNumbers) {\n option += characterSet.numbers;\n }\n if(includeSymbols) {\n option += characterSet.specialCharacters;\n }\n\n\n // create object userChoice\n var userChoice = {\n length: passwordLength,\n allCharacterSet: option\n };\n \n console.log(userChoice.length);\n console.log(userChoice.allCharacterSet);\n\n return userChoice;\n}\n\n\n\n// Generate Random Password, Controller\nexport function generatePassword() {\n\n // will store user password, random password\n var password=\"\";\n\n // get user Input, Character Set and the length of the password\n var userChoice = userInput();\n\n // get the length of the password\n var userPwdLength = userChoice.length;\n\n // get the character Set, all the option the user wants , is lowerCase by default\n var userCharacterSet = userChoice.allCharacterSet;\n\n\n // password must include at least 1 character from the characterSets \n var password = includeAtleastOneCharacter();\n var additionalPwd = userPwdLength - password.length;\n // create a loop to get a random number from 0 to the total length of the userCharacterSet-1\n // user that random number as an index\n // pick a random character untill we get desired number of password length\n for(let i = 0; i < additionalPwd; i++) {\n\n // Math.random() creates a random number between 0 to 1 , \n // Multiply it by the total length of the userCharacterSet to get the length\n // Round the result with Math.floor()\n var randomIndex = Math.floor( Math.random() * userCharacterSet.length );\n \n // user the random number as an index, get the random character and add save it\n // String is also of type array, we can access the string as with the array\n password += userCharacterSet[ randomIndex ];\n }\n\n // console log the result for testing, print both password and \n console.log(\"password : \" + password)\n console.log(\"password length: \" + password.length);\n\n // to avoid any further pattern we can shuffle it, \n // because we didn't pick from each charactre set individually, we don't have a pattern like\n // lowercaseRandom + upperCaseRandom + numberRandom + specialCharacterrandom \n\n return password;\n}\n\n\n// picks atleast 1 character from the characters set\nfunction includeAtleastOneCharacter() {\n var password = \"\";\n // random index\n var randomIndex = Math.floor( Math.random() * 10);\n\n if(includeLower) {\n password += characterSet.lowerCase[randomIndex];\n }\n\n if(includeUpper) {\n password += characterSet.upperCase[randomIndex];\n }\n\n if(includeNumbers) {\n password += characterSet.numbers[randomIndex];\n }\n\n if(includeSymbols) {\n password += characterSet.specialCharacters[randomIndex];\n }\n\n console.log(\"at : \" + password);\n\n return password;\n}\n\n"} {"doc_id": "01817c0f4578cddbbfec3fbd88a95e51", "text": "/*\n

\nIn English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.\n

\n\n\n

\nNow, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.\n

\n\n

\nYou need to output the sentence after the replacement.\n

\n\n\n

Example 1:
\n

\nInput: dict = [\"cat\", \"bat\", \"rat\"]\nsentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\n
\n

\n\n\n

Note:
\n

    \n
  1. The input will only have lower-case letters.
  2. \n
  3. 1 <= dict words number <= 1000
  4. \n
  5. 1 <= sentence words number <= 1000
  6. \n
  7. 1 <= root length <= 100
  8. \n
  9. 1 <= sentence words length <= 1000
  10. \n
\n

\u5728\u82f1\u8bed\u4e2d\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u53eb\u505a \u8bcd\u6839(root)\u7684\u6982\u5ff5\uff0c\u5b83\u53ef\u4ee5\u8ddf\u7740\u5176\u4ed6\u4e00\u4e9b\u8bcd\u7ec4\u6210\u53e6\u4e00\u4e2a\u8f83\u957f\u7684\u5355\u8bcd——\u6211\u4eec\u79f0\u8fd9\u4e2a\u8bcd\u4e3a \u7ee7\u627f\u8bcd(successor)\u3002\u4f8b\u5982\uff0c\u8bcd\u6839an\uff0c\u8ddf\u968f\u7740\u5355\u8bcd other(\u5176\u4ed6)\uff0c\u53ef\u4ee5\u5f62\u6210\u65b0\u7684\u5355\u8bcd another(\u53e6\u4e00\u4e2a)\u3002

\n\n

\u73b0\u5728\uff0c\u7ed9\u5b9a\u4e00\u4e2a\u7531\u8bb8\u591a\u8bcd\u6839\u7ec4\u6210\u7684\u8bcd\u5178\u548c\u4e00\u4e2a\u53e5\u5b50\u3002\u4f60\u9700\u8981\u5c06\u53e5\u5b50\u4e2d\u7684\u6240\u6709\u7ee7\u627f\u8bcd\u7528\u8bcd\u6839\u66ff\u6362\u6389\u3002\u5982\u679c\u7ee7\u627f\u8bcd\u6709\u8bb8\u591a\u53ef\u4ee5\u5f62\u6210\u5b83\u7684\u8bcd\u6839\uff0c\u5219\u7528\u6700\u77ed\u7684\u8bcd\u6839\u66ff\u6362\u5b83\u3002

\n\n

\u4f60\u9700\u8981\u8f93\u51fa\u66ff\u6362\u4e4b\u540e\u7684\u53e5\u5b50\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: dict(\u8bcd\u5178) = ["cat", "bat", "rat"]\nsentence(\u53e5\u5b50) = "the cattle was rattled by the battery"\n\u8f93\u51fa: "the cat was rat by the bat"\n
\n\n

\u6ce8:

\n\n
    \n\t
  1. \u8f93\u5165\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002
  2. \n\t
  3. 1 <= \u5b57\u5178\u5355\u8bcd\u6570 <=1000
  4. \n\t
  5. 1 <=  \u53e5\u4e2d\u8bcd\u8bed\u6570 <= 1000
  6. \n\t
  7. 1 <= \u8bcd\u6839\u957f\u5ea6 <= 100
  8. \n\t
  9. 1 <= \u53e5\u4e2d\u8bcd\u8bed\u957f\u5ea6 <= 1000
  10. \n
\n

\u5728\u82f1\u8bed\u4e2d\uff0c\u6211\u4eec\u6709\u4e00\u4e2a\u53eb\u505a \u8bcd\u6839(root)\u7684\u6982\u5ff5\uff0c\u5b83\u53ef\u4ee5\u8ddf\u7740\u5176\u4ed6\u4e00\u4e9b\u8bcd\u7ec4\u6210\u53e6\u4e00\u4e2a\u8f83\u957f\u7684\u5355\u8bcd——\u6211\u4eec\u79f0\u8fd9\u4e2a\u8bcd\u4e3a \u7ee7\u627f\u8bcd(successor)\u3002\u4f8b\u5982\uff0c\u8bcd\u6839an\uff0c\u8ddf\u968f\u7740\u5355\u8bcd other(\u5176\u4ed6)\uff0c\u53ef\u4ee5\u5f62\u6210\u65b0\u7684\u5355\u8bcd another(\u53e6\u4e00\u4e2a)\u3002

\n\n

\u73b0\u5728\uff0c\u7ed9\u5b9a\u4e00\u4e2a\u7531\u8bb8\u591a\u8bcd\u6839\u7ec4\u6210\u7684\u8bcd\u5178\u548c\u4e00\u4e2a\u53e5\u5b50\u3002\u4f60\u9700\u8981\u5c06\u53e5\u5b50\u4e2d\u7684\u6240\u6709\u7ee7\u627f\u8bcd\u7528\u8bcd\u6839\u66ff\u6362\u6389\u3002\u5982\u679c\u7ee7\u627f\u8bcd\u6709\u8bb8\u591a\u53ef\u4ee5\u5f62\u6210\u5b83\u7684\u8bcd\u6839\uff0c\u5219\u7528\u6700\u77ed\u7684\u8bcd\u6839\u66ff\u6362\u5b83\u3002

\n\n

\u4f60\u9700\u8981\u8f93\u51fa\u66ff\u6362\u4e4b\u540e\u7684\u53e5\u5b50\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: dict(\u8bcd\u5178) = ["cat", "bat", "rat"]\nsentence(\u53e5\u5b50) = "the cattle was rattled by the battery"\n\u8f93\u51fa: "the cat was rat by the bat"\n
\n\n

\u6ce8:

\n\n
    \n\t
  1. \u8f93\u5165\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002
  2. \n\t
  3. 1 <= \u5b57\u5178\u5355\u8bcd\u6570 <=1000
  4. \n\t
  5. 1 <=  \u53e5\u4e2d\u8bcd\u8bed\u6570 <= 1000
  6. \n\t
  7. 1 <= \u8bcd\u6839\u957f\u5ea6 <= 100
  8. \n\t
  9. 1 <= \u53e5\u4e2d\u8bcd\u8bed\u957f\u5ea6 <= 1000
  10. \n
\n*/\n\n\n/**\n * @param {string[]} dict\n * @param {string} sentence\n * @return {string}\n */\nvar replaceWords = function(dict, sentence) {\n \n};"} {"doc_id": "01a05497cac049892414cb125f551fbb", "text": "/*\nAPP: Aggregation of Prime Permutations\n---------------------------------------\nGiven an input number, return the sum of all permutations of the number that are prime. You do not have to use all digits in your permutation.\n\nInput: 123\nOutput: 72\nExplanation: Total of (2 + 3 + 13 + 23 + 31)\n*/\n(function() {\n var permutations = new Array();\n\n /*\n Time Complexity: \n Space Complexity: \n */\n var aggregationOfPrimePermutations = function(num) {\n var result = 0;\n\n if (num != null && num > 0) {\n var digits = num.toString().split('').map(function(t) {\n return parseInt(t);\n });\n\n GetPermutations('', num.toString());\n var arr = permutations;\n\n for (var i = 0; i < arr.length; i++) {\n if (IsPrime(parseInt(arr[i]))) {\n result += parseInt(arr[i]);\n }\n }\n }\n\n return result;\n };\n\n function GetPermutations(prefix, num) {\n var n = num.length;\n\n if (n == 0) {\n permutations.push(parseInt(prefix));\n } else {\n for (var i = n; i > 0; i--) {\n for (var j = 0; j < i; j++) {\n var prefix_new = prefix + num.charAt(j);\n var num_new = num.substring(0, j) + num.substring(j + 1, i);\n GetPermutations(prefix_new, num_new);\n }\n }\n }\n }\n\n function DigitsToNumber(digits) {\n var result = 0;\n\n if (digits != null && digits.length > 0) {\n result = parseInt(digits.join(''));\n }\n\n return result;\n }\n\n function Swap(arr, i, j) {\n if (arr != null && arr.length > 0 && i < arr.length && j < arr.length) {\n var temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n\n function IsPrime(num) {\n if (num <= 1) {\n return false;\n } else {\n for (var i = 2; i * i < num; i++) {\n if (num % i) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n console.log(\"null:\", aggregationOfPrimePermutations(null));\n console.log(\"undefined:\", aggregationOfPrimePermutations(undefined));\n console.log(\"0:\", aggregationOfPrimePermutations(0));\n console.log(\"123:\", aggregationOfPrimePermutations(123));\n})();"} {"doc_id": "01a5e73593ebdfe2ccb82eb47d0f1ab7", "text": "/*\n

There are a total of n courses you have to take, labeled from 0 to n-1.

\n\n

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

\n\n

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

\n\n

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

\n\n

Example 1:

\n\n
\nInput: 2, [[1,0]] \nOutput: [0,1]\nExplanation: There are a total of 2 courses to take. To take course 1 you should have finished   \n             course 0. So the correct course order is [0,1] .
\n\n

Example 2:

\n\n
\nInput: 4, [[1,0],[2,0],[3,1],[3,2]]\nOutput: [0,1,2,3] or [0,2,1,3]\nExplanation: There are a total of 4 courses to take. To take course 3 you should have finished both     \n             courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. \n             So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .
\n\n

Note:

\n\n
    \n\t
  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. \n\t
  3. You may assume that there are no duplicate edges in the input prerequisites.
  4. \n
\n

\u73b0\u5728\u4f60\u603b\u5171\u6709 n \u95e8\u8bfe\u9700\u8981\u9009\uff0c\u8bb0\u4e3a 0 \u5230 n-1\u3002

\n\n

\u5728\u9009\u4fee\u67d0\u4e9b\u8bfe\u7a0b\u4e4b\u524d\u9700\u8981\u4e00\u4e9b\u5148\u4fee\u8bfe\u7a0b\u3002 \u4f8b\u5982\uff0c\u60f3\u8981\u5b66\u4e60\u8bfe\u7a0b 0 \uff0c\u4f60\u9700\u8981\u5148\u5b8c\u6210\u8bfe\u7a0b 1 \uff0c\u6211\u4eec\u7528\u4e00\u4e2a\u5339\u914d\u6765\u8868\u793a\u4ed6\u4eec: [0,1]

\n\n

\u7ed9\u5b9a\u8bfe\u7a0b\u603b\u91cf\u4ee5\u53ca\u5b83\u4eec\u7684\u5148\u51b3\u6761\u4ef6\uff0c\u8fd4\u56de\u4f60\u4e3a\u4e86\u5b66\u5b8c\u6240\u6709\u8bfe\u7a0b\u6240\u5b89\u6392\u7684\u5b66\u4e60\u987a\u5e8f\u3002

\n\n

\u53ef\u80fd\u4f1a\u6709\u591a\u4e2a\u6b63\u786e\u7684\u987a\u5e8f\uff0c\u4f60\u53ea\u8981\u8fd4\u56de\u4e00\u79cd\u5c31\u53ef\u4ee5\u4e86\u3002\u5982\u679c\u4e0d\u53ef\u80fd\u5b8c\u6210\u6240\u6709\u8bfe\u7a0b\uff0c\u8fd4\u56de\u4e00\u4e2a\u7a7a\u6570\u7ec4\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: 2, [[1,0]] \n\u8f93\u51fa: [0,1]\n\u89e3\u91ca: \u603b\u5171\u6709 2 \u95e8\u8bfe\u7a0b\u3002\u8981\u5b66\u4e60\u8bfe\u7a0b 1\uff0c\u4f60\u9700\u8981\u5148\u5b8c\u6210\u8bfe\u7a0b 0\u3002\u56e0\u6b64\uff0c\u6b63\u786e\u7684\u8bfe\u7a0b\u987a\u5e8f\u4e3a [0,1] \u3002
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: 4, [[1,0],[2,0],[3,1],[3,2]]\n\u8f93\u51fa: [0,1,2,3] or [0,2,1,3]\n\u89e3\u91ca: \u603b\u5171\u6709 4 \u95e8\u8bfe\u7a0b\u3002\u8981\u5b66\u4e60\u8bfe\u7a0b 3\uff0c\u4f60\u5e94\u8be5\u5148\u5b8c\u6210\u8bfe\u7a0b 1 \u548c\u8bfe\u7a0b 2\u3002\u5e76\u4e14\u8bfe\u7a0b 1 \u548c\u8bfe\u7a0b 2 \u90fd\u5e94\u8be5\u6392\u5728\u8bfe\u7a0b 0 \u4e4b\u540e\u3002\n     \u56e0\u6b64\uff0c\u4e00\u4e2a\u6b63\u786e\u7684\u8bfe\u7a0b\u987a\u5e8f\u662f [0,1,2,3] \u3002\u53e6\u4e00\u4e2a\u6b63\u786e\u7684\u6392\u5e8f\u662f [0,2,1,3] \u3002\n
\n\n

\u8bf4\u660e:

\n\n
    \n\t
  1. \u8f93\u5165\u7684\u5148\u51b3\u6761\u4ef6\u662f\u7531\u8fb9\u7f18\u5217\u8868\u8868\u793a\u7684\u56fe\u5f62\uff0c\u800c\u4e0d\u662f\u90bb\u63a5\u77e9\u9635\u3002\u8be6\u60c5\u8bf7\u53c2\u89c1\u56fe\u7684\u8868\u793a\u6cd5\u3002
  2. \n\t
  3. \u4f60\u53ef\u4ee5\u5047\u5b9a\u8f93\u5165\u7684\u5148\u51b3\u6761\u4ef6\u4e2d\u6ca1\u6709\u91cd\u590d\u7684\u8fb9\u3002
  4. \n
\n\n

\u63d0\u793a:

\n\n
    \n\t
  1. \u8fd9\u4e2a\u95ee\u9898\u76f8\u5f53\u4e8e\u67e5\u627e\u4e00\u4e2a\u5faa\u73af\u662f\u5426\u5b58\u5728\u4e8e\u6709\u5411\u56fe\u4e2d\u3002\u5982\u679c\u5b58\u5728\u5faa\u73af\uff0c\u5219\u4e0d\u5b58\u5728\u62d3\u6251\u6392\u5e8f\uff0c\u56e0\u6b64\u4e0d\u53ef\u80fd\u9009\u53d6\u6240\u6709\u8bfe\u7a0b\u8fdb\u884c\u5b66\u4e60\u3002
  2. \n\t
  3. \u901a\u8fc7 DFS \u8fdb\u884c\u62d3\u6251\u6392\u5e8f - \u4e00\u4e2a\u5173\u4e8eCoursera\u7684\u7cbe\u5f69\u89c6\u9891\u6559\u7a0b\uff0821\u5206\u949f\uff09\uff0c\u4ecb\u7ecd\u62d3\u6251\u6392\u5e8f\u7684\u57fa\u672c\u6982\u5ff5\u3002
  4. \n\t
  5. \n\t

    \u62d3\u6251\u6392\u5e8f\u4e5f\u53ef\u4ee5\u901a\u8fc7 BFS \u5b8c\u6210\u3002

    \n\t
  6. \n
\n

\u73b0\u5728\u4f60\u603b\u5171\u6709 n \u95e8\u8bfe\u9700\u8981\u9009\uff0c\u8bb0\u4e3a 0 \u5230 n-1\u3002

\n\n

\u5728\u9009\u4fee\u67d0\u4e9b\u8bfe\u7a0b\u4e4b\u524d\u9700\u8981\u4e00\u4e9b\u5148\u4fee\u8bfe\u7a0b\u3002 \u4f8b\u5982\uff0c\u60f3\u8981\u5b66\u4e60\u8bfe\u7a0b 0 \uff0c\u4f60\u9700\u8981\u5148\u5b8c\u6210\u8bfe\u7a0b 1 \uff0c\u6211\u4eec\u7528\u4e00\u4e2a\u5339\u914d\u6765\u8868\u793a\u4ed6\u4eec: [0,1]

\n\n

\u7ed9\u5b9a\u8bfe\u7a0b\u603b\u91cf\u4ee5\u53ca\u5b83\u4eec\u7684\u5148\u51b3\u6761\u4ef6\uff0c\u8fd4\u56de\u4f60\u4e3a\u4e86\u5b66\u5b8c\u6240\u6709\u8bfe\u7a0b\u6240\u5b89\u6392\u7684\u5b66\u4e60\u987a\u5e8f\u3002

\n\n

\u53ef\u80fd\u4f1a\u6709\u591a\u4e2a\u6b63\u786e\u7684\u987a\u5e8f\uff0c\u4f60\u53ea\u8981\u8fd4\u56de\u4e00\u79cd\u5c31\u53ef\u4ee5\u4e86\u3002\u5982\u679c\u4e0d\u53ef\u80fd\u5b8c\u6210\u6240\u6709\u8bfe\u7a0b\uff0c\u8fd4\u56de\u4e00\u4e2a\u7a7a\u6570\u7ec4\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: 2, [[1,0]] \n\u8f93\u51fa: [0,1]\n\u89e3\u91ca: \u603b\u5171\u6709 2 \u95e8\u8bfe\u7a0b\u3002\u8981\u5b66\u4e60\u8bfe\u7a0b 1\uff0c\u4f60\u9700\u8981\u5148\u5b8c\u6210\u8bfe\u7a0b 0\u3002\u56e0\u6b64\uff0c\u6b63\u786e\u7684\u8bfe\u7a0b\u987a\u5e8f\u4e3a [0,1] \u3002
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: 4, [[1,0],[2,0],[3,1],[3,2]]\n\u8f93\u51fa: [0,1,2,3] or [0,2,1,3]\n\u89e3\u91ca: \u603b\u5171\u6709 4 \u95e8\u8bfe\u7a0b\u3002\u8981\u5b66\u4e60\u8bfe\u7a0b 3\uff0c\u4f60\u5e94\u8be5\u5148\u5b8c\u6210\u8bfe\u7a0b 1 \u548c\u8bfe\u7a0b 2\u3002\u5e76\u4e14\u8bfe\u7a0b 1 \u548c\u8bfe\u7a0b 2 \u90fd\u5e94\u8be5\u6392\u5728\u8bfe\u7a0b 0 \u4e4b\u540e\u3002\n     \u56e0\u6b64\uff0c\u4e00\u4e2a\u6b63\u786e\u7684\u8bfe\u7a0b\u987a\u5e8f\u662f [0,1,2,3] \u3002\u53e6\u4e00\u4e2a\u6b63\u786e\u7684\u6392\u5e8f\u662f [0,2,1,3] \u3002\n
\n\n

\u8bf4\u660e:

\n\n
    \n\t
  1. \u8f93\u5165\u7684\u5148\u51b3\u6761\u4ef6\u662f\u7531\u8fb9\u7f18\u5217\u8868\u8868\u793a\u7684\u56fe\u5f62\uff0c\u800c\u4e0d\u662f\u90bb\u63a5\u77e9\u9635\u3002\u8be6\u60c5\u8bf7\u53c2\u89c1\u56fe\u7684\u8868\u793a\u6cd5\u3002
  2. \n\t
  3. \u4f60\u53ef\u4ee5\u5047\u5b9a\u8f93\u5165\u7684\u5148\u51b3\u6761\u4ef6\u4e2d\u6ca1\u6709\u91cd\u590d\u7684\u8fb9\u3002
  4. \n
\n\n

\u63d0\u793a:

\n\n
    \n\t
  1. \u8fd9\u4e2a\u95ee\u9898\u76f8\u5f53\u4e8e\u67e5\u627e\u4e00\u4e2a\u5faa\u73af\u662f\u5426\u5b58\u5728\u4e8e\u6709\u5411\u56fe\u4e2d\u3002\u5982\u679c\u5b58\u5728\u5faa\u73af\uff0c\u5219\u4e0d\u5b58\u5728\u62d3\u6251\u6392\u5e8f\uff0c\u56e0\u6b64\u4e0d\u53ef\u80fd\u9009\u53d6\u6240\u6709\u8bfe\u7a0b\u8fdb\u884c\u5b66\u4e60\u3002
  2. \n\t
  3. \u901a\u8fc7 DFS \u8fdb\u884c\u62d3\u6251\u6392\u5e8f - \u4e00\u4e2a\u5173\u4e8eCoursera\u7684\u7cbe\u5f69\u89c6\u9891\u6559\u7a0b\uff0821\u5206\u949f\uff09\uff0c\u4ecb\u7ecd\u62d3\u6251\u6392\u5e8f\u7684\u57fa\u672c\u6982\u5ff5\u3002
  4. \n\t
  5. \n\t

    \u62d3\u6251\u6392\u5e8f\u4e5f\u53ef\u4ee5\u901a\u8fc7 BFS \u5b8c\u6210\u3002

    \n\t
  6. \n
\n*/\n\n\n/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {number[]}\n */\nvar findOrder = function(numCourses, prerequisites) {\n \n};"} {"doc_id": "01c885f2891e5b9c20eda02ad9dab029", "text": "/*\n

\nGiven a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.\n

\n

Examples:\n

\ns = \"leetcode\"\nreturn 0.\n\ns = \"loveleetcode\",\nreturn 2.\n
\n

\n\n

\nNote: You may assume the string contain only lowercase letters.\n

\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\uff0c\u627e\u5230\u5b83\u7684\u7b2c\u4e00\u4e2a\u4e0d\u91cd\u590d\u7684\u5b57\u7b26\uff0c\u5e76\u8fd4\u56de\u5b83\u7684\u7d22\u5f15\u3002\u5982\u679c\u4e0d\u5b58\u5728\uff0c\u5219\u8fd4\u56de -1\u3002

\n\n

\u6848\u4f8b:

\n\n
\ns = "leetcode"\n\u8fd4\u56de 0.\n\ns = "loveleetcode",\n\u8fd4\u56de 2.\n
\n\n

 

\n\n

\u6ce8\u610f\u4e8b\u9879\uff1a\u60a8\u53ef\u4ee5\u5047\u5b9a\u8be5\u5b57\u7b26\u4e32\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002

\n

\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\uff0c\u627e\u5230\u5b83\u7684\u7b2c\u4e00\u4e2a\u4e0d\u91cd\u590d\u7684\u5b57\u7b26\uff0c\u5e76\u8fd4\u56de\u5b83\u7684\u7d22\u5f15\u3002\u5982\u679c\u4e0d\u5b58\u5728\uff0c\u5219\u8fd4\u56de -1\u3002

\n\n

\u6848\u4f8b:

\n\n
\ns = "leetcode"\n\u8fd4\u56de 0.\n\ns = "loveleetcode",\n\u8fd4\u56de 2.\n
\n\n

 

\n\n

\u6ce8\u610f\u4e8b\u9879\uff1a\u60a8\u53ef\u4ee5\u5047\u5b9a\u8be5\u5b57\u7b26\u4e32\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002

\n*/\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar firstUniqChar = function(s) {\n \n};"} {"doc_id": "0247b8d95fe94097936556515ca2a275", "text": "/*\n

\nGiven a word, you need to judge whether the usage of capitals in it is right or not.\n

\n\n

\nWe define the usage of capitals in a word to be right when one of the following cases holds:\n

    \n
  1. All letters in this word are capitals, like \"USA\".
  2. \n
  3. All letters in this word are not capitals, like \"leetcode\".
  4. \n
  5. Only the first letter in this word is capital if it has more than one letter, like \"Google\".
  6. \n
\nOtherwise, we define that this word doesn't use capitals in a right way.\n

\n\n\n

Example 1:
\n

\nInput: \"USA\"\nOutput: True\n
\n

\n\n

Example 2:
\n

\nInput: \"FlaG\"\nOutput: False\n
\n

\n\n

Note:\nThe input will be a non-empty word consisting of uppercase and lowercase latin letters.\n

\u7ed9\u5b9a\u4e00\u4e2a\u5355\u8bcd\uff0c\u4f60\u9700\u8981\u5224\u65ad\u5355\u8bcd\u7684\u5927\u5199\u4f7f\u7528\u662f\u5426\u6b63\u786e\u3002

\n\n

\u6211\u4eec\u5b9a\u4e49\uff0c\u5728\u4ee5\u4e0b\u60c5\u51b5\u65f6\uff0c\u5355\u8bcd\u7684\u5927\u5199\u7528\u6cd5\u662f\u6b63\u786e\u7684\uff1a

\n\n
    \n\t
  1. \u5168\u90e8\u5b57\u6bcd\u90fd\u662f\u5927\u5199\uff0c\u6bd4\u5982"USA"\u3002
  2. \n\t
  3. \u5355\u8bcd\u4e2d\u6240\u6709\u5b57\u6bcd\u90fd\u4e0d\u662f\u5927\u5199\uff0c\u6bd4\u5982"leetcode"\u3002
  4. \n\t
  5. \u5982\u679c\u5355\u8bcd\u4e0d\u53ea\u542b\u6709\u4e00\u4e2a\u5b57\u6bcd\uff0c\u53ea\u6709\u9996\u5b57\u6bcd\u5927\u5199\uff0c \u6bd4\u5982 "Google"\u3002
  6. \n
\n\n

\u5426\u5219\uff0c\u6211\u4eec\u5b9a\u4e49\u8fd9\u4e2a\u5355\u8bcd\u6ca1\u6709\u6b63\u786e\u4f7f\u7528\u5927\u5199\u5b57\u6bcd\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: "USA"\n\u8f93\u51fa: True\n
\n\n

\u793a\u4f8b 2:

\n\n
\n\u8f93\u5165: "FlaG"\n\u8f93\u51fa: False\n
\n\n

\u6ce8\u610f: \u8f93\u5165\u662f\u7531\u5927\u5199\u548c\u5c0f\u5199\u62c9\u4e01\u5b57\u6bcd\u7ec4\u6210\u7684\u975e\u7a7a\u5355\u8bcd\u3002

\n

\u7ed9\u5b9a\u4e00\u4e2a\u5355\u8bcd\uff0c\u4f60\u9700\u8981\u5224\u65ad\u5355\u8bcd\u7684\u5927\u5199\u4f7f\u7528\u662f\u5426\u6b63\u786e\u3002

\n\n

\u6211\u4eec\u5b9a\u4e49\uff0c\u5728\u4ee5\u4e0b\u60c5\u51b5\u65f6\uff0c\u5355\u8bcd\u7684\u5927\u5199\u7528\u6cd5\u662f\u6b63\u786e\u7684\uff1a

\n\n
    \n\t
  1. \u5168\u90e8\u5b57\u6bcd\u90fd\u662f\u5927\u5199\uff0c\u6bd4\u5982"USA"\u3002
  2. \n\t
  3. \u5355\u8bcd\u4e2d\u6240\u6709\u5b57\u6bcd\u90fd\u4e0d\u662f\u5927\u5199\uff0c\u6bd4\u5982"leetcode"\u3002
  4. \n\t
  5. \u5982\u679c\u5355\u8bcd\u4e0d\u53ea\u542b\u6709\u4e00\u4e2a\u5b57\u6bcd\uff0c\u53ea\u6709\u9996\u5b57\u6bcd\u5927\u5199\uff0c \u6bd4\u5982 "Google"\u3002
  6. \n
\n\n

\u5426\u5219\uff0c\u6211\u4eec\u5b9a\u4e49\u8fd9\u4e2a\u5355\u8bcd\u6ca1\u6709\u6b63\u786e\u4f7f\u7528\u5927\u5199\u5b57\u6bcd\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: "USA"\n\u8f93\u51fa: True\n
\n\n

\u793a\u4f8b 2:

\n\n
\n\u8f93\u5165: "FlaG"\n\u8f93\u51fa: False\n
\n\n

\u6ce8\u610f: \u8f93\u5165\u662f\u7531\u5927\u5199\u548c\u5c0f\u5199\u62c9\u4e01\u5b57\u6bcd\u7ec4\u6210\u7684\u975e\u7a7a\u5355\u8bcd\u3002

\n*/\n\n\n/**\n * @param {string} word\n * @return {boolean}\n */\nvar detectCapitalUse = function(word) {\n \n};"} {"doc_id": "04665eaaeb03c031d1833ed740164913", "text": "/**\n * Performance Review\n * 3 - superstar\n * 2 - meets expectations\n * 1 - needs improvement\n * anything else - wtf?\n */\n\nlet rating = 0;\n\nif (rating === 3) {\n console.log(\"YOU ARE A SUPERSTAR!\");\n} else if (rating === 2) {\n console.log(\"MEETS EXPECTATIONS\");\n} else if (rating === 1) {\n console.log(\"NEEDS IMPROVEMENT\");\n} else {\n // console.log(\"INVALID RATING!\");\n}\n\n//Exemple 2\nlet highScore = 1430;\nlet userScore = 1300;\n\nif (userScore >= highScore) {\n // console.log(`Congrats, you have new high score of ${userScore}`);\n highScore = userScore;\n} else {\n // console.log(\n // `Good Game. Your score of ${userScore} did not beat the high score ${highScore}`\n // );\n}\n\n//exemple 3 - Nestnig Conditionals\nlet password = \"teste321\";\n\nif (password.length >= 6) {\n if (password.indexOf(\" \") === -1) {\n // console.log(\"Valid Password\");\n } else {\n // console.log(\"Password is long enough, but cannot contain spaces\");\n }\n} else {\n // console.log(\"Password must be longer\");\n}\n\n// Exemple 4 - TRUTHY & FALSY VALUES\n/**\n * All values have an inherent truthy or falsy boolean value.\n *\n * FALSY VALUES:\n * false\n * 0\n * \"\" (empty string)\n * null\n * undefined\n * NaN\n * Everything else is TRUTHY.\n */\nlet mystery = 5;\n\nif (mystery) {\n // console.log(\"TRUTHY\");\n} else {\n // console.log(\"FALSY\");\n}\n\n/**\n * LOGICAL OPERATORS\n */\n\n// AND (&&)\nlet passwords = \"minhasenha\";\n\nif (passwords.length >= 8 && passwords.indexOf(\" \") === -1) {\n // console.log(\"VALID PASSWORD\");\n} else {\n // console.log(\"INVALID PASSWORD\");\n}\n\n// exemple 2\nlet num = 3;\nif (num >= 1 && num <= 10) {\n // console.log(\"Number is between 1 and 10\");\n} else {\n // console.log(\"Please guess a number between 1 and 10\");\n}\n\n// exemple 3\n// OR (||)\nlet age = 30;\n\nif (age < 6 || age >= 65) {\n // console.log(\"YOU GET IN FOR FREE\");\n} else {\n // console.log(\"YOU MUST PAYYYY!\");\n}\n\n// exemple 4\nlet color = \"purple\";\n\nif (color === \"purple\" || color === \"lilac\" || color === \"violet\") {\n // console.log(\"GREAT CHOICE\");\n}\n\n// NOT (!)\nlet loggedInUser;\n\nif (!loggedInUser) {\n console.log(\"GET OUT OF HERE\");\n}\n\n// exemple 2\n\nlet flavor = \"grepe\";\n\n// if (flavor !== \"grepe\" && flavor !== \"cherry\") {\n// console.log(\"WE DON'T HAVE THAT FLAVOR!\");\n// }\n\nif (!(flavor === \"grepe\" && flavor === \"cherry\")) {\n console.log(\"WE DON'T HAVE THAT FLAVOR\");\n}\n"} {"doc_id": "04aaf8ac396a622fd9016bb34c000b0b", "text": "// Assignment code here\nfunction generatePassword()\n{\n//Do while loop to prompt for password length for user input.\n do {\n var passlength = window.prompt(\"How long would you like your password to be?\");\n console.log(\"Length of Password: \" + passlength);\n } while (passlength < 8 || passlength > 128)\n\n//Variables for window confirms for each question prompt.\n var passSc = window.confirm(\"Do you want symbols in your password?\");\n var passNM = window.confirm(\"Do you want numerical characters in your password?\");\n var passUC = window.confirm(\"Do you want uppercase characters in your password?\");\n var passLC = window.confirm(\"Do you want lowercase characters in your password?\");\n\n var character = \"\";\n var result = [];\n\n//If statements determining characters for each variable\n if (passSc == true)\n {\n character += \"+-!@#$%^&()?><\";\n console.log(\"passSc is True\");\n }\n if (passNM == true)\n {\n character += \"0123456789\";\n console.log(\"passNM is True\");\n }\n if (passUC == true)\n {\n character += \"ABCDEFGHIJKLMOPQRSTUVWXYZ\";\n console.log(\"passUC is True\");\n }\n if (passLC == true)\n {\n character += \"abcdefghijklmnopqrstuvwxyz\";\n console.log(\"passLC is True\");\n } \n\n console.log(character)\n\n for (var i = 0; i < passlength; i++)\n {\n result += character.charAt(Math.floor(Math.random() * character.length));\n } \n\n return result;\n}\n// code to display result\n\n\n// Get references to the #generate element\nvar generateBtn = document.querySelector(\"#generate\");\n\n// Write password to the #password input\nfunction writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}\n\n// Add event listener to generate button\ngenerateBtn.addEventListener(\"click\", writePassword);\n"} {"doc_id": "06062562866313c17977d691dfd2f17a", "text": "/*\n

Given a positive integer n, return the number of all possible attendance records with length n, which will be regarded as rewardable. The answer may be very large, return it after mod 109 + 7.

\n\n

A student attendance record is a string that only contains the following three characters:

\n\n

\n

    \n
  1. 'A' : Absent.
  2. \n
  3. 'L' : Late.
  4. \n
  5. 'P' : Present.
  6. \n
\n

\n\n

\nA record is regarded as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

\n\n

Example 1:
\n

\nInput: n = 2\nOutput: 8 \nExplanation:\nThere are 8 records with length 2 will be regarded as rewardable:\n\"PP\" , \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\nOnly \"AA\" won't be regarded as rewardable owing to more than one absent times. \n
\n

\n\n

Note:\nThe value of n won't exceed 100,000.\n

\n\n\n

\u7ed9\u5b9a\u4e00\u4e2a\u6b63\u6574\u6570 n\uff0c\u8fd4\u56de\u957f\u5ea6\u4e3a n \u7684\u6240\u6709\u53ef\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\u7684\u51fa\u52e4\u8bb0\u5f55\u7684\u6570\u91cf\u3002 \u7b54\u6848\u53ef\u80fd\u975e\u5e38\u5927\uff0c\u4f60\u53ea\u9700\u8fd4\u56de\u7ed3\u679cmod 109 + 7\u7684\u503c\u3002

\n\n

\u5b66\u751f\u51fa\u52e4\u8bb0\u5f55\u662f\u53ea\u5305\u542b\u4ee5\u4e0b\u4e09\u4e2a\u5b57\u7b26\u7684\u5b57\u7b26\u4e32\uff1a

\n\n
    \n\t
  1. 'A' : Absent\uff0c\u7f3a\u52e4
  2. \n\t
  3. 'L' : Late\uff0c\u8fdf\u5230
  4. \n\t
  5. 'P' : Present\uff0c\u5230\u573a
  6. \n
\n\n

\u5982\u679c\u8bb0\u5f55\u4e0d\u5305\u542b\u591a\u4e8e\u4e00\u4e2a'A'\uff08\u7f3a\u52e4\uff09\u6216\u8d85\u8fc7\u4e24\u4e2a\u8fde\u7eed\u7684'L'\uff08\u8fdf\u5230\uff09\uff0c\u5219\u8be5\u8bb0\u5f55\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\u7684\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: n = 2\n\u8f93\u51fa: 8 \n\u89e3\u91ca\uff1a\n\u67098\u4e2a\u957f\u5ea6\u4e3a2\u7684\u8bb0\u5f55\u5c06\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\uff1a\n"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"\n\u53ea\u6709"AA"\u4e0d\u4f1a\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\uff0c\u56e0\u4e3a\u7f3a\u52e4\u6b21\u6570\u8d85\u8fc7\u4e00\u6b21\u3002
\n\n

\u6ce8\u610f\uff1an \u7684\u503c\u4e0d\u4f1a\u8d85\u8fc7100000\u3002

\n

\u7ed9\u5b9a\u4e00\u4e2a\u6b63\u6574\u6570 n\uff0c\u8fd4\u56de\u957f\u5ea6\u4e3a n \u7684\u6240\u6709\u53ef\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\u7684\u51fa\u52e4\u8bb0\u5f55\u7684\u6570\u91cf\u3002 \u7b54\u6848\u53ef\u80fd\u975e\u5e38\u5927\uff0c\u4f60\u53ea\u9700\u8fd4\u56de\u7ed3\u679cmod 109 + 7\u7684\u503c\u3002

\n\n

\u5b66\u751f\u51fa\u52e4\u8bb0\u5f55\u662f\u53ea\u5305\u542b\u4ee5\u4e0b\u4e09\u4e2a\u5b57\u7b26\u7684\u5b57\u7b26\u4e32\uff1a

\n\n
    \n\t
  1. 'A' : Absent\uff0c\u7f3a\u52e4
  2. \n\t
  3. 'L' : Late\uff0c\u8fdf\u5230
  4. \n\t
  5. 'P' : Present\uff0c\u5230\u573a
  6. \n
\n\n

\u5982\u679c\u8bb0\u5f55\u4e0d\u5305\u542b\u591a\u4e8e\u4e00\u4e2a'A'\uff08\u7f3a\u52e4\uff09\u6216\u8d85\u8fc7\u4e24\u4e2a\u8fde\u7eed\u7684'L'\uff08\u8fdf\u5230\uff09\uff0c\u5219\u8be5\u8bb0\u5f55\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\u7684\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: n = 2\n\u8f93\u51fa: 8 \n\u89e3\u91ca\uff1a\n\u67098\u4e2a\u957f\u5ea6\u4e3a2\u7684\u8bb0\u5f55\u5c06\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\uff1a\n"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"\n\u53ea\u6709"AA"\u4e0d\u4f1a\u88ab\u89c6\u4e3a\u53ef\u5956\u52b1\uff0c\u56e0\u4e3a\u7f3a\u52e4\u6b21\u6570\u8d85\u8fc7\u4e00\u6b21\u3002
\n\n

\u6ce8\u610f\uff1an \u7684\u503c\u4e0d\u4f1a\u8d85\u8fc7100000\u3002

\n*/\n\n\n/**\n * @param {number} n\n * @return {number}\n */\nvar checkRecord = function(n) {\n \n};"} {"doc_id": "06ce34220a58450eb6119a3fe7829177", "text": "// \"use strict\";\n// single line comment\n\n/* \n multi\n line\n comment\n*/\n\n/**\n * Documentation comments\n * are multi line\n */\n\n/*\n JS Types:\n Primitives:\n - string\n - number\n - bigint\n - boolean\n - symbol\n - undefined\n - null\n\n Objects:\n - object\n - array\n - function (first-class members)\n\n \n*/\n\n// standard function declaration\nfunction a() {\n console.log('this is a named function declaration');\n}\n\na();\nconsole.log(a);\n\n// anonymous function declaration\nlet x = function() {\n console.log('this is an anonymous function assigned to a variable named \"x\".');\n}\n\nx();\nconsole.log(x);\n\n// IIFEs (immediately invoked function expressions)\n(function() {\n console.log('this is an immediately invoked function expression!')\n})();\n\n/*\n Variable declarative keywords\n - var\n - let (introduced in ES6)\n - const (introduced in ES6)\n\n Variable Scopes:\n - global\n - function/local\n - block\n - lexical (closures)\n*/\n\nfunction varScope() {\n\n console.log('line 70: ' + greeting);\n\n if (5 > 4) {\n // the variable \"greeting\" is hoisted to the top of the function scope\n var greeting = \"hello\"; \n console.log('line 74: ' + greeting);\n }\n\n console.log('line 77: ' + greeting);\n\n}\n\nvarScope();\n\nfunction letScope() {\n\n // throws a ReferenceError because \"greeting\" is not hoisted\n // console.log('line 86: ' + greeting); \n\n if (5 > 4) {\n // the variable \"greeting\" is NOT hoisted (because we used let)\n let greeting = \"hello\"; \n console.log('line 91: ' + greeting);\n\n if (4 < 5) {\n console.log('line 94: ' + greeting);\n }\n }\n\n // \"greeting\"is not visible here because let/const are scoped to the block in which they are declared\n // console.log('line 98: ' + greeting);\n\n}\n\nletScope();\n\nfunction constScope() {\n console.log(constantGreeting);\n const constantGreeting = \"hola!\";\n}\n\n// Cannot reference const before declaration, it is not hoisted.\n// constScope();\n\n\n// function hoisting\nmyFunction()\nfunction myFunction() {\n console.log('this is my function!');\n}\n\n\n// otherFunction();\nvar otherFunction = function() {\n console.log('this is another function');\n}\n\n// more on const\n// const y; // you must initialize const variables when declaring them\n\n// const variable \nconst y = 42;\n// y = 43; // once initialized, const variables can never be reassigned\n\nconst immutableMaybe = {\n someValue: 10,\n anotherValue: 'test',\n nestedObj: {\n nestedValue: 100\n }\n};\n\n// not allowed, for obvious reasons (reassigning a const variable)\n// immutableMaybe = {};\n\nconsole.log(immutableMaybe);\n\nimmutableMaybe.someValue = 11;\n\nconsole.log(immutableMaybe);\n\n// basic object\nlet myObject = {\n a: 'a',\n b: 2,\n c: true,\n d: function() {\n console.log('d');\n },\n e() {\n console.log('e');\n },\n 'some property': 'some value'\n}\n\nmyObject.e();\nmyObject.d();\n\nconsole.log(myObject.a); // dot notation for accessing object members\nconsole.log(myObject['b']); // bracket notation for accessing object members\nconsole.log(myObject['some property']);\n\n\n// old-school way of creating a JS \"class\"\nfunction Car(model) {\n this.model = model;\n this.color = 'silver';\n this.year = '2015';\n\n // this.toString = function() {\n // console.log(this.model + ', ' + this.color + ', ' + this.year);\n // }\n}\n\n// to properly overwrite the toString method, we need to access the prototype object within our Car \"class\"\nCar.prototype.toString = function() {\n console.log(`${this.model}, ${this.color}, ${this.year}`);\n}\n\nlet myCar = new Car('Nissan Rogue');\nconsole.log(myCar);\nmyCar.toString();\n\nCar.prototype.toString = function() {\n console.log(`${this.model}, ${this.color}, ${this.year}`, `${4 + 2 + 3}`); // template literals\n}\n\nlet yourCar = new Car('Honda Civic');\nconsole.log(yourCar);\nyourCar.toString();\n\n// ES6 Class syntax (sugar syntax)\nclass Truck {\n\n // only one constructor allow in ES6 class syntax\n constructor(model, year, color = 'silver') {\n this.model = model;\n this.year = year;\n this.color = color;\n }\n\n that = this;\n\n squeal() {\n console.log(this == this.that);\n console.log('SQUUUUUUEAK');\n }\n\n beep = function() {\n console.log(this == this.that);\n console.log(\"BEEEEEP!\");\n }\n\n honk = () => {\n console.log(this == this.that);\n console.log('HONK!');\n }\n\n}\n\nlet myTruck = new Truck('Toyota Tacoma', 2020, 'black');\nconsole.log(myTruck);\nmyTruck.beep();\nmyTruck.honk();\nmyTruck.squeal();\n\n// Arrays\nlet myArr = [1, 2, 3];\nlet crazyArray = [1, true, 'hello', new Car(), new Truck(), function () { console.log ('whut?!')}];\n\nconsole.log(myArr[0]); // 1\n\n// passing a arrow function to another function/method\nlet squaredValues = myArr.map(val => {\n return Math.pow(val, 2);\n});\n\nconsole.log(squaredValues);\n\nconsole.log(this); // in Node this = {}, in the browser it would = the Window object\n\n// creates its own 'this', which is the global NodeJS object\nfunction a() {\n console.log(this); // this == Object [global] {...} (provided by NodeJS)\n}\na();\n\n// creates its own 'this', which is the global NodeJS object\nlet b = function() {\n console.log(this); // this == Object [global] {...} (provided by NodeJS)\n}\nb();\n\n// does not create it own 'this', instead it inherits the 'this' from the outer scope.\nlet c = () => {\n console.log(this);\n}\nc();\n\n\nfunction D() {\n this.x = 1;\n this.y = 2;\n this.z = 3;\n console.log(this); // this == D {...}\n}\nlet d = new D();\n\nfunction E() {\n this.x = 1;\n\n console.log(this); // this == F {...}\n\n let that = this;\n\n const b = () => {\n console.log(this == that);\n }\n\n b();\n\n const c = function () {\n console.log(this == that);\n }\n\n c();\n}\n\nlet e = new E();\n\n/*\n Truthy and Falsy\n\n - due to type coercion all values in JS can be interpreted as booleans\n - just remember: there are only 6 falsy values:\n - false\n - 0\n - NaN\n - null \n - undefined\n - \"\", '', ``\n*/\n\nconsole.log(10 / 0);\nconsole.log('hello ' + 3); // type coercion\nconsole.log('hello' - 3); // NaN\nconsole.log('hello ' * 3); // NaN\nconsole.log(('hello' - 3) == ('hello' - 3)); // surprisingly false, because...\nconsole.log(NaN == NaN); // false\nconsole.log(typeof(NaN)); // not a number is a number!\nconsole.log('2' == 2); // comparison operator that performs type coercion\nconsole.log('2' === 2); // comparison operator that DOES NOT perform type coercion\n\nlet username = {};\nlet password = 'password';\n\nif (username && password) {\n login(username, password);\n} else {\n console.log('you provided empty or null values!');\n}\n\nfunction login(un, pw) {\n console.log(`Logging in: ${un} with ${pw}`);\n}\n\nconsole.log(([]+{}+!{}));\n\nconsole.log(!!\"dsgafgkj.usgarfa.hsgfjavf\");"} {"doc_id": "06d756a58ead6584829e9cd3eadcf860", "text": "/* lab 11_rps\n\n* When you click a button, the computer picks a move with the getRandomPlay() function\n* Update the scoreboard in the event of a win\n* Display the player moves and who won below the scoreboard\n* See this website for what the solution would look like:\n* https://pages.git.generalassemb.ly/fewd201810/class-resources/teacher/11_rps/\n*/\n\nlet yourScore = 0;\nlet computerScore = 0;\n\n// use this function to figure out how the computer plays each move\n// DO NOT EDIT THIS FUNCTION. just use it in the code you right\nfunction getRandomPlay() {\n // define the possible plays in an array of strings\n let plays = ['rock', 'paper', 'scissors'];\n // randomly select one of those options\n let play = plays[Math.floor(Math.random() * plays.length)];\n // return the randomly selected option\n return play;\n}\n\n\n$('#rockButton').click(function(){\n let computerResult = getRandomPlay();\n $('#choice').html(\"The computer plays \"+ computerResult+\" you plays rock\");\n if (computerResult === \"paper\"){\n console.log(\"you lose\");\n computerScore += 1;\n $('#computerScore').html(computerScore);\n $('#status').html(\"you lose\");\n } else if(computerResult === \"scissors\"){\n console.log(\"you win\");\n yourScore += 1;\n $('#humanScore').html(yourScore);\n $('#status').html(\"you win\");\n } else if(computerResult === \"rock\"){\n console.log(\"you tie\");\n $('#humanScore').html(yourScore);\n $('#status').html(\"you tie\");\n }\n })\n\n\n $('#paperButton').click(function(){\n let computerResult = getRandomPlay();\n $('#choice').html(\"The computer plays \"+ computerResult+\" you plays paper\");\n if (computerResult === \"scissors\"){\n console.log(\"you lose\");\n computerScore += 1;\n $('#computerScore').html(computerScore);\n $('#status').html(\"you lose\");\n }else if(computerResult === \"rock\"){\n console.log(\"you win\");\n yourScore += 1;\n $('#humanScore').html(yourScore);\n $('#status').html(\"you win\");\n }else if(computerResult === \"paper\"){\n console.log(\"you tie\");\n $('#humanScore').html(yourScore);\n $('#status').html(\"you tie\");\n }\n })\n\n $('#scissorsButton').click(function(){\n let computerResult = getRandomPlay();\n $('#choice').html(\"The computer plays \"+ computerResult+\" you plays scissors\");\n if (computerResult === \"rock\"){\n console.log(\"you lose\");\n computerScore += 1;\n $('#computerScore').html(computerScore);\n $('#status').html(\"you lose\");\n }else if(computerResult === \"paper\"){\n console.log(\"you win\");\n yourScore += 1;\n $('#humanScore').html(yourScore);\n $('#status').html(\"you win\");\n }else if(computerResult === \"scissors\"){\n console.log(\"you tie\");\n $('#humanScore').html(yourScore);\n $('#status').html(\"you tie\");\n }\n })\n//human play stone\n//cpu: getRandomPlay\n// if (play= paper) print you lose/ and add one to computer score\n//\n"} {"doc_id": "072f2d4ff0b1ae7845b62a4f934dd0bb", "text": "// Promise\n// async code\n\n//Exocution context\n// global -> functions\n\n//global --> this\n\n//Event Queue\n\n// 1. onClick\n// 2. setSitmeOut\n// 3. onHover\n\n// JS runs with 2 phase\n// Phase 1. Creation Phase\n// Pahse 2. Execution Phase\n\n\n// console.log(x);\n \n// var x = 0;\n\n// function x(){\n\n// };\n\n//x();\n\n// foo();\n\n//function declaration\n// function foo(){\n// console.log(\"foo\")\n// }\n\n//bar(); undefined is not a function\n\n//function expression\n// var bar = function(){\n// console.log(\"bar\");\n// }\n\n//----------Promse------------\n\n//1. Pending 2. Rejected 3. Resolved\n\nconst promise = new Promise(function(resolve, reject){\n setTimeout(()=>{\n resolve(\"Sucsess!!\")\n }, 500);\n\n});\n\npromise.then((result)=>{\n console.log(result);\n return \"some other calculated result!\"\n})\n.then(result=>console.log(result))\n.then(result=>{\n let err = new Error();\n err.message = \"error message\";\n throw err;\n})\n.catch( (e)=> {\n console.error(e.message);\n})\n\nfor(let i = 0; i< 10000; i++){\n console.log(i);\n}\n \n"} {"doc_id": "074197b839e4fd801ae10eded846de8a", "text": " //-------------Filter #01---------------//\n// Filtra o array devolvendo OUTRO array com os elementos que tenham as caracter\u00edsticas que procuramos\n// Difrente de 'map' que retorna um array com o mesmo n\u00famero de elementos, por\u00e9m com modifica\u00e7\u00f5es, fun\u00e7\u00e3o 'filter' pode retornar quantidade menor de elementos, sem modifica\u00e7\u00f5es.\n//Tem 4 par\u00e2metros, fun\u00e7\u00e3o callback (value, index, array) e this (que \u00e9 opcional))\n\n \n \n const produtos = [\n { nome: 'Notebook', preco: 2499, fragil: true },\n { nome: 'Ipad Pro', preco: 4199, fragil: true },\n { nome: 'Copo de Vidro', preco: 12.49, fragil: true },\n { nome: 'Copo de Pl\u00e1stico', preco: 18.99, fragil: false }\n ]\n\n console.log(produtos.filter(function(p){ // 'p' primeiro par\u00e2metro 'callback'\n return p.preco >= 500 & p.fragil\n } ))\n/*\n[\n { nome: 'Notebook', preco: 2499, fragil: true },\n { nome: 'Ipad Pro', preco: 4199, fragil: true }\n]\n*/\n\n const prodCaro = produto => produto.preco >= 500\n const prodFragil = produto => produto.fragil \n // repare que por 'fragil' ser uma chave com valor bollean, n\u00e3o necessita de operador.\n\n console.log(produtos.filter(prodCaro).filter(prodFragil))\n /*\n[\n { nome: 'Notebook', preco: 2499, fragil: true },\n { nome: 'Ipad Pro', preco: 4199, fragil: true }\n]\n*/"} {"doc_id": "07c0a0dd0a3d1596999e24afdc5caaef", "text": "// Funciones\n\n// Las funciones son las tareas o sentencias que va a llevar a cabo el navegador. Existen 2 tipos de funciones\n// 1) Declarativas\n// 2) De expresi\u00f3n\n// Ambas pueden llevar par\u00e1metros, que son los datos que necesitan para ejecutarse.\n// Cada par\u00e1metro va separado por una coma.\n// Cada instrucci\u00f3n que tenga la funci\u00f3n debe terminar con ; .\n// Si queremos que una funci\u00f3n nos d\u00e9 un numero o dato tenemos que usar la siguiente sintaxis:\n\n// return El dato que queremos que nos d\u00e9;\n\n// Las funciones declarativas tienen la siguiente sintaxis:\n\n// function Nombre de la funci\u00f3n (Par\u00e1metros de la funci\u00f3n) {Instrucciones}\n\n// Un ejemplo de una funci\u00f3n puede ser una suma:\n\n// _\n// function suma (a,b) {return a+b;}_\n\n// Las funciones de expresi\u00f3n son aquellas que guardamos en una variable, por lo tanto, no es necesario nombrarlas y tienen la siguiente sintaxis:\n\n// _var Nombre de la variable = function(Parametros){Instrucciones}.\n// _\n\n// Un ejemplo de una funci\u00f3n de expresi\u00f3n ser\u00eda:\n\n// var suma = function(a,b){return a+b;}\n\n// Para ejecutar las funciones debemos usar la siguiente sintaxis:\n\n// _Nombre de la funcion(Parametros funci\u00f3n); _\n\n// Si la funci\u00f3n no tiene ning\u00fan par\u00e1metro, \u00fanicamente se escribe:\n\n// _Nombre de la funci\u00f3n(); _\n\n// una funcion que tambien necesita son parametros los que va a utilizar\n//FUNCION DECLARATIVA\n//==================== la funcion va a guardar ciertos valores\nfunction miFuncion(){\n return 3; \n}\nmiFuncion(); //llamar la funcion\n//Ejemplo funcion declarativa\nfunction saludarEstudiantes(estudiante){\n console.log(estudiante);\n}\nsaludarEstudiantes(\"Jimmy\");\n//Ejemplo funcion cadena de texto\nfunction saludarEstudiantes(estudiante){\n console.log(`Hola ${estudiante}`);\n}\nsaludarEstudiantes(\"Jimmy\");\n//FUNCION EXPRESION\n//================== variables tambien puede guardar otro tipo de valores, una varible que almacena una funcion, conocidad tambien como funciones anonimas.\nvar miFuncion = function(a,b){\n return a + b;\n}\nmiFuncion();\n\n//Ejemplo de return\nfunction sumar(a,b){\n var resultado = a + b;\n return resultado;\n}\nsumar (1,2);\n\n// Cuando hablamos de funciones en JavaScript, tenemos dos tipos de funciones: Funciones Declarativas (function declaration / function statement) y Expresiones de funci\u00f3n (function expression / funciones an\u00f3nimas).\n// Funciones Declarativas:\n\n// En las funciones declarativas, utilizamos la palabra reservada function al inicio para poder declarar la funci\u00f3n:\nfunction saludar(nombre) {\n\tconsole.log(`Hola ${nombre}`);\n}\nsaludar('Diego');\n\n// Expresi\u00f3n de funci\u00f3n:\n\n// En la expresi\u00f3n de funci\u00f3n, la declaraci\u00f3n se inicia con la palabra reservada var, donde se generar\u00e1 una variable que guardar\u00e1 una funci\u00f3n an\u00f3nima.\nvar nombre = function(nombre){\n console.log(`Hola ${nombre}`)\n}\nnombre('Diego');\n\n// En la expresi\u00f3n de funci\u00f3n, la funci\u00f3n podr\u00eda o no llevar nombre, aunque es m\u00e1s com\u00fan que se hagan an\u00f3nimas.\n// Diferencias:\n\n// A las funciones declarativas se les aplica hoisting, y a la expresi\u00f3n de funci\u00f3n, no. Ya que el hoisting solo se aplica en las palabras reservadas var y function.\n\n// Lo que quiere decir que con las funciones declarativas, podemos mandar llamar la funci\u00f3n antes de que \u00e9sta sea declarada, y con la expresi\u00f3n de funci\u00f3n, no, tendr\u00edamos que declararla primero, y despu\u00e9s mandarla llamar."} {"doc_id": "0826f7475d512e4ee521e68236ef2764", "text": "// JS Functions creation\n\n// 1.Cryptos Storage\nlet cryptosList = ['crypto 1', 'crypto 2', 'crypto 3'];\nconsole.log('start:', cryptosList); \n\n// 2.Cryptos Display\nfunction cryptosDisplay() {\n console.log(cryptosList);\n}\n\n// 3.Add new cryptos\nfunction addCryptos(crypto) {\n cryptosList.push(crypto);\n cryptosDisplay(); \n}\n\n// 4.Change cryptos\nfunction changeCryptos(index, value) {\n cryptosList[index] = value;\n cryptosDisplay();\n}\n\n// 5.Delete crypto\nfunction deleteCrypto(index) {\n cryptosList.splice(index,1);\n cryptosDisplay();\n}\n// JS objects creation\n\nlet cryptos = {\n // 1. list\n listCrypto: ['crypto 1', 'crypto 2', 'crypto 3'],\n // 2. Display\n displayCryptos: function() {\n console.log(this.listCrypto);\n },\n // 3. Add\n addCryptos: function(crypto) {\n this.listCrypto.push(crypto);\n this.displayCryptos();\n },\n\n // 4. Change\n changeCryptos: function(index, value) {\n this.listCrypto[index] = value;\n this.displayCryptos();\n },\n\n //5. Delete\n deleteCrypto: function(index) {\n this.listCrypto.splice(index,1);\n this.displayCryptos();\n }\n\n};\n\nconsole.log('cryptos object: ', cryptos);"} {"doc_id": "091185ad66f847981340d7945af60fe9", "text": "\"use strict\";\r\n/*\r\nrunning lite-srver\r\n*/\r\n// console.log(\"This is a ts file\");\r\n/*\r\nadding types to simple functions\r\n*/\r\n// {\r\n// function add(num1: number, num2: number): number {\r\n// \treturn num1 + num2;\r\n// };\r\n// const num1 = 20,\r\n// \tnum2 = 8;\r\n// const result = add(num1, num2);\r\n// console.log(result);\r\n// }\r\n/*\r\nTypes (Number, Boolean, String...)\r\n*/\r\n// {\r\n// \tfunction add(num1: number, num2: number, showresult: boolean, phrase: string): number | void {\r\n// \t\tif (showresult) {\r\n// \t\t\tconsole.log(phrase, num1 + num2);\r\n// \t\t} else {\r\n// \t\t\treturn num1 + num2;\r\n// \t\t}\r\n// \t};\r\n// \tconst num1 = 20,\r\n// \t\tnum2 = 8,\r\n// \t\tprintResult = true,\r\n// \t\tresultPhrase = \"The result is \";\r\n// \tadd(num1, num2, printResult, resultPhrase);\r\n// \t/*\r\n// \t\tObject\r\n// \t*/\r\n// \t{\r\n// \t\t//not recomended\r\n// \t\tconst person: {\r\n// \t\t\tname: string;\r\n// \t\t\tage: number;\r\n// \t\t} = {\r\n// \t\t\tname: \"Paddington\",\r\n// \t\t\tage: 23\r\n// \t\t};\r\n// \t\tconsole.log(\"Object\", person.name);\r\n// \t\t//recomended\r\n// \t\tconst person1 = {\r\n// \t\t\tname: \"Nick\",\r\n// \t\t\tage: 23\r\n// \t\t};\r\n// \t\tconsole.log(\"Object\", person1.name);\r\n// \t}\r\n// \t/*\r\n// \tArrays\r\n// \t*/\r\n// \t{\r\n// \t\tconst person3 = {\r\n// \t\t\tname: \"Nick\",\r\n// \t\t\tage: 23,\r\n// \t\t\thobbies: [\"sports\", \"cooking\"]\r\n// \t\t};\r\n// \t\tlet favActivities: string[];\r\n// \t\tfavActivities = [\"swimming\"];\r\n// \t\tconsole.log(\"Arrys\", person3.hobbies, favActivities);\r\n// \t\t//allows explicit functions to run as it knows the type of varible\r\n// \t\tfor (const hobby of person3.hobbies) {\r\n// \t\t\tconsole.log(\"Arrys\", hobby.toUpperCase());\r\n// \t\t}\r\n// \t}\r\n// \t/*\r\n// \tTuple fixed length, fixed type arrrays (does not exist in JS but does in some other programming languages)\r\n// \t*/\r\n// \t{\r\n// \t\t//ts assumes it as this and allows the following modifications which aere not acceptable\r\n// \t\tconst person4: {\r\n// \t\t\tname: string;\r\n// \t\t\tage: number;\r\n// \t\t\thobbies: string[];\r\n// \t\t\trole: (number | string)[]\r\n// \t\t} = {\r\n// \t\t\tname: \"Nick\",\r\n// \t\t\tage: 23,\r\n// \t\t\thobbies: [\"sports\", \"cooking\"],\r\n// \t\t\trole: [2, 'author']\r\n// \t\t};\r\n// \t\tperson4.role.push(\"admin\"); //still works but not ideal\r\n// \t\tperson4.role[1] = (1); //still works but not ideal\r\n// \t\tconsole.log(\"Tuple\", person4);\r\n// \t\t//ts assumes it as this and allows the following modifications which aere not acceptable\r\n// \t\tconst person5: {\r\n// \t\t\tname: string;\r\n// \t\t\tage: number;\r\n// \t\t\thobbies: string[];\r\n// \t\t\trole: [number, string] //tells ts that first element is a number and second is a string\r\n// \t\t} = {\r\n// \t\t\tname: \"Nick\",\r\n// \t\t\tage: 23,\r\n// \t\t\thobbies: [\"sports\", \"cooking\"],\r\n// \t\t\trole: [2, 'author']\r\n// \t\t};\r\n// \t\tperson5.role.push(\"admin\"); //still works but not ideal as push works in tupleand can push any value\r\n// \t\t// person5.role[1] = (1); //now throws an error\r\n// \t\tconsole.log(\"Tuple\", person5)\r\n// \t}\r\n// \t/*\r\n// \tEnum exists in other programming languages but not in JS\r\n// \t*/\r\n// \t{\r\n// \t\t// default enum\r\n// \t\tenum Roles {\r\n// \t\t\tADMIN, READ_ONLY, AUTHOR\r\n// \t\t}; //assigns 0, 1, 2 as keys to the enum\r\n// \t\tconst person6 = {\r\n// \t\t\tname: \"Nick\",\r\n// \t\t\tage: 23,\r\n// \t\t\thobbies: [\"sports\", \"cooking\"],\r\n// \t\t\trole: Roles.ADMIN\r\n// \t\t};\r\n// \t\tconsole.log(\"Enum\", person6)\r\n// \t\tif (person6.role === Roles.AUTHOR) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is Author\");\r\n// \t\t} else if (person6.role === Roles.ADMIN) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is Admin\");\r\n// \t\t} else if (person6.role === Roles.READ_ONLY) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is readOnly\");\r\n// \t\t}\r\n// \t\t// custom enum\r\n// \t\tenum Roles1 {\r\n// \t\t\tADMIN = 5, READ_ONLY, AUTHOR\r\n// \t\t}; //assigns 5, 6, 7 as keys to the enum\r\n// \t\tconst person7 = {\r\n// \t\t\tname: \"Nick\",\r\n// \t\t\tage: 23,\r\n// \t\t\thobbies: [\"sports\", \"cooking\"],\r\n// \t\t\trole: Roles1.ADMIN\r\n// \t\t};\r\n// \t\tconsole.log(\"Enum\", person7)\r\n// \t\tif (person7.role === Roles1.AUTHOR) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is Author\");\r\n// \t\t} else if (person7.role === Roles1.ADMIN) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is Admin\");\r\n// \t\t} else if (person7.role === Roles1.READ_ONLY) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is readOnly\");\r\n// \t\t}\r\n// \t\t// custom enum\r\n// \t\tenum Roles2 {\r\n// \t\t\tADMIN = \"Administrator\",\r\n// \t\t\tREAD_ONLY = 6,\r\n// \t\t\tAUTHOR = 100\r\n// \t\t}; //assigns 5, 6, 7 as keys to the enum\r\n// \t\tconst person8 = {\r\n// \t\t\tname: \"Nick\",\r\n// \t\t\tage: 23,\r\n// \t\t\thobbies: [\"sports\", \"cooking\"],\r\n// \t\t\trole: Roles2.ADMIN\r\n// \t\t};\r\n// \t\tconsole.log(\"Enum\", person8)\r\n// \t\tif (person8.role === Roles2.AUTHOR) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is Author\");\r\n// \t\t} else if (person8.role === Roles2.ADMIN) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is Admin\");\r\n// \t\t} else if (person8.role === Roles2.READ_ONLY) {\r\n// \t\t\tconsole.log(\"Enum\", \"role is readOnly\");\r\n// \t\t}\r\n// \t}\r\n// \t/*\r\n// \tAny is the most flexible as it does not tell ts anything and allow any type for the variable\r\n// \tnot recomended to use as its same to vanila js and does not do an ts checks\r\n// \t*/\r\n// }\r\n/*\r\n Exploring union type\r\n*/\r\n// {\r\n// \t//should work with numbers and strings\r\n// \tfunction combnine(num1: number | string,\r\n// \t\tnum2: number | string,\r\n// \t\tresultType: string): number | string {\r\n// \t\tlet result: number | string;\r\n// \t\t//sometines runtime checks might be required when using union types as ts does not know about the exact type of input from the union\r\n// \t\tif (typeof num1 === \"number\" && typeof num2 === \"number\") {\r\n// \t\t\tresult = num1 + num2;\r\n// \t\t} else {\r\n// \t\t\tresult = num1.toString() + num2.toString();\r\n// \t\t}\r\n// \t\tif (resultType === \"as-string\") {\r\n// \t\t\treturn result.toString();\r\n// \t\t} else {\r\n// \t\t\treturn +result;\r\n// \t\t}\r\n// \t};\r\n// \tconst combineAges = combnine(\"12\", \"23\", \"as-number\");\r\n// \tconsole.log(\"union type\", combineAges);\r\n// \tconst combinestr = combnine(12, 23, \"as-string\");\r\n// \tconsole.log(\"union type\", combinestr);\r\n// \tconst combinestr2 = combnine(\"Amit\", \"23\", \"as-string\");\r\n// \tconsole.log(\"union type\", combinestr2);\r\n// \t//literal Strings\r\n// \t//does not allow any other value other than as-number or as-string for resultType\r\n// \tfunction combnine1(num1: number | string,\r\n// \t\tnum2: number | string,\r\n// \t\tresultType: \"as-number\" | \"as-string\"): number | string {\r\n// \t\tlet result1: number | string;\r\n// \t\t//sometines runtime checks might be required when using union types as ts does not know about the exact type of input from the union\r\n// \t\tif (typeof num1 === \"number\" && typeof num2 === \"number\") {\r\n// \t\t\tresult1 = num1 + num2;\r\n// \t\t} else {\r\n// \t\t\tresult1 = num1.toString() + num2.toString();\r\n// \t\t}\r\n// \t\tif (resultType === \"as-string\") {\r\n// \t\t\treturn result1.toString();\r\n// \t\t} else {\r\n// \t\t\treturn +result1;\r\n// \t\t}\r\n// \t};\r\n// \tconst combineAges1 = combnine1(\"12\", \"23\", \"as-number\");\r\n// \tconsole.log(\"literal type\", combineAges1);\r\n// \tconst combinestr3 = combnine1(12, 23, \"as-string\");\r\n// \tconsole.log(\"literal type\", combinestr3);\r\n// \tconst combinestr4 = combnine1(\"Amit\", \"23\", \"as-string\");\r\n// \tconsole.log(\"literal type\", combinestr4);\r\n// \t//type alias\r\n// \ttype Combinable = number | string\r\n// \tfunction combnine2(num1: Combinable,\r\n// \t\tnum2: Combinable,\r\n// \t\tresultType: \"as-number\" | \"as-string\"): Combinable {\r\n// \t\tlet result1: Combinable;\r\n// \t\t//sometines runtime checks might be required when using union types as ts does not know about the exact type of input from the union\r\n// \t\tif (typeof num1 === \"number\" && typeof num2 === \"number\") {\r\n// \t\t\tresult1 = num1 + num2;\r\n// \t\t} else {\r\n// \t\t\tresult1 = num1.toString() + num2.toString();\r\n// \t\t}\r\n// \t\tif (resultType === \"as-string\") {\r\n// \t\t\treturn result1.toString();\r\n// \t\t} else {\r\n// \t\t\treturn +result1;\r\n// \t\t}\r\n// \t};\r\n// \tconst combineAges2 = combnine2(\"12\", \"23\", \"as-number\");\r\n// \tconsole.log(\"alias type\", combineAges2);\r\n// \tconst combinestr1 = combnine2(12, 23, \"as-string\");\r\n// \tconsole.log(\"alias type\", combinestr1);\r\n// \tconst combinestr5 = combnine2(\"Amit\", \"23\", \"as-string\");\r\n// \tconsole.log(\"alias type\", combinestr5);\r\n// }\r\n/*\r\n Function type\r\n*/\r\n// {\r\n// \t//declaring a variable as function and using it\r\n// \tfunction add1(num1: number, num2: number): number {\r\n// \t\treturn num1 + num2;\r\n// \t};\r\n// \tfunction printResult(num: number): void {\r\n// \t\tconsole.log(\"Result\", num);\r\n// \t}\r\n// \tprintResult1(add1(4, 2));\r\n// \tlet combineValues: Function;\r\n// \tcombineValues = add1;\r\n// \t// combineValues = 5;// would have been possible if combineValue was not typecasted as a function and would have resulted in a run time error\r\n// \tconsole.log(\"function Types\", combineValues(2, 3));\r\n// \t//declaring function types with a return type\r\n// \tfunction add2(num1: number, num2: number): number {\r\n// \t\treturn num1 + num2;\r\n// \t};\r\n// \tfunction printResult1(num: number): void {\r\n// \t\tconsole.log(\"Result\", num);\r\n// \t}\r\n// \tprintResult1(add2(4, 2));\r\n// \tlet combineValues1: (a: number, b: number) => number;\r\n// \tcombineValues1 = add2;\r\n// \t// combineValues1 = 5;// thros error as a number cannot be assigned to a function type\r\n// \tconsole.log(\"function Types\", combineValues1(2, 3));\r\n//function type and callback\r\n// function add3(num1: number, num2: number): number {\r\n// \treturn num1 + num2;\r\n// };\r\n// function printResult2(num: number): void {\r\n// \tconsole.log(\"Result\", num);\r\n// }\r\n// function addAndHandle(num1: number, num2: number, callbackFunc: (num: number) => void) {\r\n// \tconst result = num1 + num2;\r\n// \tcallbackFunc(result);\r\n// }\r\n// printResult2(add3(4, 2));\r\n// let combineValues2: (a: number, b: number) => number;\r\n// combineValues2 = add3;\r\n// // combineValues1 = 5;// thros error as a number cannot be assigned to a function type\r\n// console.log(\"function callback\", combineValues2(2, 3));\r\n// addAndHandle(10, 20, num => { console.log(num); })\r\n// }\r\n/*\r\ntype Unknown\r\n*/\r\n// {\r\n// \tlet userInput: unknown,\r\n// \t\tuserName: string;\r\n// \tuserInput = 5;\r\n// \tuserInput = \"max\";\r\n// \t// userName = userInput;//throws an error as unknown can be of any type\r\n// \tif (typeof userInput === \"string\") {\r\n// \t\tuserName = userInput;\r\n// \t}\r\n// }\r\n/*\r\nnever type\r\n*/\r\n// {\r\n// \t//the below function never returns an error. It either crases the app or goes to catch\r\n// \t//void is usually assumed as never in older code\r\n// \t//newer code shoud use never if a code never returns anything\r\n// \tfunction generateErr(message: string, code: number): never {\r\n// \t\tthrow { message: message, errorCode: code };\r\n// \t}\r\n// \tgenerateErr(\"unknown type of variable nice\", 301);\r\n// }\r\n"} {"doc_id": "094210a66b7fdc5bb7392027ed790243", "text": "/**\n * Created by thanos on 4/8/16.\n */\n//\u521b\u5efa\u6570\u7ec4(creating an array)\nvar arr = new Array(element0, element1, elementN);\nvar arr = Array(elechuangjment0, element1, elementN);\nvar arr = [element0, element1, elementN];\n// \u8bd1\u8005\u6ce8: var arr=[4] \u548c var arr=new Array(4)\u662f\u4e0d\u7b49\u6548\u7684\uff0c\n// \u540e\u80054\u6307\u6570\u7ec4\u957f\u5ea6\uff0c\u6240\u4ee5\u4f7f\u7528\u5b57\u9762\u503c(literal)\u7684\u65b9\u5f0f\u5e94\u8be5\u4e0d\u4ec5\u4ec5\u662f\u4fbf\u6377\uff0c\u540c\u65f6\u4e5f\u4e0d\u6613\u8e29\u5751\n\n//forEach() \u65b9\u6cd5\u63d0\u4f9b\u4e86\u904d\u5386\u6570\u7ec4\u5143\u7d20\u7684\u5176\u4ed6\u65b9\u6cd5\nvar colors = ['red', 'green', 'blue'];\ncolors.forEach(function(color) {\n console.log(color);\n});\n\n//--------------------------------------------------------\n//\u6570\u7ec4\u7684\u65b9\u6cd5(array methods)\n//concat() \u8fde\u63a5\u4e24\u4e2a\u6570\u7ec4\u5e76\u8fd4\u56de\u4e00\u4e2a\u65b0\u7684\u6570\u7ec4\u3002\nvar myArray = new Array(\"1\", \"2\", \"3\");\nmyArray = myArray.concat(\"a\", \"b\", \"c\");\n// myArray is now [\"1\", \"2\", \"3\", \"a\", \"b\", \"c\"]\n\n//join(\u5206\u9694\u7b26 = ',') \u5c06\u6570\u7ec4\u7684\u6240\u6709\u5143\u7d20\u8fde\u63a5\u6210\u4e00\u4e2a\u5b57\u7b26\u4e32\nvar myArray = new Array(\"Wind\", \"Rain\", \"Fire\");\nvar list = myArray.join(\" - \"); // list is \"Wind - Rain - Fire\"\n\n//push() \u5728\u6570\u7ec4\u672b\u5c3e\u6dfb\u52a0\u4e00\u4e2a\u6216\u591a\u4e2a\u5143\u7d20\uff0c\u5e76\u8fd4\u56de\u6570\u7ec4\u64cd\u4f5c\u540e\u7684\u957f\u5ea6\u3002\nvar myArray = new Array(\"1\", \"2\");\nmyArray.push(\"3\"); // myArray is now [\"1\", \"2\", \"3\"]\n\n//pop() \u4ece\u6570\u7ec4\u79fb\u51fa\u6700\u540e\u4e00\u4e2a\u5143\u7d20\uff0c\u5e76\u8fd4\u56de\u8be5\u5143\u7d20\u3002\nvar myArray = new Array(\"1\", \"2\", \"3\");\nvar last = myArray.pop();\n// myArray is now [\"1\", \"2\"], last = \"3\"\n\n//shift() \u4ece\u6570\u7ec4\u79fb\u51fa\u7b2c\u4e00\u4e2a\u5143\u7d20\uff0c\u5e76\u8fd4\u56de\u8be5\u5143\u7d20\u3002\nvar myArray = new Array (\"1\", \"2\", \"3\");\nvar first = myArray.shift();\n// myArray is now [\"2\", \"3\"], first is \"1\"\n\n//unshift() \u5728\u6570\u7ec4\u5f00\u5934\u6dfb\u52a0\u4e00\u4e2a\u6216\u591a\u4e2a\u5143\u7d20\uff0c\u5e76\u8fd4\u56de\u6570\u7ec4\u7684\u65b0\u957f\u5ea6\u3002\nvar myArray = new Array (\"1\", \"2\", \"3\");\nmyArray.unshift(\"4\", \"5\");\n// myArray becomes [\"4\", \"5\", \"1\", \"2\", \"3\"]\n\n//slice(start_index, upto_index) \u4ece\u6570\u7ec4\u63d0\u53d6\u4e00\u4e2a\u7247\u6bb5\uff0c\u5e76\u4f5c\u4e3a\u4e00\u4e2a\u65b0\u6570\u7ec4\u8fd4\u56de\u3002\nvar myArray = new Array (\"a\", \"b\", \"c\", \"d\", \"e\");\nmyArray = myArray.slice(1, 4);\n// starts at index 1 and extracts all elements until index 3, returning [ \"b\", \"c\", \"d\"]\n\n//splice(index, count_to_remove, addElement1, addElement2, ...)\u4ece\u6570\u7ec4\u79fb\u51fa\u4e00\u4e9b\u5143\u7d20\uff0c\uff08\u53ef\u9009\uff09\u5e76\u66ff\u6362\u5b83\u4eec\u3002\nvar myArray = new Array (\"1\", \"2\", \"3\", \"4\", \"5\");\nmyArray.splice(1, 3, \"a\", \"b\", \"c\", \"d\");\n\n//reverse() \u98a0\u5012\u6570\u7ec4\u5143\u7d20\u7684\u987a\u5e8f\uff1a\u7b2c\u4e00\u4e2a\u53d8\u6210\u6700\u540e\u4e00\u4e2a\uff0c\u6700\u540e\u4e00\u4e2a\u53d8\u6210\u7b2c\u4e00\u4e2a\u3002\nvar myArray = new Array (\"1\", \"2\", \"3\");\nmyArray.reverse();\n// transposes the array so that myArray = [ \"3\", \"2\", \"1\" ]\n\n//sort() \u7ed9\u6570\u7ec4\u5143\u7d20\u6392\u5e8f\u3002\nvar myArray = new Array(\"Wind\", \"Rain\", \"Fire\");\nmyArray.sort();\n// sorts the array so that myArray = [ \"Fire\", \"Rain\", \"Wind\" ]\n\n//indexOf(searchElement[, fromIndex]) \u5728\u6570\u7ec4\u4e2d\u641c\u7d22searchElement \u5e76\u8fd4\u56de\u7b2c\u4e00\u4e2a\u5339\u914d\u7684\u7d22\u5f15\u3002\nvar a = ['a', 'b', 'a', 'b', 'a'];\nconsole.log(a.indexOf('b')); // logs 1\n// Now try again, starting from after the last match\nconsole.log(a.indexOf('b', 2)); // logs 3\nconsole.log(a.indexOf('z')); // logs -1, because 'z' was not found\n\n//lastIndexOf(searchElement[, fromIndex]) \u548c indexOf\u5dee\u4e0d\u591a\uff0c\u4f46\u662f\u662f\u4ece\u7ed3\u5c3e\u5f00\u59cb\uff0c\u5e76\u4e14\u662f\u53cd\u5411\u641c\u7d22\u3002\nvar a = ['a', 'b', 'c', 'd', 'a', 'b'];\nconsole.log(a.lastIndexOf('b')); // logs 5\n// Now try again, starting from before the last match\nconsole.log(a.lastIndexOf('b', 4)); // logs 1\nconsole.log(a.lastIndexOf('z')); // logs -1\n\n//forEach(callback[, thisObject]) \u5728\u6570\u7ec4\u6bcf\u4e2a\u5143\u7d20\u9879\u4e0a\u6267\u884ccallback\u3002\n\n//map(callback[, thisObject]) \u5728\u6570\u7ec4\u7684\u6bcf\u4e2a\u5355\u5143\u9879\u4e0a\u6267\u884ccallback\u51fd\u6570\uff0c\u5e76\u628a\u8fd4\u56de\u5305\u542b\u56de\u8c03\u51fd\u6570\u8fd4\u56de\u503c\u7684\u65b0\u6570\u7ec4\u3002\n// \u8bd1\u8005\u6ce8\uff1a\u4e5f\u5c31\u662f\u904d\u5386\u6570\u7ec4\uff0c\u5e76\u901a\u8fc7callback\u5bf9\u6570\u7ec4\u5143\u7d20\u8fdb\u884c\u64cd\u4f5c\uff0c\u5e76\u5c06\u6240\u6709\u64cd\u4f5c\u7ed3\u679c\u653e\u5165\u6570\u7ec4\u4e2d\u5e76\u8fd4\u56de\u8be5\u6570\u7ec4\u3002\n\n//filter(callback[, thisObject]) \u8fd4\u56de\u4e00\u4e2a\u5305\u542b\u6240\u6709\u5728\u56de\u8c03\u51fd\u6570\u4e0a\u8fd4\u56de\u4e3atrue\u7684\u5143\u7d20\u7684\u65b0\u6570\u7ec4\u3002\n// \u8bd1\u8005\u6ce8\uff1acallback\u5728\u8fd9\u91cc\u62c5\u4efb\u7684\u662f\u8fc7\u6ee4\u5668\u7684\u89d2\u8272\uff0c\u5f53\u5143\u7d20\u7b26\u5408\u6761\u4ef6\uff0c\u8fc7\u6ee4\u5668\u5c31\u8fd4\u56detrue\uff0c\u800cfilter\u5219\u4f1a\u8fd4\u56de\u6240\u6709\u7b26\u5408\u8fc7\u6ee4\u6761\u4ef6\u7684\u5143\u7d20\u3002\n\n//every(callback[, thisObject]) \u5f53\u6570\u7ec4\u4e2d\u6bcf\u4e00\u4e2a\u5143\u7d20\u5728callback\u4e0a\u88ab\u8fd4\u56detrue\u65f6\u5c31\u8fd4\u56detrue\u3002\n// \u8bd1\u8005\u6ce8\uff1a\u540c\u4e0a\uff0cevery\u5176\u5b9e\u7c7b\u4f3cfilter\uff0c\u53ea\u4e0d\u8fc7\u5b83\u7684\u529f\u80fd\u662f\u5224\u65ad\u662f\u4e0d\u662f\u6570\u7ec4\u4e2d\u7684\u6240\u6709\u5143\u7d20\u90fd\u7b26\u5408\u6761\u4ef6\uff0c\u5e76\u4e14\u8fd4\u56de\u7684\u662fbool\u503c\u3002\n\n//some(callback[, thisObject]) \u53ea\u8981\u6570\u7ec4\u4e2d\u6709\u4e00\u9879\u5728callback\u4e0a\u88ab\u8fd4\u56detrue\uff0c\u5c31\u8fd4\u56detrue\u3002\n// \u8bd1\u8005\u6ce8\uff1a\u540c\u4e0a\uff0c\u7c7b\u4f3cevery\uff0c\u4e0d\u8fc7\u524d\u8005\u8981\u6c42\u90fd\u7b26\u5408\u7b5b\u9009\u6761\u4ef6\u624d\u8fd4\u56detrue\uff0c\u540e\u8005\u53ea\u8981\u6709\u7b26\u5408\u6761\u4ef6\u7684\u5c31\u8fd4\u56detrue\u3002"} {"doc_id": "0960c691348486f74db09b0d80f85fb1", "text": "var numeroPremiado = parseInt(Math.random() * (10 - 0) + 0);\nvar tentativas = 3;\nwhile (tentativas > 0) {\nvar entradaUser = parseInt(prompt(\"Digite um n\u00famero:\"));\n \n if (numeroPremiado == entradaUser) {\n alert(\"Voc\u00ea acertou\");\n break\n }\n else if (numeroPremiado > entradaUser){\n alert(\"O n\u00famero premiado \u00e9 maior\");\n tentativas = tentativas - 1;\n }\n else if (numeroPremiado < entradaUser){\n alert(\"O n\u00famero premiado \u00e9 menor\");\n tentativas = tentativas - 1;\n } \n}\nif( numeroPremiado != entradaUser ) {\n alert(\"Voc\u00ea j\u00e1 utilizou as 3 tentativas\");\n }"} {"doc_id": "0a1451bf99c83294d982a54f8e7d06ba", "text": "var Rectangle = (function () {\n function Rectangle(width, height) {\n this.width = width;\n this.height = height;\n }\n ;\n Rectangle.prototype.compareTo = function (value) {\n if (this.width * this.height >= value.width * value.height) {\n return 1;\n }\n else {\n return -1;\n }\n };\n return Rectangle;\n}());\nvar rect1 = new Rectangle(2, 5);\nvar rect2 = new Rectangle(2, 3);\nrect1.compareTo(rect2) === 1 ? console.log(\"rect1 is bigger\") :\n console.log(\"rect1 is smaller\");\nvar Programmer = (function () {\n function Programmer(name, salary) {\n this.name = name;\n this.salary = salary;\n }\n ;\n Programmer.prototype.compareTo = function (value) {\n if (this.salary >= value.salary) {\n return 1;\n }\n else {\n return -1;\n }\n };\n return Programmer;\n}());\nvar prog1 = new Programmer(\"John\", 20000);\nvar prog2 = new Programmer(\"Alex\", 30000);\nprog1.compareTo(prog2) === 1 ? console.log(prog1.name + \" is richer\") :\n console.log(prog1.name + \" is poorer\");\n"} {"doc_id": "0aa4211e39fff5bfb491baa2988b5e24", "text": "/*\n===============\nDeny dan Mainan\n===============\n\n[INSTRUCTION]\nDeny dan Jenny sangat bahagia setelah kelahiran anak pertama. Anak mereka sangat\nmenyukai mainan, jadi Deny ingin membeli beberapa. Ada banyak pilihan mainan\nyang dapat dibeli.\nFunction maximum toys menerima 2 parameter array dan number, array merupakan daftar harga mainan dan number merupakan uang yang dimiliki Deny.\n\n[EXAMPLE]\nBila input harga array adalah [1, 12, 5, 111, 200, 1000, 10] dan uang k = 50\nmaka hasilnya adalah 4, karena jumlah mainan yang dapat dibeli terbanyak adalah mainan\ndengan harga 1,12,5,10.\n\n[RULE]\n1. Wajib menulis pseudo code, bila tidak menulis pseudo code maka dianggap tidak\nmengerjakan.\n2. dilarang menggunakan indexOf(), find(), filter() dan sort()\n3. dilarang menggunakan regex\n*/\n\n/*\n Pseudo code disini\n\n */\n\nfunction maximumToys(prices, k) {\n //code disini\n}\n\nconsole.log(maximumToys([3, 7, 2, 9, 4], 15)); // 3\nconsole.log(maximumToys([1, 12, 5, 111, 200, 1000, 10], 50)); // 4\nconsole.log(maximumToys([1, 2, 3, 4], 7)); // 3\nconsole.log(\nmaximumToys(\n [\n 52952808,\n 39586066,\n 70403274,\n 33392541,\n 37992362,\n 55743111,\n 55380991,\n 48022854,\n 54843595,\n 440\n ],\n 100000\n)\n); // 1"} {"doc_id": "0b20ed0f521a1a9f86a2a5e88df37781", "text": "/*\n

Given a string, find the length of the longest substring without repeating characters.

\n\n

Examples:

\n\n

Given \"abcabcbb\", the answer is \"abc\", which the length is 3.

\n\n

Given \"bbbbb\", the answer is \"b\", with the length of 1.

\n\n

Given \"pwwkew\", the answer is \"wke\", with the length of 3. Note that the answer must be a substring, \"pwke\" is a subsequence and not a substring.

\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\uff0c\u627e\u51fa\u4e0d\u542b\u6709\u91cd\u590d\u5b57\u7b26\u7684\u6700\u957f\u5b50\u4e32\u7684\u957f\u5ea6\u3002

\n\n

\u793a\u4f8b\uff1a

\n\n

\u7ed9\u5b9a "abcabcbb" \uff0c\u6ca1\u6709\u91cd\u590d\u5b57\u7b26\u7684\u6700\u957f\u5b50\u4e32\u662f "abc" \uff0c\u90a3\u4e48\u957f\u5ea6\u5c31\u662f3\u3002

\n\n

\u7ed9\u5b9a "bbbbb" \uff0c\u6700\u957f\u7684\u5b50\u4e32\u5c31\u662f "b" \uff0c\u957f\u5ea6\u662f1\u3002

\n\n

\u7ed9\u5b9a "pwwkew" \uff0c\u6700\u957f\u5b50\u4e32\u662f "wke" \uff0c\u957f\u5ea6\u662f3\u3002\u8bf7\u6ce8\u610f\u7b54\u6848\u5fc5\u987b\u662f\u4e00\u4e2a\u5b50\u4e32\uff0c"pwke" \u662f \u5b50\u5e8f\u5217  \u800c\u4e0d\u662f\u5b50\u4e32\u3002

\n

\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\uff0c\u627e\u51fa\u4e0d\u542b\u6709\u91cd\u590d\u5b57\u7b26\u7684\u6700\u957f\u5b50\u4e32\u7684\u957f\u5ea6\u3002

\n\n

\u793a\u4f8b\uff1a

\n\n

\u7ed9\u5b9a "abcabcbb" \uff0c\u6ca1\u6709\u91cd\u590d\u5b57\u7b26\u7684\u6700\u957f\u5b50\u4e32\u662f "abc" \uff0c\u90a3\u4e48\u957f\u5ea6\u5c31\u662f3\u3002

\n\n

\u7ed9\u5b9a "bbbbb" \uff0c\u6700\u957f\u7684\u5b50\u4e32\u5c31\u662f "b" \uff0c\u957f\u5ea6\u662f1\u3002

\n\n

\u7ed9\u5b9a "pwwkew" \uff0c\u6700\u957f\u5b50\u4e32\u662f "wke" \uff0c\u957f\u5ea6\u662f3\u3002\u8bf7\u6ce8\u610f\u7b54\u6848\u5fc5\u987b\u662f\u4e00\u4e2a\u5b50\u4e32\uff0c"pwke" \u662f \u5b50\u5e8f\u5217  \u800c\u4e0d\u662f\u5b50\u4e32\u3002

\n*/\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar lengthOfLongestSubstring = function(s) {\n \n};"} {"doc_id": "0bc496fb82a7c70615d7e43a7e7c0a61", "text": "/*\n

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

\n\n
\nSymbol       Value\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000
\n\n

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

\n\n

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

\n\n\n\n

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

\n\n

Example 1:

\n\n
\nInput: "III"\nOutput: 3
\n\n

Example 2:

\n\n
\nInput: "IV"\nOutput: 4
\n\n

Example 3:

\n\n
\nInput: "IX"\nOutput: 9
\n\n

Example 4:

\n\n
\nInput: "LVIII"\nOutput: 58\nExplanation: C = 100, L = 50, XXX = 30 and III = 3.\n
\n\n

Example 5:

\n\n
\nInput: "MCMXCIV"\nOutput: 1994\nExplanation: M = 1000, CM = 900, XC = 90 and IV = 4.
\n

\u7f57\u9a6c\u6570\u5b57\u5305\u542b\u4ee5\u4e0b\u4e03\u79cd\u5b57\u7b26\uff1aI\uff0c V\uff0c X\uff0c L\uff0cC\uff0cD \u548c M\u3002

\n\n
\u5b57\u7b26          \u6570\u503c\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000
\n\n

\u4f8b\u5982\uff0c \u7f57\u9a6c\u6570\u5b57 2 \u5199\u505a II \uff0c\u5373\u4e3a\u4e24\u4e2a\u5e76\u5217\u7684 1\u300212 \u5199\u505a XII \uff0c\u5373\u4e3a X + II \u3002 27 \u5199\u505a  XXVII, \u5373\u4e3a XX + V + II \u3002

\n\n

\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u7f57\u9a6c\u6570\u5b57\u4e2d\u5c0f\u7684\u6570\u5b57\u5728\u5927\u7684\u6570\u5b57\u7684\u53f3\u8fb9\u3002\u4f46\u4e5f\u5b58\u5728\u7279\u4f8b\uff0c\u4f8b\u5982 4 \u4e0d\u5199\u505a IIII\uff0c\u800c\u662f IV\u3002\u6570\u5b57 1 \u5728\u6570\u5b57 5 \u7684\u5de6\u8fb9\uff0c\u6240\u8868\u793a\u7684\u6570\u7b49\u4e8e\u5927\u6570 5 \u51cf\u5c0f\u6570 1 \u5f97\u5230\u7684\u6570\u503c 4 \u3002\u540c\u6837\u5730\uff0c\u6570\u5b57 9 \u8868\u793a\u4e3a IX\u3002\u8fd9\u4e2a\u7279\u6b8a\u7684\u89c4\u5219\u53ea\u9002\u7528\u4e8e\u4ee5\u4e0b\u516d\u79cd\u60c5\u51b5\uff1a

\n\n\n\n

\u7ed9\u5b9a\u4e00\u4e2a\u7f57\u9a6c\u6570\u5b57\uff0c\u5c06\u5176\u8f6c\u6362\u6210\u6574\u6570\u3002\u8f93\u5165\u786e\u4fdd\u5728 1 \u5230 3999 \u7684\u8303\u56f4\u5185\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: "III"\n\u8f93\u51fa: 3
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: "IV"\n\u8f93\u51fa: 4
\n\n

\u793a\u4f8b 3:

\n\n
\u8f93\u5165: "IX"\n\u8f93\u51fa: 9
\n\n

\u793a\u4f8b 4:

\n\n
\u8f93\u5165: "LVIII"\n\u8f93\u51fa: 58\n\u89e3\u91ca: C = 100, L = 50, XXX = 30, III = 3.\n
\n\n

\u793a\u4f8b 5:

\n\n
\u8f93\u5165: "MCMXCIV"\n\u8f93\u51fa: 1994\n\u89e3\u91ca: M = 1000, CM = 900, XC = 90, IV = 4.
\n

\u7f57\u9a6c\u6570\u5b57\u5305\u542b\u4ee5\u4e0b\u4e03\u79cd\u5b57\u7b26\uff1aI\uff0c V\uff0c X\uff0c L\uff0cC\uff0cD \u548c M\u3002

\n\n
\u5b57\u7b26          \u6570\u503c\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000
\n\n

\u4f8b\u5982\uff0c \u7f57\u9a6c\u6570\u5b57 2 \u5199\u505a II \uff0c\u5373\u4e3a\u4e24\u4e2a\u5e76\u5217\u7684 1\u300212 \u5199\u505a XII \uff0c\u5373\u4e3a X + II \u3002 27 \u5199\u505a  XXVII, \u5373\u4e3a XX + V + II \u3002

\n\n

\u901a\u5e38\u60c5\u51b5\u4e0b\uff0c\u7f57\u9a6c\u6570\u5b57\u4e2d\u5c0f\u7684\u6570\u5b57\u5728\u5927\u7684\u6570\u5b57\u7684\u53f3\u8fb9\u3002\u4f46\u4e5f\u5b58\u5728\u7279\u4f8b\uff0c\u4f8b\u5982 4 \u4e0d\u5199\u505a IIII\uff0c\u800c\u662f IV\u3002\u6570\u5b57 1 \u5728\u6570\u5b57 5 \u7684\u5de6\u8fb9\uff0c\u6240\u8868\u793a\u7684\u6570\u7b49\u4e8e\u5927\u6570 5 \u51cf\u5c0f\u6570 1 \u5f97\u5230\u7684\u6570\u503c 4 \u3002\u540c\u6837\u5730\uff0c\u6570\u5b57 9 \u8868\u793a\u4e3a IX\u3002\u8fd9\u4e2a\u7279\u6b8a\u7684\u89c4\u5219\u53ea\u9002\u7528\u4e8e\u4ee5\u4e0b\u516d\u79cd\u60c5\u51b5\uff1a

\n\n\n\n

\u7ed9\u5b9a\u4e00\u4e2a\u7f57\u9a6c\u6570\u5b57\uff0c\u5c06\u5176\u8f6c\u6362\u6210\u6574\u6570\u3002\u8f93\u5165\u786e\u4fdd\u5728 1 \u5230 3999 \u7684\u8303\u56f4\u5185\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: "III"\n\u8f93\u51fa: 3
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: "IV"\n\u8f93\u51fa: 4
\n\n

\u793a\u4f8b 3:

\n\n
\u8f93\u5165: "IX"\n\u8f93\u51fa: 9
\n\n

\u793a\u4f8b 4:

\n\n
\u8f93\u5165: "LVIII"\n\u8f93\u51fa: 58\n\u89e3\u91ca: C = 100, L = 50, XXX = 30, III = 3.\n
\n\n

\u793a\u4f8b 5:

\n\n
\u8f93\u5165: "MCMXCIV"\n\u8f93\u51fa: 1994\n\u89e3\u91ca: M = 1000, CM = 900, XC = 90, IV = 4.
\n*/\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar romanToInt = function(s) {\n \n};"} {"doc_id": "0bd2d7379c63ad921eb0913a57b556c7", "text": "/**\n * Created by montaque22 on 2/24/15.\n */\n(function(){\n var queue = (function(){\n var cell = {};\n function strip(str){\n return str.replace(/[^a-zA-Z ]/g, \"\");\n }\n return {\n store:function(item, args){\n var id = strip(item.toString());\n if(!cell[id]){\n cell[id]={item:item, extra:args};\n }\n },\n find:function(item){\n var id = strip(item.toString());\n var obj = cell[id];\n cell[id] = null;\n return obj;\n }\n }\n })();\n /*\n Curry allows your to feed parameters\n to your function until all the requirements are met.\n\n Ex.\n add(a, b){\n //.. Logic to add a & b\n }\n\n // All are Equivalent\n add.curry()(1)(2);\n add.curry(1)(2);\n add.curry(1,2)();\n add.curry()(1,2);\n add.curry(1)()(2);\n // All of the above equals 3\n */\n Function.prototype.curry = function(){\n var length = this.length;\n var fn = this;\n var args = [].splice.call(arguments,0);\n return args.length >= length ?\n function(){\n return fn.apply(fn, args);\n }\n :\n function(){\n var combined = args.concat([].splice.call(arguments,0));\n return combined.length < length ?\n fn.curry.apply(fn,combined)\n :\n fn.apply(fn, combined);\n };\n };\n\n /*\n Pipe feeds the value returned from the caller to the next\n function in the list. Pipe can take an unlimited number of\n functions to chain in the pipe.\n\n Pipe works similar to piping in the terminal however\n this function also employs currying to allow functions\n that require more than one parameter to have a chance to\n fill their remaining values.\n\n\n Ex.\n function add(a, b){\n return a + b;\n }\n\n function sub(a, b){\n return b - a;\n }\n\n function multi(a, b, c){\n return a * b * c;\n }\n\n function half(a){\n return a / 2;\n }\n\n var pipeOne = add.pipe(half);\n pipeOne(2,4); // Returns 2;\n\n var pipeTwo = add.pipe(half, sub);\n\n var pipeInSecondState = pipeTwo(8,2);\n // Pipe executed the add function which piped 10 to the half function.\n // The half function needs only 1 parameter which was fulfilled by the previous function so\n // half was executed with the value 10 which returned 5.\n // However the sub function needs 2 parameters, so it stored the 5 (which came from the half function)\n // internally and returned a curried function that needs only 1 more value to execute.\n\n pipeInSecondState(3)\n // Executes the sub function against the internally stored value 5 which returns 2\n\n pipeInSecondState(10)\n // The function can be reused multiple times and the values passed in will be executed against the\n // internally stored 5. So the function will return -5\n\n var pipeThree = add.pipe(sub, multi, half);\n var anotherPipeInSecondState = pipeThree(1)(2); // stores 3 internally\n // The add function needs two values so it will curry until the parameters are satisfied.\n\n var pipeInThirdState = anotherPipeInSecondState()()(5); // stores 2 internally\n // The sub function was fed 3 by the add function and needs 1 more parameter fulfilled.\n // It will return itself until the function is satisfied\n\n pipeInThirdState()()(2)()(2,3); // returns 6\n // The multi function needs two more of its parameters fulfilled so, like the example before it,\n // it will continue to return itself until it receives a input that satisfies the correct number\n // of input. pipeInThirdState()()(2)() were incorrect number of parameters. The function doesnt\n // execute until it reaches the input (2,3).\n // Since the next function only needs 1 parameter it is immediately fired which returns 6\n\n // The above executed the following:\n // ((5 - (1 + 2)) * 2 * 3) / 2\n */\n Function.prototype.pipe = function(){\n var functions = [].splice.call(arguments,0);\n var currentFunc = this;\n var savedInputs = [];\n return function stream(){\n var duplicatedFunctions = functions.slice();\n\n // If the arguments satisfy the current Function's Needs on the first try\n if(!savedInputs.length && arguments.length >= currentFunc.length)\n return helper(arguments);\n\n // If the arguments satisfy the current function's needs on any 'second' try\n else if(arguments.length + savedInputs.length >= currentFunc.length)\n return helper(savedInputs\n .concat(Array\n .prototype\n .splice\n .call(arguments,0)));\n\n // Return your self cuz the caller sucked\n else {\n // Only Save the arguments the first time\n // If we make it to this point means that we were being called recursively from the function before this\n // Saving the input is similar to saving the state and allows the user to pickup where they left off.\n if(!savedInputs.length){\n savedInputs = savedInputs.concat([].splice.call(arguments,0));\n }\n\n return stream;\n\n }\n\n function helper(args){\n var nextFunction = duplicatedFunctions.shift();\n var param = currentFunc.apply(currentFunc, args);\n return (!nextFunction)? param : nextFunction.pipe.apply(nextFunction, duplicatedFunctions)(param);\n }\n };\n };\n\n\n /*\n Stores the values for a function to be used later on.\n This is supposed to be used with release.\n */\n Function.prototype.hold = function(){\n //store the function internally along with any arguments passed\n //only one function can be stored at a time\n // note : the function is still usable\n queue.store(this, arguments);\n };\n\n /*\n This releases the function that was held previously\n and executes it along with the arguments that were given at both\n instances.\n\n This companion function is useful in situations similar to the following:\n\n function add(a, b){\n return a + b\n }\n\n add.hold(10);\n\n setTimeout(function(){\n var ans = add.release(5);\n // returns 15\n },5000)\n\n */\n Function.prototype.release = function(){\n // call the function that was in queue\n // any previous arguements plus the ones passed in at this point are used\n // the function is released from holding and\n // the process can be repeated again\n var data = queue.find(this.toString());\n var args = [].splice.call(data.extra,0);\n var combine = args.concat([].splice.call(arguments, 0));\n return this.apply(this, combine);\n\n };\n\n})();\n\n"} {"doc_id": "0bf3397160dd49d3f5f089a24288caaa", "text": "/*\nTwo red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads.\n\n@ @@ @ @@ @ @@ @ @@ @ @@ @\n\nImplement count_red_beads(n) (in PHP count_red_beads($n); in Java, Javascript, TypeScript, C, C++ countRedBeads(n)) so that it returns the number of red beads.\nIf there are less than 2 blue beads return 0. \n*/\n\nfunction countRedBeads(n) {\n if (n < 2) return 0;\n return (n - 1) * 2;\n \n // Another Solution:\n // return n < 2 ? 0 : 2 * n - 2;\n}"} {"doc_id": "0bf3b733e45c31e49d6e3384095e3786", "text": "/*\n

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

\n\n

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

\n\n

You may assume the integer does not contain any leading zero, except the number 0 itself.

\n\n

Example 1:

\n\n
\nInput: [1,2,3]\nOutput: [1,2,4]\nExplanation: The array represents the integer 123.\n
\n\n

Example 2:

\n\n
\nInput: [4,3,2,1]\nOutput: [4,3,2,2]\nExplanation: The array represents the integer 4321.\n
\n

\u7ed9\u5b9a\u4e00\u4e2a\u975e\u8d1f\u6574\u6570\u7ec4\u6210\u7684\u975e\u7a7a\u6570\u7ec4\uff0c\u5728\u8be5\u6570\u7684\u57fa\u7840\u4e0a\u52a0\u4e00\uff0c\u8fd4\u56de\u4e00\u4e2a\u65b0\u7684\u6570\u7ec4\u3002

\n\n

\u6700\u9ad8\u4f4d\u6570\u5b57\u5b58\u653e\u5728\u6570\u7ec4\u7684\u9996\u4f4d\uff0c \u6570\u7ec4\u4e2d\u6bcf\u4e2a\u5143\u7d20\u53ea\u5b58\u50a8\u4e00\u4e2a\u6570\u5b57\u3002

\n\n

\u4f60\u53ef\u4ee5\u5047\u8bbe\u9664\u4e86\u6574\u6570 0 \u4e4b\u5916\uff0c\u8fd9\u4e2a\u6574\u6570\u4e0d\u4f1a\u4ee5\u96f6\u5f00\u5934\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: [1,2,3]\n\u8f93\u51fa: [1,2,4]\n\u89e3\u91ca: \u8f93\u5165\u6570\u7ec4\u8868\u793a\u6570\u5b57 123\u3002\n
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: [4,3,2,1]\n\u8f93\u51fa: [4,3,2,2]\n\u89e3\u91ca: \u8f93\u5165\u6570\u7ec4\u8868\u793a\u6570\u5b57 4321\u3002\n
\n

\u7ed9\u5b9a\u4e00\u4e2a\u975e\u8d1f\u6574\u6570\u7ec4\u6210\u7684\u975e\u7a7a\u6570\u7ec4\uff0c\u5728\u8be5\u6570\u7684\u57fa\u7840\u4e0a\u52a0\u4e00\uff0c\u8fd4\u56de\u4e00\u4e2a\u65b0\u7684\u6570\u7ec4\u3002

\n\n

\u6700\u9ad8\u4f4d\u6570\u5b57\u5b58\u653e\u5728\u6570\u7ec4\u7684\u9996\u4f4d\uff0c \u6570\u7ec4\u4e2d\u6bcf\u4e2a\u5143\u7d20\u53ea\u5b58\u50a8\u4e00\u4e2a\u6570\u5b57\u3002

\n\n

\u4f60\u53ef\u4ee5\u5047\u8bbe\u9664\u4e86\u6574\u6570 0 \u4e4b\u5916\uff0c\u8fd9\u4e2a\u6574\u6570\u4e0d\u4f1a\u4ee5\u96f6\u5f00\u5934\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: [1,2,3]\n\u8f93\u51fa: [1,2,4]\n\u89e3\u91ca: \u8f93\u5165\u6570\u7ec4\u8868\u793a\u6570\u5b57 123\u3002\n
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165: [4,3,2,1]\n\u8f93\u51fa: [4,3,2,2]\n\u89e3\u91ca: \u8f93\u5165\u6570\u7ec4\u8868\u793a\u6570\u5b57 4321\u3002\n
\n*/\n\n\n/**\n * @param {number[]} digits\n * @return {number[]}\n */\nvar plusOne = function(digits) {\n \n};"} {"doc_id": "0d088f89fe8a4d4e5f6e43b97e7b72d9", "text": "/*\n

\nA string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.\n

\n\n

Example 1:
\n

\nInput: S = \"ababcbacadefegdehijhklij\"\nOutput: [9,7,8]\nExplanation:\nThe partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits S into less parts.\n
\n

\n\n

Note:

    \n
  1. S will have length in range [1, 500].
  2. \n
  3. S will consist of lowercase letters ('a' to 'z') only.
  4. \n

\u5b57\u7b26\u4e32 S \u7531\u5c0f\u5199\u5b57\u6bcd\u7ec4\u6210\u3002\u6211\u4eec\u8981\u628a\u8fd9\u4e2a\u5b57\u7b26\u4e32\u5212\u5206\u4e3a\u5c3d\u53ef\u80fd\u591a\u7684\u7247\u6bb5\uff0c\u540c\u4e00\u4e2a\u5b57\u6bcd\u53ea\u4f1a\u51fa\u73b0\u5728\u5176\u4e2d\u7684\u4e00\u4e2a\u7247\u6bb5\u3002\u8fd4\u56de\u4e00\u4e2a\u8868\u793a\u6bcf\u4e2a\u5b57\u7b26\u4e32\u7247\u6bb5\u7684\u957f\u5ea6\u7684\u5217\u8868\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: S = "ababcbacadefegdehijhklij"\n\u8f93\u51fa: [9,7,8]\n\u89e3\u91ca:\n\u5212\u5206\u7ed3\u679c\u4e3a "ababcbaca", "defegde", "hijhklij"\u3002\n\u6bcf\u4e2a\u5b57\u6bcd\u6700\u591a\u51fa\u73b0\u5728\u4e00\u4e2a\u7247\u6bb5\u4e2d\u3002\n\u50cf "ababcbacadefegde", "hijhklij" \u7684\u5212\u5206\u662f\u9519\u8bef\u7684\uff0c\u56e0\u4e3a\u5212\u5206\u7684\u7247\u6bb5\u6570\u8f83\u5c11\u3002\n
\n\n

\u6ce8\u610f:

\n\n
    \n\t
  1. S\u7684\u957f\u5ea6\u5728[1, 500]\u4e4b\u95f4\u3002
  2. \n\t
  3. S\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd'a'\u5230'z'\u3002
  4. \n
\n

\u5b57\u7b26\u4e32 S \u7531\u5c0f\u5199\u5b57\u6bcd\u7ec4\u6210\u3002\u6211\u4eec\u8981\u628a\u8fd9\u4e2a\u5b57\u7b26\u4e32\u5212\u5206\u4e3a\u5c3d\u53ef\u80fd\u591a\u7684\u7247\u6bb5\uff0c\u540c\u4e00\u4e2a\u5b57\u6bcd\u53ea\u4f1a\u51fa\u73b0\u5728\u5176\u4e2d\u7684\u4e00\u4e2a\u7247\u6bb5\u3002\u8fd4\u56de\u4e00\u4e2a\u8868\u793a\u6bcf\u4e2a\u5b57\u7b26\u4e32\u7247\u6bb5\u7684\u957f\u5ea6\u7684\u5217\u8868\u3002

\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165: S = "ababcbacadefegdehijhklij"\n\u8f93\u51fa: [9,7,8]\n\u89e3\u91ca:\n\u5212\u5206\u7ed3\u679c\u4e3a "ababcbaca", "defegde", "hijhklij"\u3002\n\u6bcf\u4e2a\u5b57\u6bcd\u6700\u591a\u51fa\u73b0\u5728\u4e00\u4e2a\u7247\u6bb5\u4e2d\u3002\n\u50cf "ababcbacadefegde", "hijhklij" \u7684\u5212\u5206\u662f\u9519\u8bef\u7684\uff0c\u56e0\u4e3a\u5212\u5206\u7684\u7247\u6bb5\u6570\u8f83\u5c11\u3002\n
\n\n

\u6ce8\u610f:

\n\n
    \n\t
  1. S\u7684\u957f\u5ea6\u5728[1, 500]\u4e4b\u95f4\u3002
  2. \n\t
  3. S\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd'a'\u5230'z'\u3002
  4. \n
\n*/\n\n\n/**\n * @param {string} S\n * @return {number[]}\n */\nvar partitionLabels = function(S) {\n \n};"} {"doc_id": "0ec7c72113fb98fdaa70f2aea4c2ccb7", "text": "class NumComplejo{\n constructor(x,y){\n this.x = x;\n this.y = y;\n }\n toString(){\n return \"(\" + this.x + \", \" + this.y + \")\";\n }\n modulo(){\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n argumento(){\n return Math.atan2(this.y,this.x);\n }\n sumar(otro){// otro ser\u00e1 un NumComplejo\n return new NumComplejo(this.x + otro.x, this.y + otro.y);\n }\n}\n// ------------- CREACION Y USO ---------------\nlet a = new NumComplejo(3,4);\nconsole.log(a.toString() + \" tiene un m\u00f3dulo de\", a.modulo(), \n \"y un argumento de\", a.argumento(), \"radianes\");\nlet b = new NumComplejo(1,1);\n// Cuando una referencia a un objeto (en este caso b) est\u00e1 en \n// un sitio dondes se espera un String (por ejemplo en una\n// concatenaci\u00f3n), autom\u00e1ticamente se ejectuta el m\u00e9todo toString.\nconsole.log(b + \" tiene un m\u00f3dulo de\", b.modulo(), \n \"y un argumento de\", b.argumento(), \"radianes\");\nlet c = a.sumar(b);\nconsole.log(a + \" + \" + b + \" = \" + c);\n"} {"doc_id": "0f27a9dba4806fd28cd0892f973a90d2", "text": "\ufeff/*Write a function that formats a string. The function should have placeholders, as shown in the example\nAdd the function to the String.prototype\nExample:\ninput\t | output\nvar options = {name: 'John'}; | \n'Hello, there! Are you #{name}?'.format(options);\t |'Hello, there! Are you John'\nvar options = {name: 'John', age: 13}; |\n'My name is #{name} and I am #{age}-years-old'.format(options);|'My name is John and I am 13-years-old'*/\n\nconsole.log('=================================');\nconsole.log('01. Format with placeholders');\nconsole.log('-------------------');\n\nvar str1 = 'Hello, there! Are you #{name}?',\n str2 = 'My name is #{name} and I am #{age}-years-old';\n\nString.prototype.format = function (options) {\n var result = this,\n regExp,\n prop;\n\n for (prop in options) {\n regExp = new RegExp('#{' + prop + '}', 'g');\n\n result = result.replace(regExp, options[prop]);\n }\n\n return result;\n};\n\nconsole.log(str1.format({ name: 'John' }));\nconsole.log(str2.format({ name: 'John', age: 13 }));"} {"doc_id": "0ffb9184392bef8777bdb718190d5d0f", "text": "// Include the Word Constructor\nvar Word = require(\"./Word\");\n\n// Include the inquirer Module\nvar inquirer = require(\"inquirer\");\n\n// Game Possible Words\nvar randomWords = require(\"./randomwords\")\n\n// Create the game Word with a randomly chosen Word\n// var myWord = new Word(\"Cat\");\nvar myWord = new Word(randomWords[Math.floor(Math.random()*randomWords.length)]);\n\n// This Variable store the Number of Chances\nvar chances = 10;\n\n// Play Function\nfunction play(){\n // User Menu\n inquirer.prompt([\n {\n name: \"charGuess\",\n message: \"Guess a Letter?\"\n },\n ]).then(answers => {\n // Decrease the remaining chances\n chances--;\n // Compare the captured character with all word letters\n var guessed = myWord.charIsIn(answers.charGuess);\n // Display the result word with letters guessed.\n console.log(myWord.display());\n // Display Messages according to guessed status.\n if(guessed){\n // Display Message in Green Color\n console.log('\\x1b[32m%s\\x1b[0m', \"\\nCORRECT!!!\");\n }else{\n // Display Message in Red Color\n console.log('\\x1b[31m%s\\x1b[0m', \"\\nINCORRECT!!!\");\n }\n // Display the remaining guesses\n console.log(chances + \" guesses remaining!!\\n\");\n \n // The game ends with a Winner when no more underscores \"_\"\n // are shown in the Word\n if (!myWord.display().includes(\"_\")) {\n console.log('\\x1b[32m%s\\x1b[0m', \"=====================\\nWell Done!! You Win!!!\");\n } \n // The game ends with a Loser when we run out of chances\n else if (chances===0){\n console.log('\\x1b[36m%s\\x1b[0m',\"The Word was: \" + myWord.forceDisplay());\n console.log('\\x1b[31m%s\\x1b[0m',\"=====================\\nYou Lose!!!\");\n } \n // We Recursively call the the play() function until Winner or Loser.\n else {\n play();\n }\n });\n}\n\nplay();"} {"doc_id": "10291283caddc27ca614a452cb77c99d", "text": "$(function() {\n\t\n\t// Time function to get the date/time\n\tfunction time() {\n\t\t\n\t\t// Create new date var and init other vars\n\t\tvar date = new Date(),\n\t\t\thours = date.getHours(), // Get the hours\n\t\t\tminutes = date.getMinutes().toString(), // Get minutes, convert to string\n\t\t\tante, // Will be used for AM and PM later\n\t\t\tgreeting, // Set the appropriate greeting for the time of day\n\t\t\tdd = date.getDate().toString(), // Get the current day\n\t\t\tuserName = \"User\"; // Can be used to insert a unique name\n\n\t\t/* Set the AM or PM according to the time, it is important to note that up\n\t\t\tto this point in the code this is a 24 clock */\n\t\tif (hours < 12) {\n\t\t\tante = \"AM\";\n\t\t\tgreeting = \"Morning\";\n\t\t} else if (hours === 12 && hours >= 3) {\n\t\t\tante = \"PM\";\n\t\t\tgreeting = \"Afternoon\"\n\t\t} else {\n\t\t\tante = \"PM\";\n\t\t\tgreeting = \"Evening\";\n\t\t}\n\n\t\t/* Since it is a 24 hour clock, 0 represents 12am, if that is the case\n\t\tthen convert that to 12 */\n\t\tif (hours === 0) {\n\t\t\thours = 12;\n\t\t\t\n\t\t\t/* For any other case where hours is not equal to twelve, let's use modulus\n\t\t\tto get the corresponding time equivilant */\n\t\t} else if (hours !== 12) {\n\t\t\thours = hours % 12;\n\t\t}\n\n\t\t// Minutes can be in single digits, hence let's add a 0 when the length is less than two\n\t\tif (minutes.length < 2) {\n\t\t\tminutes = \"0\" + minutes;\n\t\t}\n\n\t\t// Let's do the same thing above here for the day\n\t\tif (dd.length < 2) {\n\t\t\tdd = \"0\" + dd;\n\t\t}\n\n\t\t// Months\n\t\tDate.prototype.monthNames = [\n\t\t\t\"January\",\n\t\t\t\"February\",\n\t\t\t\"March\",\n\t\t\t\"April\",\n\t\t\t\"May\",\n\t\t\t\"June\",\n\t\t\t\"July\",\n\t\t\t\"August\",\n\t\t\t\"September\",\n\t\t\t\"October\",\n\t\t\t\"November\",\n\t\t\t\"December\"\n\t\t];\n\n\t\t// Days\n\t\tDate.prototype.weekNames = [\n\t\t\t\"Sunday\",\n\t\t\t\"Monday\",\n\t\t\t\"Tuesday\",\n\t\t\t\"Wednesday\",\n\t\t\t\"Thursday\",\n\t\t\t\"Friday\",\n\t\t\t\"Saturday\"\n\t\t];\n\t\t\n\t\t// Return the month name according to its number value\n\t\tDate.prototype.getMonthName = function() {\n\t\t\treturn this.monthNames[this.getMonth()];\n\t\t};\n\t\t\n\t\t// Return the day's name according to its number value\n\t\tDate.prototype.getWeekName = function() {\n\t\t\treturn this.weekNames[this.getDay()];\n\t\t};\n\n\t\t// Display the following in html\n\t\t$(\"#time\").html(hours + \":\" + minutes + \" \" + ante);\n\t\t$(\"#day\").html(date.getWeekName() + \", \" + date.getMonthName() + \" \" + dd);\n\t\t$(\"#greeting\").html(\"Good \" + greeting + \", \" + userName + \".\");\n\t\t\n\t\t// The interval is necessary for proper time syncing\n\t\tsetInterval(time, 1000);\n\t}\n\ttime();\n});\n"} {"doc_id": "105927b0596c557ca6b83bc8657f3eec", "text": "// Return a value from the .then() handler\n\n// Create a Promise\nlet getUser = new Promise(function (resolve, reject) {\n const user = {\n name: \"John Doe\",\n email: \"jdoe@email.com\",\n password: \"jdoe.password\",\n };\n resolve(user);\n});\n\ngetUser\n .then(function (user) {\n console.log(`Got user ${user.name}`);\n // Return a simple value\n return user.email;\n })\n .then(function (email) {\n console.log(`User email is ${email}`);\n });\n"} {"doc_id": "105bf58fdd1b967f209282be9595364f", "text": "alert(`Guess 3 secrets in 3 tries\n\n Player 1:\n enter three secrets\n\n Player 2:\n see the three secrets in order\n then enter them back in order\n if you get one wrong - game over!\n`);\n\nalert('Player 2: go hide');\n\nlet secret1 = prompt('Player 1, enter your first secret:');\nlet secret2 = prompt('Player 1, enter your second secret:');\nlet secret3 = prompt('Player 1, enter your third secret:');\n\nalert('Player 2, get back here');\n\nalert(\n 'Player 2, remember these:' +\n '\\n1. \"' +\n secret1 +\n '\"' +\n '\\n2. \"' +\n secret2 +\n '\"' +\n '\\n3. \"' +\n secret3 +\n '\"'\n);\n\nlet score = 0;\n\nlet firstTry = prompt('Player 1, guess the first secret:');\nif (firstTry === secret1) {\n score = score + 1;\n\n let secondTry = prompt('Player 1, guess the second secret:');\n if (secondTry === secret2) {\n score = score + 1;\n\n let thirdTry = prompt('Player 1, guess the third secret:');\n if (thirdTry === secret3) {\n score = score + 1;\n }\n }\n}\n\nalert('your score: ' + score);\n"} {"doc_id": "1164b22d7e6184bc94119786bb5e9701", "text": "/*\n

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

\n\n\n\n

Example 1:

\n\n
\nInput:\nmatrix = [\n  [1,   3,  5,  7],\n  [10, 11, 16, 20],\n  [23, 30, 34, 50]\n]\ntarget = 3\nOutput: true\n
\n\n

Example 2:

\n\n
\nInput:\nmatrix = [\n  [1,   3,  5,  7],\n  [10, 11, 16, 20],\n  [23, 30, 34, 50]\n]\ntarget = 13\nOutput: false
\n

\u7f16\u5199\u4e00\u4e2a\u9ad8\u6548\u7684\u7b97\u6cd5\u6765\u5224\u65ad m x n \u77e9\u9635\u4e2d\uff0c\u662f\u5426\u5b58\u5728\u4e00\u4e2a\u76ee\u6807\u503c\u3002\u8be5\u77e9\u9635\u5177\u6709\u5982\u4e0b\u7279\u6027\uff1a

\n\n\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165:\nmatrix = [\n  [1,   3,  5,  7],\n  [10, 11, 16, 20],\n  [23, 30, 34, 50]\n]\ntarget = 3\n\u8f93\u51fa: true\n
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165:\nmatrix = [\n  [1,   3,  5,  7],\n  [10, 11, 16, 20],\n  [23, 30, 34, 50]\n]\ntarget = 13\n\u8f93\u51fa: false
\n

\u7f16\u5199\u4e00\u4e2a\u9ad8\u6548\u7684\u7b97\u6cd5\u6765\u5224\u65ad m x n \u77e9\u9635\u4e2d\uff0c\u662f\u5426\u5b58\u5728\u4e00\u4e2a\u76ee\u6807\u503c\u3002\u8be5\u77e9\u9635\u5177\u6709\u5982\u4e0b\u7279\u6027\uff1a

\n\n\n\n

\u793a\u4f8b 1:

\n\n
\u8f93\u5165:\nmatrix = [\n  [1,   3,  5,  7],\n  [10, 11, 16, 20],\n  [23, 30, 34, 50]\n]\ntarget = 3\n\u8f93\u51fa: true\n
\n\n

\u793a\u4f8b 2:

\n\n
\u8f93\u5165:\nmatrix = [\n  [1,   3,  5,  7],\n  [10, 11, 16, 20],\n  [23, 30, 34, 50]\n]\ntarget = 13\n\u8f93\u51fa: false
\n*/\n\n\n/**\n * @param {number[][]} matrix\n * @param {number} target\n * @return {boolean}\n */\nvar searchMatrix = function(matrix, target) {\n \n};"} {"doc_id": "11d1dda98dff45b1026fa4d2d4875f47", "text": "/*\n

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

\n\n

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

\n\n

Example:

\n\n
\nint k = 3;\nint[] arr = [4,5,8,2];\nKthLargest kthLargest = new KthLargest(3, arr);\nkthLargest.add(3);   // returns 4\nkthLargest.add(5);   // returns 5\nkthLargest.add(10);  // returns 5\nkthLargest.add(9);   // returns 8\nkthLargest.add(4);   // returns 8\n
\n\n

Note:
\nYou may assume that nums' length ≥ k-1 and k ≥ 1.

\u8bbe\u8ba1\u4e00\u4e2a\u627e\u5230\u6570\u636e\u6d41\u4e2d\u7b2cK\u5927\u5143\u7d20\u7684\u7c7b\uff08class\uff09\u3002\u6ce8\u610f\u662f\u6392\u5e8f\u540e\u7684\u7b2cK\u5927\u5143\u7d20\uff0c\u4e0d\u662f\u7b2cK\u4e2a\u4e0d\u540c\u7684\u5143\u7d20\u3002

\n\n

\u4f60\u7684 KthLargest \u7c7b\u9700\u8981\u4e00\u4e2a\u540c\u65f6\u63a5\u6536\u6574\u6570 k \u548c\u6574\u6570\u6570\u7ec4nums \u7684\u6784\u9020\u5668\uff0c\u5b83\u5305\u542b\u6570\u636e\u6d41\u4e2d\u7684\u521d\u59cb\u5143\u7d20\u3002\u6bcf\u6b21\u8c03\u7528 KthLargest.add\uff0c\u8fd4\u56de\u5f53\u524d\u6570\u636e\u6d41\u4e2d\u7b2cK\u5927\u7684\u5143\u7d20\u3002

\n\n

\u793a\u4f8b:

\n\n
\nint k = 3;\nint[] arr = [4,5,8,2];\nKthLargest kthLargest = new KthLargest(3, arr);\nkthLargest.add(3);   // returns 4\nkthLargest.add(5);   // returns 5\nkthLargest.add(10);  // returns 5\nkthLargest.add(9);   // returns 8\nkthLargest.add(4);   // returns 8\n
\n\n

\u8bf4\u660e:
\n\u4f60\u53ef\u4ee5\u5047\u8bbe nums \u7684\u957f\u5ea6≥ k-1 \u4e14k ≥ 1\u3002

\n

\u8bbe\u8ba1\u4e00\u4e2a\u627e\u5230\u6570\u636e\u6d41\u4e2d\u7b2cK\u5927\u5143\u7d20\u7684\u7c7b\uff08class\uff09\u3002\u6ce8\u610f\u662f\u6392\u5e8f\u540e\u7684\u7b2cK\u5927\u5143\u7d20\uff0c\u4e0d\u662f\u7b2cK\u4e2a\u4e0d\u540c\u7684\u5143\u7d20\u3002

\n\n

\u4f60\u7684 KthLargest \u7c7b\u9700\u8981\u4e00\u4e2a\u540c\u65f6\u63a5\u6536\u6574\u6570 k \u548c\u6574\u6570\u6570\u7ec4nums \u7684\u6784\u9020\u5668\uff0c\u5b83\u5305\u542b\u6570\u636e\u6d41\u4e2d\u7684\u521d\u59cb\u5143\u7d20\u3002\u6bcf\u6b21\u8c03\u7528 KthLargest.add\uff0c\u8fd4\u56de\u5f53\u524d\u6570\u636e\u6d41\u4e2d\u7b2cK\u5927\u7684\u5143\u7d20\u3002

\n\n

\u793a\u4f8b:

\n\n
\nint k = 3;\nint[] arr = [4,5,8,2];\nKthLargest kthLargest = new KthLargest(3, arr);\nkthLargest.add(3);   // returns 4\nkthLargest.add(5);   // returns 5\nkthLargest.add(10);  // returns 5\nkthLargest.add(9);   // returns 8\nkthLargest.add(4);   // returns 8\n
\n\n

\u8bf4\u660e:
\n\u4f60\u53ef\u4ee5\u5047\u8bbe nums \u7684\u957f\u5ea6≥ k-1 \u4e14k ≥ 1\u3002

\n*/\n\n\n/**\n * @param {number} k\n * @param {number[]} nums\n */\nvar KthLargest = function(k, nums) {\n \n};\n\n/** \n * @param {number} val\n * @return {number}\n */\nKthLargest.prototype.add = function(val) {\n \n};\n\n/** \n * Your KthLargest object will be instantiated and called as such:\n * var obj = Object.create(KthLargest).createNew(k, nums)\n * var param_1 = obj.add(val)\n */"} {"doc_id": "11e2a615efd3b3ca1e5c5c0e32f1e1c5", "text": "/********************/\r\n/* Array Exercises */\r\n/********************/\r\n\r\n/*\r\n DO NOT EDIT/DELETE THESE FUNCTIONS. They are used for the exercises!\r\n*/\r\nfunction process(item) {\r\n return item;\r\n}\r\n\r\n/*\r\n EXAMPLE ANSWER\r\n Create a function named 'example' with no parameters.\r\n Return an array consisting of three values\r\n ie:\r\n example() -> an array with 3 items\r\n*/\r\nfunction example() {\r\n return [1, 2, 3];\r\n}\r\n\r\n/*\r\n Create a function named 'quadArray' with no parameters\r\n Return an array consisting of four values\r\n ie:\r\n quadArray() -> an array with 4 items\r\n*/\r\nfunction quadArray(){\r\n return [1, 2, 3, 4];\r\n}\r\n\r\n/*\r\n Create a function named 'itemCount' with one parameter\r\n Name the parameter anything you want\r\n Return the number of items in the array passed in through the parameter\r\n ie:\r\n itemCount([1, 2, 3]) -> 3\r\n itemCount([\"hello\", \"hola\", \"bonjour\", \"ni hao\"]) -> 4\r\n*/\r\nfunction itemCount(loop){\r\n return loop.length;\r\n}\r\n\r\n/*\r\n Create a function named 'firstItem' with one parameter\r\n Name the parameter anything you want\r\n Return the first item in the array passed in through the parameter\r\n ie:\r\n itemCount([1, 2, 3]) -> 1\r\n itemCount([\"hello\", \"hola\", \"bonjour\", \"ni hao\"]) -> \"hello\"\r\n*/\r\nfunction firstItem(items){\r\n return items [0];\r\n}\r\n\r\n/*\r\n Create a function named 'lastItem' with one parameter\r\n Name the parameter anything you want\r\n Return the last item in the array passed in through the parameter\r\n ie:\r\n lastItem([1, 2, 3]) -> 3\r\n lastItem([\"hello\", \"hola\", \"bonjour\", \"ni hao\"]) -> \"ni hao\"\r\n*/\r\nfunction lastItem(last){\r\n return last [last.length-1];\r\n}\r\n\r\n/*\r\n Create a function named 'arrayEdge' with one parameter\r\n Name the parameter anything you want\r\n Return the first and last item in the array passed through the parameter as a new array\r\n ie:\r\n arrayEdge([1, 2, 3]) -> [1, 3]\r\n arrayEdge([\"hello\", \"hola\", \"bonjour\", \"ni hao\"]) -> [\"hello\", \"ni hao\"]\r\n*/\r\nfunction arrayEdge(edge){\r\n return edge [0], edge[edge.length()-1];\r\n}\r\n\r\n/*\r\n Create a function named 'processArray' with one parameter\r\n Name the parameter anything you want\r\n Create a for loop that runs based on the length of the array entered as the parameter\r\n Inside the for loop, call the process function with the argument for each item in the array\r\n ie:\r\n processArray([1, 2, 3]) -> process(1), process(2) and process(3) are called\r\n processArray([\"hello\", \"hola\", \"bonjour\", \"ni hao\"]) -> process(\"hello\"), process(\"hola\"), process(\"bonjour\") and process(\"ni hao\") are called\r\n*/\r\nfunction processArray(array){\r\n \r\n}\r\n\r\n/*\r\n Create a function named 'filterArray' with two parameters\r\n Name the parameters anything you want\r\n The first parameter will be an array, the second parameter will be a number\r\n Return a new array that will consist of items that are greater than or equal to the second parameter\r\n ie:\r\n filterArray([1, 2, 3], 2) -> [2, 3]\");\r\n filterArray([7, 3, 10, 6], 5) -> [7, 10, 6]\");\r\n filterArray([7, 3, 10, 6], 20) -> []\");\r\n*/\r\n"} {"doc_id": "122ea6b9cccea647716d6a87938a72d2", "text": "\n// ************************ WORD REVEAL ************************\n\n\n// ---- VARIABLES ----\n\n // ==> Create accessibly scoped variables\n var secretWord = '';\n\n var secretWordArray = [];\n\n// ===========>>> Create js objects from the html \n var wordTable = document.getElementById(\"word-table\"); \n\n var startButton = document.getElementById(\"start-button\"); \n\n var guessButton = document.getElementById(\"guess-button\"); \n\n var resetButton = document.getElementById(\"reset-button\");\n\n\n// ---- FUNCTIONS ----\n\n// ===========>>> Create fn to INITIALIZE the game\n var initializeGame = function () {\n\n // Set the word and array variables:\n secretWord = \"\";\n secretWordArray = [];\n\n // Set the initial table row that will hold the secret letters\n\n var row = wordTable.insertRow(0);\n row.setAttribute(\"class\",\"letters\");\n\n //+++ verify the changes in console\n\n console.log(wordTable)\n console.log(wordTable.count)\n return console.log (\"The secret word is \" + \"'\" + secretWord+\"'\"); \n \n };\n\n // *** RESET *** ==> Create a function to reset game data\n var resetGame = function () {\n // set variables\n var tableRows = document.getElementsByClassName(\"letters\");\n var tableLength = tableRows.length;\n \n // delete all of word row(s) from the table\n if (tableLength > 0) {\n // important that 'i <', and not '<=' to avoid null value\n for (var i = 0; i < tableLength; i++) {\n document.getElementById(\"word-table\").deleteRow(tableRows[i]); \n }; // end for\n }; // end if\n\n // ++ Log the data\n console.log(secretWord, secretWordArray)\n };// end resetGame\n\n// ===========>>> Create a fn to PROMPT for user input\n var getSecretWord = function () {\n // establish new game variables\n var spaces = /\\s+/gi\n secretWord = prompt(\"Enter a secret word\").replace(spaces, \"-\");\n secretWordArray = secretWord.toUpperCase().split(\"\");\n \n return secretWordArray\n };\n \n// ===========>>> Create a fn SHOW letters- via background color\n var revealLetter = function(myGuess) {\n var elms = document.getElementsByClassName(\"letter-\"+ myGuess);\n // match and change letters\n for(i=0; i>> Create a fn to SETUP the board\n var setBoard = function (array) {\n // Create the board based on secret word length\n var wordLength = array.length;\n // should only be one row but needed classes to eliminate excess\n // !!! set an id and a class for clearing rows\n var tableSet = document.getElementsByClassName(\"letters\");\n var tableRow = tableSet[0];\n \n // set loop to build the html game board (word only)\n for(i=0; i < wordLength; i++) {\n var newLetter = array[i]\n var dash = /[-]+/i\n\n var letterBox = document.createElement(\"td\");\n // establish class vs id in case duplicate letters in the word\n // set a general class for all letters\n letterBox.setAttribute(\"class\",\"single-letter letter-\"+ newLetter);\n\n // set the letter value for the table item (td)\n letterBox.innerHTML= newLetter;\n\n // add the item to the table row\n tableRow.appendChild(letterBox);\n\n }; // end for loop\n \n return\n };\n\n// ===========>>> Create a fn to check STATUS of revealed word\n\n // var wordRevealStatus = function (array) {\n // use the 'every' method on the word array to see if all are yet revealed (boolean)\n\n // if this is true, then delcare the game is over and reset the game\n // };\n\n\n\n// ---- BUTTONS ----\n\n// ===========>>> Set action of \"START\" button:initialize \n\n // !!! Refactor to pull additional functionality out of start button\n startButton.onclick = function () {\n\n // run the initializing function to clear the board\n initializeGame();\n\n // start game with prompt and setting up board\n var word = getSecretWord ();\n setBoard(word);\n \n // ++ test logging to verify word entry\n var nodesArray = wordTable.childNodes;\n console.log (nodesArray.length);\n return console.log (\"The secret word is \" + \"'\" + secretWord+\"'\"); \n };\n\n// ===========>>> Set action of \"GUESS\" button- guess a letter\n\n guessButton.onclick = function(){\n // take an input from player and make all caps to match case in the word array\n\n var guessLetter = prompt(\"guess a letter\").toUpperCase();\n // reveal if part of secret word\n revealLetter(guessLetter);\n // check status to see if all of the letters have been revealed\n };\n\n// ===========>>> Set the action for the \"RESET\" button \n\n resetButton.onclick = function(){\n \n resetGame();\n return initializeGame();\n // return alert('rest works!!!');\n };\n\n// ===========>>> Set the action for the \"WORD\" button \n // Button to select when ready to guess a word- connect to a form\n\n\n\n\n"} {"doc_id": "12303ef65ddf5ea719b7c1e8b3410d0d", "text": "/*\n

Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.

\n\n

Note:
\n

    \n
  1. Input contains only lowercase English letters.
  2. \n
  3. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as \"abc\" or \"zerone\" are not permitted.
  4. \n
  5. Input length is less than 50,000.
  6. \n
\n

\n\n

Example 1:
\n

\nInput: \"owoztneoer\"\n\nOutput: \"012\"\n
\n

\n\n

Example 2:
\n

\nInput: \"fviefuro\"\n\nOutput: \"45\"\n
\n

\u7ed9\u5b9a\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u4e32\uff0c\u5176\u4e2d\u5305\u542b\u5b57\u6bcd\u987a\u5e8f\u6253\u4e71\u7684\u82f1\u6587\u5355\u8bcd\u8868\u793a\u7684\u6570\u5b570-9\u3002\u6309\u5347\u5e8f\u8f93\u51fa\u539f\u59cb\u7684\u6570\u5b57\u3002

\n\n

\u6ce8\u610f:

\n\n
    \n\t
  1. \u8f93\u5165\u53ea\u5305\u542b\u5c0f\u5199\u82f1\u6587\u5b57\u6bcd\u3002
  2. \n\t
  3. \u8f93\u5165\u4fdd\u8bc1\u5408\u6cd5\u5e76\u53ef\u4ee5\u8f6c\u6362\u4e3a\u539f\u59cb\u7684\u6570\u5b57\uff0c\u8fd9\u610f\u5473\u7740\u50cf "abc" \u6216 "zerone" \u7684\u8f93\u5165\u662f\u4e0d\u5141\u8bb8\u7684\u3002
  4. \n\t
  5. \u8f93\u5165\u5b57\u7b26\u4e32\u7684\u957f\u5ea6\u5c0f\u4e8e 50,000\u3002
  6. \n
\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: "owoztneoer"\n\n\u8f93\u51fa: "012" (zeroonetwo)\n
\n\n

\u793a\u4f8b 2:

\n\n
\n\u8f93\u5165: "fviefuro"\n\n\u8f93\u51fa: "45" (fourfive)\n
\n

\u7ed9\u5b9a\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u4e32\uff0c\u5176\u4e2d\u5305\u542b\u5b57\u6bcd\u987a\u5e8f\u6253\u4e71\u7684\u82f1\u6587\u5355\u8bcd\u8868\u793a\u7684\u6570\u5b570-9\u3002\u6309\u5347\u5e8f\u8f93\u51fa\u539f\u59cb\u7684\u6570\u5b57\u3002

\n\n

\u6ce8\u610f:

\n\n
    \n\t
  1. \u8f93\u5165\u53ea\u5305\u542b\u5c0f\u5199\u82f1\u6587\u5b57\u6bcd\u3002
  2. \n\t
  3. \u8f93\u5165\u4fdd\u8bc1\u5408\u6cd5\u5e76\u53ef\u4ee5\u8f6c\u6362\u4e3a\u539f\u59cb\u7684\u6570\u5b57\uff0c\u8fd9\u610f\u5473\u7740\u50cf "abc" \u6216 "zerone" \u7684\u8f93\u5165\u662f\u4e0d\u5141\u8bb8\u7684\u3002
  4. \n\t
  5. \u8f93\u5165\u5b57\u7b26\u4e32\u7684\u957f\u5ea6\u5c0f\u4e8e 50,000\u3002
  6. \n
\n\n

\u793a\u4f8b 1:

\n\n
\n\u8f93\u5165: "owoztneoer"\n\n\u8f93\u51fa: "012" (zeroonetwo)\n
\n\n

\u793a\u4f8b 2:

\n\n
\n\u8f93\u5165: "fviefuro"\n\n\u8f93\u51fa: "45" (fourfive)\n
\n*/\n\n\n/**\n * @param {string} s\n * @return {string}\n */\nvar originalDigits = function(s) {\n \n};"} {"doc_id": "123539bb72de07d91b553cd73e8c7784", "text": "// JavaScript source code\nvar factorial = parseInt(prompt(\"Enter the number to factorialize\"));\nvar counter = factorial;\nvar total = 1;\n\nif (factorial > 0) {\n\twhile (counter > 1) {\n\t\ttotal *= counter;\n\t\tcounter--;\n\t}\n\twindow.alert(factorial + \"! = \" + total);\n} else {\n\twindow.alert(\"That number is invalid\");\n}"} {"doc_id": "1248637b0e01351a7c65bfc82e021c45", "text": "/*\n

Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.

If there is no answer, return the empty string.\n\n

Example 1:
\n

\nInput: \nwords = [\"w\",\"wo\",\"wor\",\"worl\", \"world\"]\nOutput: \"world\"\nExplanation: \nThe word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".\n
\n

\n\n

Example 2:
\n

\nInput: \nwords = [\"a\", \"banana\", \"app\", \"appl\", \"ap\", \"apply\", \"apple\"]\nOutput: \"apple\"\nExplanation: \nBoth \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".\n
\n

\n\n

Note:\n

  • All the strings in the input will only contain lowercase letters.
  • \n
  • The length of words will be in the range [1, 1000].
  • \n
  • The length of words[i] will be in the range [1, 30].
  • \n

    \u7ed9\u51fa\u4e00\u4e2a\u5b57\u7b26\u4e32\u6570\u7ec4words\u7ec4\u6210\u7684\u4e00\u672c\u82f1\u8bed\u8bcd\u5178\u3002\u4ece\u4e2d\u627e\u51fa\u6700\u957f\u7684\u4e00\u4e2a\u5355\u8bcd\uff0c\u8be5\u5355\u8bcd\u662f\u7531words\u8bcd\u5178\u4e2d\u5176\u4ed6\u5355\u8bcd\u9010\u6b65\u6dfb\u52a0\u4e00\u4e2a\u5b57\u6bcd\u7ec4\u6210\u3002\u82e5\u5176\u4e2d\u6709\u591a\u4e2a\u53ef\u884c\u7684\u7b54\u6848\uff0c\u5219\u8fd4\u56de\u7b54\u6848\u4e2d\u5b57\u5178\u5e8f\u6700\u5c0f\u7684\u5355\u8bcd\u3002

    \n\n

    \u82e5\u65e0\u7b54\u6848\uff0c\u5219\u8fd4\u56de\u7a7a\u5b57\u7b26\u4e32\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: \nwords = ["w","wo","wor","worl", "world"]\n\u8f93\u51fa: "world"\n\u89e3\u91ca: \n\u5355\u8bcd"world"\u53ef\u7531"w", "wo", "wor", \u548c "worl"\u6dfb\u52a0\u4e00\u4e2a\u5b57\u6bcd\u7ec4\u6210\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: \nwords = ["a", "banana", "app", "appl", "ap", "apply", "apple"]\n\u8f93\u51fa: "apple"\n\u89e3\u91ca: \n"apply"\u548c"apple"\u90fd\u80fd\u7531\u8bcd\u5178\u4e2d\u7684\u5355\u8bcd\u7ec4\u6210\u3002\u4f46\u662f"apple"\u5f97\u5b57\u5178\u5e8f\u5c0f\u4e8e"apply"\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n\n

    \u7ed9\u51fa\u4e00\u4e2a\u5b57\u7b26\u4e32\u6570\u7ec4words\u7ec4\u6210\u7684\u4e00\u672c\u82f1\u8bed\u8bcd\u5178\u3002\u4ece\u4e2d\u627e\u51fa\u6700\u957f\u7684\u4e00\u4e2a\u5355\u8bcd\uff0c\u8be5\u5355\u8bcd\u662f\u7531words\u8bcd\u5178\u4e2d\u5176\u4ed6\u5355\u8bcd\u9010\u6b65\u6dfb\u52a0\u4e00\u4e2a\u5b57\u6bcd\u7ec4\u6210\u3002\u82e5\u5176\u4e2d\u6709\u591a\u4e2a\u53ef\u884c\u7684\u7b54\u6848\uff0c\u5219\u8fd4\u56de\u7b54\u6848\u4e2d\u5b57\u5178\u5e8f\u6700\u5c0f\u7684\u5355\u8bcd\u3002

    \n\n

    \u82e5\u65e0\u7b54\u6848\uff0c\u5219\u8fd4\u56de\u7a7a\u5b57\u7b26\u4e32\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: \nwords = ["w","wo","wor","worl", "world"]\n\u8f93\u51fa: "world"\n\u89e3\u91ca: \n\u5355\u8bcd"world"\u53ef\u7531"w", "wo", "wor", \u548c "worl"\u6dfb\u52a0\u4e00\u4e2a\u5b57\u6bcd\u7ec4\u6210\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: \nwords = ["a", "banana", "app", "appl", "ap", "apply", "apple"]\n\u8f93\u51fa: "apple"\n\u89e3\u91ca: \n"apply"\u548c"apple"\u90fd\u80fd\u7531\u8bcd\u5178\u4e2d\u7684\u5355\u8bcd\u7ec4\u6210\u3002\u4f46\u662f"apple"\u5f97\u5b57\u5178\u5e8f\u5c0f\u4e8e"apply"\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n\n*/\n\n\n/**\n * @param {string[]} words\n * @return {string}\n */\nvar longestWord = function(words) {\n \n};"} {"doc_id": "1290281b3389e8031376fd4fa394220e", "text": "// if (1 + 1 === 2) {\n// console.log(\"Math still works.\");\n// }\n\n// let random = Math.random();\n// if (random < 0.5) {\n// console.log(\"winner!\");\n// console.log(random);\n// }\n\n// let dayOfWeek = prompt(\"What's your favorite day of the week? \").toLowerCase();\n\n// if (dayOfWeek === 'monday') {\n// console.log(\"Ugh, I hate Mondays!\");\n// } else if (dayOfWeek === 'saturday') {\n// console.log(\"Yay, I love Saturday!\");\n// } else {\n// console.log(\"Meh\")\n// }\n\n// Nesting\n// Checks user input (password) for length and no space\nlet password = prompt(\"Enter a new password: \");\nif (password.length >= 6) {\n if (password.indexOf(' ') !== -1) {\n console.log(\"Password cannot include spaces\");\n } else {\n console.log('Valid Password!')\n }\n} else {\n console.log(\"Password is too short!\");\n}"} {"doc_id": "12d9460ab290cc809bfe523a35a9db5b", "text": "/*\n

    X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X.  Each digit must be rotated - we cannot choose to leave it alone.

    \n\n

    A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

    \n\n

    Now given a positive number N, how many numbers X from 1 to N are good?

    \n\n
    \nExample:\nInput: 10\nOutput: 4\nExplanation: \nThere are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.\n
    \n\n

    Note:

    \n\n\n

    \u6211\u4eec\u79f0\u4e00\u4e2a\u6570 X \u4e3a\u597d\u6570, \u5982\u679c\u5b83\u7684\u6bcf\u4f4d\u6570\u5b57\u9010\u4e2a\u5730\u88ab\u65cb\u8f6c 180 \u5ea6\u540e\uff0c\u6211\u4eec\u4ecd\u53ef\u4ee5\u5f97\u5230\u4e00\u4e2a\u6709\u6548\u7684\uff0c\u4e14\u548c X \u4e0d\u540c\u7684\u6570\u3002\u8981\u6c42\u6bcf\u4f4d\u6570\u5b57\u90fd\u8981\u88ab\u65cb\u8f6c\u3002

    \n\n

    \u5982\u679c\u4e00\u4e2a\u6570\u7684\u6bcf\u4f4d\u6570\u5b57\u88ab\u65cb\u8f6c\u4ee5\u540e\u4ecd\u7136\u8fd8\u662f\u4e00\u4e2a\u6570\u5b57\uff0c \u5219\u8fd9\u4e2a\u6570\u662f\u6709\u6548\u7684\u30020, 1, \u548c 8 \u88ab\u65cb\u8f6c\u540e\u4ecd\u7136\u662f\u5b83\u4eec\u81ea\u5df1\uff1b2 \u548c 5 \u53ef\u4ee5\u4e92\u76f8\u65cb\u8f6c\u6210\u5bf9\u65b9\uff1b6 \u548c 9 \u540c\u7406\uff0c\u9664\u4e86\u8fd9\u4e9b\u4ee5\u5916\u5176\u4ed6\u7684\u6570\u5b57\u65cb\u8f6c\u4ee5\u540e\u90fd\u4e0d\u518d\u662f\u6709\u6548\u7684\u6570\u5b57\u3002

    \n\n

    \u73b0\u5728\u6211\u4eec\u6709\u4e00\u4e2a\u6b63\u6574\u6570 N, \u8ba1\u7b97\u4ece 1 \u5230 N \u4e2d\u6709\u591a\u5c11\u4e2a\u6570 X \u662f\u597d\u6570\uff1f

    \n\n
    \n\u793a\u4f8b:\n\u8f93\u5165: 10\n\u8f93\u51fa: 4\n\u89e3\u91ca: \n\u5728[1, 10]\u4e2d\u6709\u56db\u4e2a\u597d\u6570\uff1a 2, 5, 6, 9\u3002\n\u6ce8\u610f 1 \u548c 10 \u4e0d\u662f\u597d\u6570, \u56e0\u4e3a\u4ed6\u4eec\u5728\u65cb\u8f6c\u4e4b\u540e\u4e0d\u53d8\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n\n

    \u6211\u4eec\u79f0\u4e00\u4e2a\u6570 X \u4e3a\u597d\u6570, \u5982\u679c\u5b83\u7684\u6bcf\u4f4d\u6570\u5b57\u9010\u4e2a\u5730\u88ab\u65cb\u8f6c 180 \u5ea6\u540e\uff0c\u6211\u4eec\u4ecd\u53ef\u4ee5\u5f97\u5230\u4e00\u4e2a\u6709\u6548\u7684\uff0c\u4e14\u548c X \u4e0d\u540c\u7684\u6570\u3002\u8981\u6c42\u6bcf\u4f4d\u6570\u5b57\u90fd\u8981\u88ab\u65cb\u8f6c\u3002

    \n\n

    \u5982\u679c\u4e00\u4e2a\u6570\u7684\u6bcf\u4f4d\u6570\u5b57\u88ab\u65cb\u8f6c\u4ee5\u540e\u4ecd\u7136\u8fd8\u662f\u4e00\u4e2a\u6570\u5b57\uff0c \u5219\u8fd9\u4e2a\u6570\u662f\u6709\u6548\u7684\u30020, 1, \u548c 8 \u88ab\u65cb\u8f6c\u540e\u4ecd\u7136\u662f\u5b83\u4eec\u81ea\u5df1\uff1b2 \u548c 5 \u53ef\u4ee5\u4e92\u76f8\u65cb\u8f6c\u6210\u5bf9\u65b9\uff1b6 \u548c 9 \u540c\u7406\uff0c\u9664\u4e86\u8fd9\u4e9b\u4ee5\u5916\u5176\u4ed6\u7684\u6570\u5b57\u65cb\u8f6c\u4ee5\u540e\u90fd\u4e0d\u518d\u662f\u6709\u6548\u7684\u6570\u5b57\u3002

    \n\n

    \u73b0\u5728\u6211\u4eec\u6709\u4e00\u4e2a\u6b63\u6574\u6570 N, \u8ba1\u7b97\u4ece 1 \u5230 N \u4e2d\u6709\u591a\u5c11\u4e2a\u6570 X \u662f\u597d\u6570\uff1f

    \n\n
    \n\u793a\u4f8b:\n\u8f93\u5165: 10\n\u8f93\u51fa: 4\n\u89e3\u91ca: \n\u5728[1, 10]\u4e2d\u6709\u56db\u4e2a\u597d\u6570\uff1a 2, 5, 6, 9\u3002\n\u6ce8\u610f 1 \u548c 10 \u4e0d\u662f\u597d\u6570, \u56e0\u4e3a\u4ed6\u4eec\u5728\u65cb\u8f6c\u4e4b\u540e\u4e0d\u53d8\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n\n*/\n\n\n/**\n * @param {number} N\n * @return {number}\n */\nvar rotatedDigits = function(N) {\n \n};"} {"doc_id": "13fbcde7a7a47a102baf259161f4e791", "text": "/*\n

    \nGiven an array nums of integers, you can perform operations on the array.\n

    \nIn each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.\n

    \nYou start with 0 points. Return the maximum number of points you can earn by applying such operations.\n

    \n\n

    Example 1:
    \n

    \nInput: nums = [3, 4, 2]\nOutput: 6\nExplanation: \nDelete 4 to earn 4 points, consequently 3 is also deleted.\nThen, delete 2 to earn 2 points. 6 total points are earned.\n
    \n

    \n\n

    Example 2:
    \n

    \nInput: nums = [2, 2, 3, 3, 3, 4]\nOutput: 9\nExplanation: \nDelete 3 to earn 3 points, deleting both 2's and the 4.\nThen, delete 3 again to earn 3 points, and 3 again to earn 3 points.\n9 total points are earned.\n
    \n

    \n\n

    Note:\n

  • The length of nums is at most 20000.
  • \n
  • Each element nums[i] is an integer in the range [1, 10000].
  • \n

    \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u6570\u7ec4 nums \uff0c\u4f60\u53ef\u4ee5\u5bf9\u5b83\u8fdb\u884c\u4e00\u4e9b\u64cd\u4f5c\u3002

    \n\n

    \u6bcf\u6b21\u64cd\u4f5c\u4e2d\uff0c\u9009\u62e9\u4efb\u610f\u4e00\u4e2a nums[i] \uff0c\u5220\u9664\u5b83\u5e76\u83b7\u5f97 nums[i] \u7684\u70b9\u6570\u3002\u4e4b\u540e\uff0c\u4f60\u5fc5\u987b\u5220\u9664\u6bcf\u4e2a\u7b49\u4e8e nums[i] - 1 \u6216 nums[i] + 1 \u7684\u5143\u7d20\u3002

    \n\n

    \u5f00\u59cb\u4f60\u62e5\u6709 0 \u4e2a\u70b9\u6570\u3002\u8fd4\u56de\u4f60\u80fd\u901a\u8fc7\u8fd9\u4e9b\u64cd\u4f5c\u83b7\u5f97\u7684\u6700\u5927\u70b9\u6570\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: nums = [3, 4, 2]\n\u8f93\u51fa: 6\n\u89e3\u91ca: \n\u5220\u9664 4 \u6765\u83b7\u5f97 4 \u4e2a\u70b9\u6570\uff0c\u56e0\u6b64 3 \u4e5f\u88ab\u5220\u9664\u3002\n\u4e4b\u540e\uff0c\u5220\u9664 2 \u6765\u83b7\u5f97 2 \u4e2a\u70b9\u6570\u3002\u603b\u5171\u83b7\u5f97 6 \u4e2a\u70b9\u6570\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: nums = [2, 2, 3, 3, 3, 4]\n\u8f93\u51fa: 9\n\u89e3\u91ca: \n\u5220\u9664 3 \u6765\u83b7\u5f97 3 \u4e2a\u70b9\u6570\uff0c\u63a5\u7740\u8981\u5220\u9664\u4e24\u4e2a 2 \u548c 4 \u3002\n\u4e4b\u540e\uff0c\u518d\u6b21\u5220\u9664 3 \u83b7\u5f97 3 \u4e2a\u70b9\u6570\uff0c\u518d\u6b21\u5220\u9664 3 \u83b7\u5f97 3 \u4e2a\u70b9\u6570\u3002\n\u603b\u5171\u83b7\u5f97 9 \u4e2a\u70b9\u6570\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n\n

    \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u6570\u7ec4 nums \uff0c\u4f60\u53ef\u4ee5\u5bf9\u5b83\u8fdb\u884c\u4e00\u4e9b\u64cd\u4f5c\u3002

    \n\n

    \u6bcf\u6b21\u64cd\u4f5c\u4e2d\uff0c\u9009\u62e9\u4efb\u610f\u4e00\u4e2a nums[i] \uff0c\u5220\u9664\u5b83\u5e76\u83b7\u5f97 nums[i] \u7684\u70b9\u6570\u3002\u4e4b\u540e\uff0c\u4f60\u5fc5\u987b\u5220\u9664\u6bcf\u4e2a\u7b49\u4e8e nums[i] - 1 \u6216 nums[i] + 1 \u7684\u5143\u7d20\u3002

    \n\n

    \u5f00\u59cb\u4f60\u62e5\u6709 0 \u4e2a\u70b9\u6570\u3002\u8fd4\u56de\u4f60\u80fd\u901a\u8fc7\u8fd9\u4e9b\u64cd\u4f5c\u83b7\u5f97\u7684\u6700\u5927\u70b9\u6570\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: nums = [3, 4, 2]\n\u8f93\u51fa: 6\n\u89e3\u91ca: \n\u5220\u9664 4 \u6765\u83b7\u5f97 4 \u4e2a\u70b9\u6570\uff0c\u56e0\u6b64 3 \u4e5f\u88ab\u5220\u9664\u3002\n\u4e4b\u540e\uff0c\u5220\u9664 2 \u6765\u83b7\u5f97 2 \u4e2a\u70b9\u6570\u3002\u603b\u5171\u83b7\u5f97 6 \u4e2a\u70b9\u6570\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: nums = [2, 2, 3, 3, 3, 4]\n\u8f93\u51fa: 9\n\u89e3\u91ca: \n\u5220\u9664 3 \u6765\u83b7\u5f97 3 \u4e2a\u70b9\u6570\uff0c\u63a5\u7740\u8981\u5220\u9664\u4e24\u4e2a 2 \u548c 4 \u3002\n\u4e4b\u540e\uff0c\u518d\u6b21\u5220\u9664 3 \u83b7\u5f97 3 \u4e2a\u70b9\u6570\uff0c\u518d\u6b21\u5220\u9664 3 \u83b7\u5f97 3 \u4e2a\u70b9\u6570\u3002\n\u603b\u5171\u83b7\u5f97 9 \u4e2a\u70b9\u6570\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n\n*/\n\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar deleteAndEarn = function(nums) {\n \n};"} {"doc_id": "15ea58ee97dbec6e146d953faf3c761c", "text": "/** Linked List Construction\nWrite a DoublyLinkedList class that has a head and a tail, both of\nwhich point to either a linked list Node or None / null . The class should\nsupport:\n- Setting the head and tail of the linked list.\n- Inserting nodes before and after other nodes as well as at given\npositions.\n- Removing given nodes and removing nodes with given values;\n- Searching for nodes with given values.\nEach Node has an integer value as well as a prev node and a next\nnode, both of which can point to either another node or None / null.\n\nSample Usage:\n/ / Assume the following linked list has already been created:\n1 <-> 2 <-> 3 <-> 4 <-> 5 \nsetHead (4): 4 <-> 1 <-> 2 <-> 3 <-> 5 // set the existing node with value 4 as the head\nset Tail (6): 4 <-> 1 <-> 2 <-> 3 <-> 5 <-> 6 // set the existing node with value 6 as the tail\ninsertBefore (6, 3): 4 <-> 1 <-> 2 <-> 5 <-> 3 <-> 6 // move the existing node with value 3 before the existing node with value 6\ninsertAfter(6, 3): 4 <-> 1 <-> 2 <-> 5 <-> 3 <-> 6 <-> 3 // insert a new node with value 3 after the existing node with value 6\ninsertAtPosition(1, 3): 3 <-> 4 <-> 1 <-> 2 <-> 5 <-> 3 <-> 6 <-> 3 // insert a new node with value 3 in position 1\nremoveNodesWithValue(3): 4 <-> 1 <-> 2 <-> 5 <-> 6 // remove all nodes with value 3\nremove(2): 4 <-> 1 <-> 5 <-> 6 // remove the existing node with value 2\ncontainsNodeWithVa1ue(5} : true\n\n */\n\n // This is an input class. Do not edit.\nclass Node {\n constructor(value) {\n this.value = value;\n this.prev = null;\n this.next = null;\n }\n }\n \n // Feel free to add new properties and methods to the class.\n class DoublyLinkedList {\n constructor() {\n this.head = null;\n this.tail = null;\n }\n \n setHead(node) {\n // Write your code here.\n }\n \n setTail(node) {\n // Write your code here.\n }\n \n insertBefore(node, nodeToInsert) {\n // Write your code here.\n }\n \n insertAfter(node, nodeToInsert) {\n // Write your code here.\n }\n \n insertAtPosition(position, nodeToInsert) {\n // Write your code here.\n }\n \n removeNodesWithValue(value) {\n // Write your code here.\n }\n \n remove(node) {\n // Write your code here.\n }\n \n containsNodeWithValue(value) {\n // Write your code here.\n }\n }\n \n // Do not edit the line below.\n exports.Node = Node;\n exports.DoublyLinkedList = DoublyLinkedList;\n "} {"doc_id": "16a99396c3f80c38b598753fdf1753dd", "text": "/*\n

    \nGiven a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such\nthat i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.

    \n\n

    Note: n will be less than 15,000.

    \n\n

    Example 1:
    \n

    \nInput: [1, 2, 3, 4]\n\nOutput: False\n\nExplanation: There is no 132 pattern in the sequence.\n
    \n

    \n\n

    Example 2:
    \n

    \nInput: [3, 1, 4, 2]\n\nOutput: True\n\nExplanation: There is a 132 pattern in the sequence: [1, 4, 2].\n
    \n

    \n\n

    Example 3:
    \n

    \nInput: [-1, 3, 2, 0]\n\nOutput: True\n\nExplanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].\n
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u5e8f\u5217\uff1aa1, a2, ..., an\uff0c\u4e00\u4e2a132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217 ai, aj, ak \u88ab\u5b9a\u4e49\u4e3a\uff1a\u5f53 i < j < k \u65f6\uff0cai < ak < aj\u3002\u8bbe\u8ba1\u4e00\u4e2a\u7b97\u6cd5\uff0c\u5f53\u7ed9\u5b9a\u6709 n \u4e2a\u6570\u5b57\u7684\u5e8f\u5217\u65f6\uff0c\u9a8c\u8bc1\u8fd9\u4e2a\u5e8f\u5217\u4e2d\u662f\u5426\u542b\u6709132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217\u3002

    \n\n

    \u6ce8\u610f\uff1an \u7684\u503c\u5c0f\u4e8e15000\u3002

    \n\n

    \u793a\u4f8b1:

    \n\n
    \n\u8f93\u5165: [1, 2, 3, 4]\n\n\u8f93\u51fa: False\n\n\u89e3\u91ca: \u5e8f\u5217\u4e2d\u4e0d\u5b58\u5728132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: [3, 1, 4, 2]\n\n\u8f93\u51fa: True\n\n\u89e3\u91ca: \u5e8f\u5217\u4e2d\u6709 1 \u4e2a132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217\uff1a [1, 4, 2].\n
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \n\u8f93\u5165: [-1, 3, 2, 0]\n\n\u8f93\u51fa: True\n\n\u89e3\u91ca: \u5e8f\u5217\u4e2d\u6709 3 \u4e2a132\u6a21\u5f0f\u7684\u7684\u5b50\u5e8f\u5217: [-1, 3, 2], [-1, 3, 0] \u548c [-1, 2, 0].\n
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u5e8f\u5217\uff1aa1, a2, ..., an\uff0c\u4e00\u4e2a132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217 ai, aj, ak \u88ab\u5b9a\u4e49\u4e3a\uff1a\u5f53 i < j < k \u65f6\uff0cai < ak < aj\u3002\u8bbe\u8ba1\u4e00\u4e2a\u7b97\u6cd5\uff0c\u5f53\u7ed9\u5b9a\u6709 n \u4e2a\u6570\u5b57\u7684\u5e8f\u5217\u65f6\uff0c\u9a8c\u8bc1\u8fd9\u4e2a\u5e8f\u5217\u4e2d\u662f\u5426\u542b\u6709132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217\u3002

    \n\n

    \u6ce8\u610f\uff1an \u7684\u503c\u5c0f\u4e8e15000\u3002

    \n\n

    \u793a\u4f8b1:

    \n\n
    \n\u8f93\u5165: [1, 2, 3, 4]\n\n\u8f93\u51fa: False\n\n\u89e3\u91ca: \u5e8f\u5217\u4e2d\u4e0d\u5b58\u5728132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: [3, 1, 4, 2]\n\n\u8f93\u51fa: True\n\n\u89e3\u91ca: \u5e8f\u5217\u4e2d\u6709 1 \u4e2a132\u6a21\u5f0f\u7684\u5b50\u5e8f\u5217\uff1a [1, 4, 2].\n
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \n\u8f93\u5165: [-1, 3, 2, 0]\n\n\u8f93\u51fa: True\n\n\u89e3\u91ca: \u5e8f\u5217\u4e2d\u6709 3 \u4e2a132\u6a21\u5f0f\u7684\u7684\u5b50\u5e8f\u5217: [-1, 3, 2], [-1, 3, 0] \u548c [-1, 2, 0].\n
    \n*/\n\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nvar find132pattern = function(nums) {\n \n};"} {"doc_id": "17a218b62648ece24fe8101886d521fd", "text": "/**\n * Created by\uff1aCaMnter\n */\n\n/****************\n * ES6 Set \u57fa\u672c *\n ****************/\n\n/**\n * ES6 \u63d0\u4f9b\u4e86\u65b0\u7684\u6570\u636e\u7ed3\u6784 Set\n * \u5b83\u7c7b\u4f3c\u4e8e\u6570\u7ec4\n * \u4f46\u662f\u6210\u5458\u7684\u503c\u90fd\u662f\u552f\u4e00\u7684\n * \u6ca1\u6709\u91cd\u590d\u7684\u503c\n */\n\n(() => {\n var set = new Set();\n // \u6dfb\u52a0\u91cd\u590d\u503c\u65e0\u6548\n [2, 3, 3].map(v => set.add(v));\n console.log(\"[structure]\\t\\t[test-\" + 1 + \"]\\t\\t[value] = \", [...set], '\\n');\n})();\n\n/**\n * \u6570\u7ec4\u4f5c\u4e3a\u53c2\u6570\n */\n(() => {\n var set1 = new Set([1, 2, 3, 4]);\n for (let value of set1) {\n console.log(\"[structure]\\t\\t[test-\" + 2 + \"]\\t\\t[value] = \", value);\n }\n console.log('');\n\n var set2 = new Set([2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]);\n console.log(\"[structure]\\t\\t[test-\" + 3 + \"]\\t\\t[set2.size] = \", set2.size, '\\n');\n\n function getArray() {\n let array = [2, 3, 3]\n return [...array];\n }\n\n var set3 = new Set(getArray());\n console.log(\"[structure]\\t\\t[test-\" + 4 + \"]\\t\\t[set3] = \", set3, '\\n');\n\n var set4 = new Set();\n getArray().forEach(v => set4.add(v));\n console.log(\"[structure]\\t\\t[test-\" + 5 + \"]\\t\\t[set4] = \", set4, '\\n');\n})();\n\n\n/**\n * \u4f7f\u7528\u6280\u5de7\uff1a\n *\n * \u5229\u7528 Set\n * \u53bb\u9664\u6570\u7ec4\u4e2d\u7684\u91cd\u590d\u503c\n * \u7136\u540e\u5f97\u5230\u6570\u7ec4\n */\n\n(() => {\n let array = [2, 3, 3, 3, 3, 3, 3];\n console.log(\"[structure]\\t\\t[test-\" + 6 + \"]\\t\\t[...new Set(array)] = \", [...new Set(array)], '\\n');\n})();\n\n/**\n * Set \u52a0\u5165\u503c\n * \u4e0d\u4f1a\u53d1\u751f\u7c7b\u578b\u8f6c\u6362\n *\n * 2 \u548c \"2\" \u662f\u4e24\u4e2a\u4e0d\u540c\u7684\u503c\n * Set \u5b83\u4eec\u662f\u4e0d\u540c\u7684\n * \u4f7f\u7528\u7684\u7b97\u6cd5\u53eb\u505a Same-value equality\n *\n * \u7c7b\u4f3c\u4e8e\u7cbe\u786e\u76f8\u7b49\u8fd0\u7b97\u7b26\uff08===\uff09\n * \u4e3b\u8981\u7684\u533a\u522b\u662f NaN \u7b49\u4e8e\u81ea\u8eab\uff0c\u800c\u7cbe\u786e\u76f8\u7b49\u8fd0\u7b97\u7b26\u8ba4\u4e3a NaN \u4e0d\u7b49\u4e8e\u81ea\u8eab\n */\n(() => {\n let set = new Set();\n set.add(NaN);\n set.add(NaN);\n console.log(\"[structure]\\t\\t[test-\" + 6 + \"]\\t\\t[set] = \", set);\n set.clear();\n\n set.add(2);\n set.add(\"2\");\n console.log(\"[structure]\\t\\t[test-\" + 6 + \"]\\t\\t[set] = \", set, '\\n');\n set.clear();\n})();\n\n/**\n * \u7a7a\u5bf9\u8c61\u662f\u4e0d\u76f8\u7b49\u7684\n */\n(() => {\n let set = new Set();\n set.add({}).add({}).add({}).add({}).add({}).add({});\n console.log(\"[structure]\\t\\t[test-\" + 7 + \"]\\t\\t[set] = \", set);\n})();"} {"doc_id": "17c2eca03a9f05d0f5fcebb02a60bc6b", "text": "\n/*\nPseudocode - create 3 functions to apply to an array of numbers\n\nCreate a function called 'sum' \n\nsum will have an array of numbers as its argument\n\nsum will add the numbers within that array\n\n--------------------------------------------------\n\nCreate a new function called 'mean'\n\nmean will average all the numbers within the array of numbers\n\n--------------------------------------------------------\n\nCreate a function called 'median'\n\nmedian will find the middle value from the array of numbers. If there is no single middle number, the function should average the 2 middle numbers\n*/\n//User Story 1: As a user, I'll want to sum the numbers in a list of numbers.\n\nvar sum = function(numbers){\n\n var add = 0\n for(var i = 0; i < numbers.length; i++){\n add += numbers[i];\n }\n\n console.log(add);\n}\n\n\nsum([1,2,3,4,5])\n\n\n/*############################################*/\n\n//User Story 2: As a user, I'll want to find the average within a list of numbers.\n\nvar mean = function(numbers){\n\n var answer = 0;\n var totalNumbers = numbers.length;\n var add = 0;\n\n for(var i = 0; i < totalNumbers; i++){\n add += numbers[i];\n }\n\n answer = (add / totalNumbers);\n\n console.log(answer);\n}\n\nmean([1,2,3,5,5])\n\n/*############################################*/\n\n//User Story 3: As a user, I'll want to find the middle number within a list of numbers, or both middle numbers if the list is even.\n\nvar median = function(numbers){\n\n var index = 0;\n var totalNumbers = numbers.length;\n var results = 0;\n\n var results = [];\n\n if (totalNumbers % 2 != 0){\n index = Math.floor(totalNumbers / 2);\n results = numbers[index];\n }\n \n else if (totalNumbers % 2 == 0){\n index = Math.floor(totalNumbers / 2);\n results = (numbers[index] + numbers[index-1]) / 2;\n\n\n\n }\n\n console.log(results);\n\n}\n\nmedian([1, 1, 2, 5, 6, 6, 9])\nmedian([1, 1, 2, 6, 6, 9])\n"} {"doc_id": "17f70b9a8bc7363658008c331ad5b643", "text": "\"use strict\";\n\n/**\n * TODO:\n * Write some JavaScript that uses a `confirm` dialog to ask the user if they\n * would like to enter a number. If they click 'Ok', prompt the user for a\n * number, then use 3 separate alerts to tell the user:\n *\n * - whether the number is even or odd\n * - what the number plus 100 is\n * - if the number is negative or positive\n *\n * if what the user enters is not a number, use an alert to tell them that, and\n * do *not* display any of the above information.\n *\n * Can you refactor your code to use functions?\n */\n\n//\n// function enterNumber(number){\n// confirm(\"would you like to enter a number?\");\n// number = prompt(\"Please enter a number...\");\n//\n// if(number % 2 === 0){\n// alert(\"this number is even\");\n// } else {\n// alert(\"this number is odd\");\n// }\n//\n// alert((number) + \" plus 100 is: \" + (parseInt(number) + 100));\n//\n// if(number > 0){\n// alert(\"this number is positive\");\n// } else {\n// alert(\"this number is negative.\");\n// }\n//\n// return \"thank you for participating!\";\n// }\n//\n// enterNumber();\n/* ########################################################################## */\n\n/**\n * TODO:\n * Create a function named `analyzeColor` that accepts a string that is a color\n * name as input. This function should return a message that related to that\n * color. Only worry about the colors defined above, if the color passed is not\n * one of the ones defined above, return a message that says so\n *\n * Example:\n * > analyzeColor('blue') // returns \"blue is the color of the sky\"\n * > analyzeColor('red') // returns \"Strawberries are red\"\n * > analyzeColor('cyan') // returns \"I don't know anything about cyan\"\n *\n * You should use an if-else-if-else block to return different messages.\n *\n * Test your function by passing various string literals to it and\n * console.logging the function's return value\n */\n\n// function analyzeColor(anyColorString) {\n// anyColorString = prompt(\"please enter a color here...\");\n// switch (anyColorString){\n// case(\"red\"):\n// return \"Strawberries are red\"\n// break;\n// case(\"orange\"):\n// return \"Orange is my favorite color!\"\n// break;\n// case(\"yellow\"):\n// return \"bananas are yellow\"\n// break;\n// case(\"green\"):\n// return \"grass is always greener\"\n// break;\n// case(\"blue\"):\n// return \"the sky is blue\");\n// break;\n// case(\"indigo\"):\n// return \"there is a pokemon indigo league\"\n// break;\n// case(\"violet\"):\n// return \"are violets really violet?\"\n// break;\n// default:\n// return \"I have never heard of that color\"\n// break;\n// }\n// }\n\n// analyzeColor();\n\n\n\n// Don't change the next two lines!\n// These lines create two variables for you:\n// - `colors`: a list of the colors of the rainbow\n// - `randomColor`: contains a single random color value from the list (this\n// will contain a different color everytime the page loads)\nvar colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];\nvar randomColor = colors[Math.floor(Math.random() * colors.length)];\n/**\n * TODO:\n * Pass the `randomColor` variable to your function and console.log the results.\n * You should see a different message everytime you refresh the page\n */\n\n/**\n * TODO:\n * Refactor your above function to use a switch-case statement\n */\n\n/**\n * TODO:\n * Prompt the user for a color when the page loads, and pass the input from the\n * user to your `analyzeColor` function. Alert the return value from your\n * function to show it to the user.\n */\n\n/* ########################################################################## */\n\n/**\n * TODO:\n * Suppose there's a promotion in Walmart, each customer is given a randomly\n * generated \"lucky number\" between 0 and 5. If your lucky number is 0 you have\n * no discount, if your lucky number is 1 you'll get a 10% discount, if it's 2,\n * the discount is 25%, if it's 3, 35%, if it's 4, 50%, and if it's 5 you'll get\n * all for free!.\n *\n * Write a function named `calculateTotal` that accepts a lucky number and total\n * amount, and returns the discounted price.\n *\n * Example:\n * calculateTotal(0, 100) // returns 100\n * calculateTotal(4, 100) // returns 50\n * calculateTotal(5, 100) // returns 0\n *\n * Test your function by passing it various values and checking for the expected\n * return value.\n */\n\n// var luckyNumber = Math.floor(Math.random()* 6)\n// var pay = 60\n// var total;\n//\n// switch (luckyNumber) {\n// case \"1\":\n// total = .9 * pay;\n// break;\n// case \"2\":\n// total = pay * .75;\n// break;\n// case \"4\":\n// total = pay * .5;\n// break;\n// case \"5\":\n// total = 0;\n// break;\n// default:\n// total = pay;\n// break;\n// }\n//\n// console.log(\"your total pay is \" + total);\n\n\n/**\n * TODO:\n * Uncomment the line below to generate a random number between 0 and 6.\n * Prompt the user for their total bill, then use your `calculateTotal` function\n * and alerts to display to the user what their lucky number was, what their\n * price before the discount was, and what their price after the discount is.\n */\n// Generate a random number between 0 and 6\n// var luckyNumber = Math.floor(Math.random() * 6);\n\n\n\n/*bonuses\n===============================================================\n */\n\n// write a function (or multiple functions) that will return\n// a boolean depending on if the string value passed to it\n// as an argument is the name of a day of the week that starts with a T.\n// Otherwise, it should return false.\n\n// Example: dayOfTheWeekStartsWithT(\"Monday\") => returns false\n// Example: dayOfTheWeekStartsWithT(\"Tuesday\") => returns true\n// Example: dayOfTheWeekStartsWithT(\"Tommy\") => returns false\nfunction dayOfTheWeekStartsWithT(day) {\n day = prompt(\"What day starts with T?\");\n switch (day){\n case \"Monday\":\n alert(\"false\");\n break;\n case \"Tuesday\":\n alert(\"true\");\n break;\n case \"Wednesday\":\n alert(\"false\");\n break;\n case \"Thursday\":\n alert(\"true\");\n break;\n case \"Friday\":\n alert(\"false\");\n break;\n default:\n alert(\"false\");\n }\n}\n\nconsole.log(dayOfTheWeekStartsWithT());\n\n/*bonus 2\n===============================================================================\n */\n// Write a function, isValidPassword, that takes in a string argument and returns true or false\n// depending on whether or not all the following conditions are true:\n// 1) Must be 6 characters long (only for the sake of this exercise, NOT a best practice)\n// 2) Contains at least one letter and one number\n// 3) Contains at least one upper and one lower case letter\n// 4) Only comprised of letters and numbers\n// 5) EXTRA BONUS: is not the same forwards and backwards\n\n\nfunction isValidPassword(password) {\n\n\n}\n\n"} {"doc_id": "17fc0b04921459c8f8acee5abc6f8b13", "text": "/*\n

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

    \n\n

    An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

    \n\n

    Example:\n

    \nInput:\n[[10,16], [2,8], [1,6], [7,12]]\n\nOutput:\n2\n\nExplanation:\nOne way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).\n
    \n

    \u5728\u4e8c\u7ef4\u7a7a\u95f4\u4e2d\u6709\u8bb8\u591a\u7403\u5f62\u7684\u6c14\u7403\u3002\u5bf9\u4e8e\u6bcf\u4e2a\u6c14\u7403\uff0c\u63d0\u4f9b\u7684\u8f93\u5165\u662f\u6c34\u5e73\u65b9\u5411\u4e0a\uff0c\u6c14\u7403\u76f4\u5f84\u7684\u5f00\u59cb\u548c\u7ed3\u675f\u5750\u6807\u3002\u7531\u4e8e\u5b83\u662f\u6c34\u5e73\u7684\uff0c\u6240\u4ee5y\u5750\u6807\u5e76\u4e0d\u91cd\u8981\uff0c\u56e0\u6b64\u53ea\u8981\u77e5\u9053\u5f00\u59cb\u548c\u7ed3\u675f\u7684x\u5750\u6807\u5c31\u8db3\u591f\u4e86\u3002\u5f00\u59cb\u5750\u6807\u603b\u662f\u5c0f\u4e8e\u7ed3\u675f\u5750\u6807\u3002\u5e73\u9762\u5185\u6700\u591a\u5b58\u5728104\u4e2a\u6c14\u7403\u3002

    \n\n

    \u4e00\u652f\u5f13\u7bad\u53ef\u4ee5\u6cbf\u7740x\u8f74\u4ece\u4e0d\u540c\u70b9\u5b8c\u5168\u5782\u76f4\u5730\u5c04\u51fa\u3002\u5728\u5750\u6807x\u5904\u5c04\u51fa\u4e00\u652f\u7bad\uff0c\u82e5\u6709\u4e00\u4e2a\u6c14\u7403\u7684\u76f4\u5f84\u7684\u5f00\u59cb\u548c\u7ed3\u675f\u5750\u6807\u4e3a xstart\uff0cxend\uff0c \u4e14\u6ee1\u8db3  xstart ≤ x ≤ xend\uff0c\u5219\u8be5\u6c14\u7403\u4f1a\u88ab\u5f15\u7206\u3002\u53ef\u4ee5\u5c04\u51fa\u7684\u5f13\u7bad\u7684\u6570\u91cf\u6ca1\u6709\u9650\u5236\u3002 \u5f13\u7bad\u4e00\u65e6\u88ab\u5c04\u51fa\u4e4b\u540e\uff0c\u53ef\u4ee5\u65e0\u9650\u5730\u524d\u8fdb\u3002\u6211\u4eec\u60f3\u627e\u5230\u4f7f\u5f97\u6240\u6709\u6c14\u7403\u5168\u90e8\u88ab\u5f15\u7206\uff0c\u6240\u9700\u7684\u5f13\u7bad\u7684\u6700\u5c0f\u6570\u91cf\u3002

    \n\n

    Example:

    \n\n
    \n\u8f93\u5165:\n[[10,16], [2,8], [1,6], [7,12]]\n\n\u8f93\u51fa:\n2\n\n\u89e3\u91ca:\n\u5bf9\u4e8e\u8be5\u6837\u4f8b\uff0c\u6211\u4eec\u53ef\u4ee5\u5728x = 6\uff08\u5c04\u7206[2,8],[1,6]\u4e24\u4e2a\u6c14\u7403\uff09\u548c x = 11\uff08\u5c04\u7206\u53e6\u5916\u4e24\u4e2a\u6c14\u7403\uff09\u3002\n
    \n

    \u5728\u4e8c\u7ef4\u7a7a\u95f4\u4e2d\u6709\u8bb8\u591a\u7403\u5f62\u7684\u6c14\u7403\u3002\u5bf9\u4e8e\u6bcf\u4e2a\u6c14\u7403\uff0c\u63d0\u4f9b\u7684\u8f93\u5165\u662f\u6c34\u5e73\u65b9\u5411\u4e0a\uff0c\u6c14\u7403\u76f4\u5f84\u7684\u5f00\u59cb\u548c\u7ed3\u675f\u5750\u6807\u3002\u7531\u4e8e\u5b83\u662f\u6c34\u5e73\u7684\uff0c\u6240\u4ee5y\u5750\u6807\u5e76\u4e0d\u91cd\u8981\uff0c\u56e0\u6b64\u53ea\u8981\u77e5\u9053\u5f00\u59cb\u548c\u7ed3\u675f\u7684x\u5750\u6807\u5c31\u8db3\u591f\u4e86\u3002\u5f00\u59cb\u5750\u6807\u603b\u662f\u5c0f\u4e8e\u7ed3\u675f\u5750\u6807\u3002\u5e73\u9762\u5185\u6700\u591a\u5b58\u5728104\u4e2a\u6c14\u7403\u3002

    \n\n

    \u4e00\u652f\u5f13\u7bad\u53ef\u4ee5\u6cbf\u7740x\u8f74\u4ece\u4e0d\u540c\u70b9\u5b8c\u5168\u5782\u76f4\u5730\u5c04\u51fa\u3002\u5728\u5750\u6807x\u5904\u5c04\u51fa\u4e00\u652f\u7bad\uff0c\u82e5\u6709\u4e00\u4e2a\u6c14\u7403\u7684\u76f4\u5f84\u7684\u5f00\u59cb\u548c\u7ed3\u675f\u5750\u6807\u4e3a xstart\uff0cxend\uff0c \u4e14\u6ee1\u8db3  xstart ≤ x ≤ xend\uff0c\u5219\u8be5\u6c14\u7403\u4f1a\u88ab\u5f15\u7206\u3002\u53ef\u4ee5\u5c04\u51fa\u7684\u5f13\u7bad\u7684\u6570\u91cf\u6ca1\u6709\u9650\u5236\u3002 \u5f13\u7bad\u4e00\u65e6\u88ab\u5c04\u51fa\u4e4b\u540e\uff0c\u53ef\u4ee5\u65e0\u9650\u5730\u524d\u8fdb\u3002\u6211\u4eec\u60f3\u627e\u5230\u4f7f\u5f97\u6240\u6709\u6c14\u7403\u5168\u90e8\u88ab\u5f15\u7206\uff0c\u6240\u9700\u7684\u5f13\u7bad\u7684\u6700\u5c0f\u6570\u91cf\u3002

    \n\n

    Example:

    \n\n
    \n\u8f93\u5165:\n[[10,16], [2,8], [1,6], [7,12]]\n\n\u8f93\u51fa:\n2\n\n\u89e3\u91ca:\n\u5bf9\u4e8e\u8be5\u6837\u4f8b\uff0c\u6211\u4eec\u53ef\u4ee5\u5728x = 6\uff08\u5c04\u7206[2,8],[1,6]\u4e24\u4e2a\u6c14\u7403\uff09\u548c x = 11\uff08\u5c04\u7206\u53e6\u5916\u4e24\u4e2a\u6c14\u7403\uff09\u3002\n
    \n*/\n\n\n/**\n * @param {number[][]} points\n * @return {number}\n */\nvar findMinArrowShots = function(points) {\n \n};"} {"doc_id": "18685ec2ff3e77d260df567826bf4bfc", "text": "var numeroSecreto = parseInt(Math.random() * 11);\n//var numeroLimite = 10;\n\nfunction Chutar() {\n var chute = parseInt(document.getElementById(\"valor\").value);\n\n var elementoResultado = document.getElementById(\"resultado\");\n\n //console.log(chute);\n\n if (chute == numeroSecreto) {\n // console.log(\"acertou\");\n\n elementoResultado.innerHTML = \"Acertou, mizeravi!\";\n } else if (chute > 10 || chute < 0) {\n //console.log(\"Digitar um n\u00famero entre 0 a 10 voc\u00ea deve\");\n\n elementoResultado.innerHTML = \"Digitar um n\u00famero entre 0 a 10 voc\u00ea deve\";\n } else {\n //console.log(\"Errowwwww! O n\u00famero secreto era \" + numeroSecreto);\n\n elementoResultado.innerHTML =\n \"Errowwwww! O n\u00famero secreto era \" + numeroSecreto;\n }\n}"} {"doc_id": "18edb35dd48c7ef6ca240a92fad46804", "text": "/*\nA valid parentheses string is either empty (\"\"), \"(\" + A + \")\", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, \"\", \"()\", \"(())()\", and \"(()(()))\" are all valid parentheses strings.\n\nA valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.\n\nGiven a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.\n\nReturn S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.\n\n \n\nExample 1:\n\nInput: \"(()())(())\"\nOutput: \"()()()\"\nExplanation: \nThe input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".\nExample 2:\n\nInput: \"(()())(())(()(()))\"\nOutput: \"()()()()(())\"\nExplanation: \nThe input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".\nExample 3:\n\nInput: \"()()\"\nOutput: \"\"\nExplanation: \nThe input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".\n \n\nNote:\n\nS.length <= 10000\nS[i] is \"(\" or \")\"\nS is a valid parentheses string\n*/\nvar removeOuterParentheses = function(S) {\n let parenthesCount = 0;\n let result = \"\";\n for (const letter of S) {\n if (letter === \"(\") {\n if (parenthesCount) {\n result += letter;\n }\n parenthesCount++;\n } else {\n parenthesCount--;\n if (parenthesCount) {\n result += letter;\n }\n }\n }\n \n return result;\n};\n"} {"doc_id": "196e912802fadab9879e7219881e5947", "text": "/*----------UNDERSTANDING THE PROBLEM----------\n- Expected Input(s):\n - Number of Inputs: 2\n - Types (respectively): Number (an integer), Array\n - Names/Values (respectively): 'k', 'numbers'\n\n- Expected Output(s):\n - Number of Outputs: 1 (with 2 possibilities)\n - Type: String\n - Names/Values (respectively): 'Yes', 'No'\n\n- Constraints:\n - Each element in the array occurs in EXACTLY one subsequence.\n - This means that the elements within a subsequence are UNIQUE.\n - All the numbers in a subsequence are distinct.\n - Elements in the array having the same value must be in different\n subsequences.\n - ^All of these statements are essentially saying the same thing.\n - 1 <= n <= 100,000 (n = the length of the given array)\n - 1 <= k <= n (k = the number of items required in the subsequence)\n - 1 <= numbers[i] <= 100,000 (the value of an item in the array)\n\n- Examples:\n - Sample Input #1: 2, [3, 5, 3, 2]\n - Sample Output #1: Yes\n - Explanation #1:\n - The array is [3, 5, 3, 2]. One solution is to partition into 2\n subsequences - [3, 2] and [5, 3]. So the answer is 'Yes'.\n\n - Sample Input #2: 3, [4, 8, 8, 8, 6, 4]\n - Sample Output #2: No\n - Explanation #2:\n - Element 8 occurs thrice in the array. There is no possible way to\n partition into subsequences of length 3, such that 8 occurs at most\n once in each subsequence. So the answer is 'No'.\n\n - Sample Input #3: 2, [1, 1, 1, 3, 4, 5]\n - Sample Output #3: No\n - Explanation #2:\n - Element 1 occurs thrice in the array. There is no possible way to\n partition into subsequences of length 3, such that 1 occurs at most\n once in each subsequence. So the answer is 'No'.\n */\n\n/*----------DEVISING A PLAN----------\n- BRUTE FORCE SOLUTION:\n\n 1. Create a function, 'partitionArray()', that takes in 2 parameters,\n 'k' (an integer) and 'numbers' (an array), and returns either the\n string 'Yes' or the string 'No' based on whether or not the given\n 'numbers' array can be partitioned into subsequences where the\n length of each subsequence is equal to 'k' and each item in the\n subsequent subsequences is a distinctly unique integer.\n\n 2. Create a variable with 'let' called 'lenOfNums', which denotes the\n length of the given input array, 'numbers'.\n\n 3. Create a variable with 'const' called 'cache', which denotes the\n frequency of each occuring item in the given input array. \n\n 4. Use an 'if/else' statement to evaluate whether or not 'lenOfArr' \n can be partitioned evenly into subsequences with a length of 'k'.\n\n a. If 'lenOfArr' can be partitioned evenly into subsequences with\n a length of 'k', use a 'for' loop and a cache to determine the\n frequency of each item in the given array, storing the item\n itself as a 'key' and the number of occurrences as the 'value' \n of a key/value pair in the cache.\n\n b. If 'lenOfArr' CANNOT be partitioned evenly into subsequence\n with a length of 'k', do nothing.\n \n 5. Use a separate 'for' loop that will iterate through the keys of the\n cache object to determine if any associated values are > 1.\n\n a. If a key's value IS greater than 1, do the following:\n\n i. Evaluate whether or not the multiple occurrences of the\n key in quesion are AT LEAST 'k' indices apart in the\n given array.\n\n 1. If the occurrence in question ARE at least 'k' \n indices apart in the original given input array,\n return 'Yes'.\n\n 2. If the occurrence in question is NOT at least 'k'\n indices apart in the original given input array,\n return 'No'.\n\n b. If a key's value is NOT greater than 1, do nothing.\n\n 6. Return 'No'.\n */\n\n/*----------IMPLEMENTING THE PLAN----------*/\n\nconst partitionArray = (k, numbers) => {\n let lenOfNums = numbers.length;\n const cache = {};\n\n if (lenOfNums % k == 0) {\n for (let i = 0; i < lenOfNums; i++) {\n // console.log(`i = ${i}; numbers[${i}] = ${numbers[i]}`);\n if (cache[numbers[i]]) {\n console.log(`${numbers[i]} ALREADY existed in the cache!`);\n cache[numbers[i]] += 1;\n console.log(cache);\n } else {\n console.log(`${numbers[i]} was just added to the cache!`);\n cache[numbers[i]] = 1;\n console.log(cache);\n }\n }\n\n for (let key = 0; key < cache.length; i++) {\n console.log(`cache[key] = ${cache[key]}`);\n if (cache[key] > 1) {\n for (let j = 0; j < lenOfNums; j++) {\n if (key == numbers[j]) {\n console.log(\n `The key, ${key}, has duplicates within the same subsquence!`\n );\n if (key == numbers[j + k - 1]) {\n return 'No';\n }\n } else {\n console.log(\n `The key, ${key}, DOES NOT have any duplicates within the same subsquence!`\n );\n return 'Yes';\n }\n }\n } else {\n console.log(`\\nEach key is a DISTINCT integer in the given array!`);\n console.log(cache);\n return 'Yes';\n }\n }\n } else {\n console.log(\n `The given input array has a length that is not evenly divisible by 'k'.`\n );\n }\n return 'No';\n};\n\nconsole.log(partitionArray(2, [1, 2, 3, 4, 5, 6])); // should return 'Yes'\nconsole.log(partitionArray(3, [4, 8, 8, 8, 6])); // should return 'No'\nconsole.log(partitionArray(3, [4, 8, 8, 8, 6, 7])); // should return 'No'\nconsole.log(partitionArray(2, [1, 2, 3, 1, 4, 1])); // should return 'Yes'\n\n/*----------REFLECTING/ITERATING ON THE PLAN----------\n\n */\n"} {"doc_id": "198c1602cc0fcfa85ca6388b9042a045", "text": "/*\n

    Given a binary tree

    \n\n
    \nstruct TreeLinkNode {\n  TreeLinkNode *left;\n  TreeLinkNode *right;\n  TreeLinkNode *next;\n}\n
    \n\n

    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

    \n\n

    Initially, all next pointers are set to NULL.

    \n\n

    Note:

    \n\n\n\n

    Example:

    \n\n

    Given the following perfect binary tree,

    \n\n
    \n     1\n   /  \\\n  2    3\n / \\  / \\\n4  5  6  7\n
    \n\n

    After calling your function, the tree should look like:

    \n\n
    \n     1 -> NULL\n   /  \\\n  2 -> 3 -> NULL\n / \\  / \\\n4->5->6->7 -> NULL\n
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811

    \n\n
    struct TreeLinkNode {\n  TreeLinkNode *left;\n  TreeLinkNode *right;\n  TreeLinkNode *next;\n}
    \n\n

    \u586b\u5145\u5b83\u7684\u6bcf\u4e2a next \u6307\u9488\uff0c\u8ba9\u8fd9\u4e2a\u6307\u9488\u6307\u5411\u5176\u4e0b\u4e00\u4e2a\u53f3\u4fa7\u8282\u70b9\u3002\u5982\u679c\u627e\u4e0d\u5230\u4e0b\u4e00\u4e2a\u53f3\u4fa7\u8282\u70b9\uff0c\u5219\u5c06 next \u6307\u9488\u8bbe\u7f6e\u4e3a NULL\u3002

    \n\n

    \u521d\u59cb\u72b6\u6001\u4e0b\uff0c\u6240\u6709 next \u6307\u9488\u90fd\u88ab\u8bbe\u7f6e\u4e3a NULL\u3002

    \n\n

    \u8bf4\u660e:

    \n\n\n\n

    \u793a\u4f8b:

    \n\n

    \u7ed9\u5b9a\u5b8c\u7f8e\u4e8c\u53c9\u6811\uff0c

    \n\n
         1\n   /  \\\n  2    3\n / \\  / \\\n4  5  6  7
    \n\n

    \u8c03\u7528\u4f60\u7684\u51fd\u6570\u540e\uff0c\u8be5\u5b8c\u7f8e\u4e8c\u53c9\u6811\u53d8\u4e3a\uff1a

    \n\n
         1 -> NULL\n   /  \\\n  2 -> 3 -> NULL\n / \\  / \\\n4->5->6->7 -> NULL
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811

    \n\n
    struct TreeLinkNode {\n  TreeLinkNode *left;\n  TreeLinkNode *right;\n  TreeLinkNode *next;\n}
    \n\n

    \u586b\u5145\u5b83\u7684\u6bcf\u4e2a next \u6307\u9488\uff0c\u8ba9\u8fd9\u4e2a\u6307\u9488\u6307\u5411\u5176\u4e0b\u4e00\u4e2a\u53f3\u4fa7\u8282\u70b9\u3002\u5982\u679c\u627e\u4e0d\u5230\u4e0b\u4e00\u4e2a\u53f3\u4fa7\u8282\u70b9\uff0c\u5219\u5c06 next \u6307\u9488\u8bbe\u7f6e\u4e3a NULL\u3002

    \n\n

    \u521d\u59cb\u72b6\u6001\u4e0b\uff0c\u6240\u6709 next \u6307\u9488\u90fd\u88ab\u8bbe\u7f6e\u4e3a NULL\u3002

    \n\n

    \u8bf4\u660e:

    \n\n\n\n

    \u793a\u4f8b:

    \n\n

    \u7ed9\u5b9a\u5b8c\u7f8e\u4e8c\u53c9\u6811\uff0c

    \n\n
         1\n   /  \\\n  2    3\n / \\  / \\\n4  5  6  7
    \n\n

    \u8c03\u7528\u4f60\u7684\u51fd\u6570\u540e\uff0c\u8be5\u5b8c\u7f8e\u4e8c\u53c9\u6811\u53d8\u4e3a\uff1a

    \n\n
         1 -> NULL\n   /  \\\n  2 -> 3 -> NULL\n / \\  / \\\n4->5->6->7 -> NULL
    \n*/\n\n\n/**\n * Definition for binary tree with next pointer.\n * function TreeLinkNode(val) {\n * this.val = val;\n * this.left = this.right = this.next = null;\n * }\n */\n\n/**\n * @param {TreeLinkNode} root\n * @return {void} Do not return anything, modify tree in-place instead.\n */\nvar connect = function(root) {\n \n};"} {"doc_id": "1a16aa04d58de2ba3a062a54f51b6b60", "text": "\"use strict\";\n// Getting Started\n/* function foo(bar: string) {\n return 'Hello, ' + bar\n}\n\nlet baz = 'Alireza'\n\nconsole.log(foo(baz)) */\n/*\n// Common Types\nlet foo: string\nlet bar: boolean\nlet baz: number\nlet qux: string[]\nlet quuz: [number, string]\nlet corge: { [key: number]: string }\nlet grault: Set\nbaz = 0xffff\n\nfoo = 'ABCDDDDz'\nbar = true\nbaz = 123\nqux = ['a', 'b', 'c']\nquuz = [1, 'abc']\ncorge = { 123: 'abc', 456: 'def' }\ngrault = new Set([1, 2, 3])\n*/\n/*\n//Number\n// A number can be written in many bases or with floating point precision.\n\nlet baz: number\nbaz = 123 //decimal\nbaz = 123.456 //float\nbaz = 0xffff //hex\nbaz = 0b10101 //binary\nbaz = 0o671 //octal\n*/\n/* Strings\nSome more string experiments you can try are,\n\n\nlet foo: string\nfoo = 'ABC'\nfoo = '123'\nfoo = 'ABC = 123'\nfoo = 'quick brown fox, etc'\nfoo = \"It wasn't me\" */\n/* Boolean\nA boolean can either be true or false.\n\n\nlet bar: boolean\nbar = true\nbar = false */\n/*\n// Array\nlet a: string[]\na = ['a', 'b', 'd', 'd']\nlet b: number[]\nb = [1, 2, 3, 4]\nlet c: boolean[]\nc = [true, false, true]\nlet d: unknown[]\nd = [1, 'a', true, ['even', 'another', 'internal', 'array']]\n// Array items can be retrieved using a zero based index.\nconsole.log(a[1])\nconsole.log(b[0])\nconsole.log(c[1])\nconsole.log(d[2])\n*/\n/* let a:any[] = []\nconsole.log(a); */\n// Dictionary\n// A Dictionary is used as a key/value construct, where you can retrieve a value from the dictionary by using a key.\n// let a: { [key: number]: string }\n// a = { 123: 'abc', 456: 'def' }\n// let b: { [key: string]: boolean }\n// b = { abc: true, def: false, ghi: true }\n// console.log(a[123])\n// console.log(b['def'])\n/*\n// The key of a dictionary can be of any type and name\nlet a: { [key: string]: string }\nlet b: { [id: number]: string }\na = { a: 'car', b: 'train', c: 'plane', d: 'boat' }\nb = { 1: 'car', 2: 'train', 3: 'plane', 4: 'boat' }\n// and can be retrieved as such\nconsole.log(a['a'])\nconsole.log(b[2])\n\n// Since Dictionaries are really just objects. You can also retrieve\n// a dictionary's value using object notation if the keys are strings\nconsole.log(a.c)\n// console.log(b.2) // this doesn't work when the key is a number\n\n// you can add items to a dictionary\na['e'] = 'go-cart'\nconsole.log(a)\n\n// you can delete\ndelete b[2]\nconsole.log(b)\n\n// The values of a dictionary can be of any type, even an array.\nlet c: { [id: number]: number[] }\nc = { 1: [1, 2, 3], 2: [4, 5, 6], 3: [7, 8, 9], 4: [10, 11, 12] }\nconsole.log(c)\n*/\n/*\n// Tuple\n// The Tuple is similar to an array,\n// but you are explicitly indicating how many items are\n// in the Tuple and of which type they are when you instantiate\n// it. The Tuple type is not directly supported in JavaScript\n// as a Tuple, but as an array instead. The rules of the Tuple\n// are enforced in TypeScript only when it is created. After\n// the Tuple is created, it behaves the same as an array. You\n// can add/remove/edit items.\n\nlet a: [number, string]\na = [1, 'abc']\nlet b: [string, boolean, number]\nb = ['abc', false, 123]\n\nconsole.log(a[1])\nconsole.log(b[2])\n*/\n// Set\n// The Set object lets you store unique values of\n// any type. Any duplicate items added to the Set won't\n// be added.\nlet a;\na = new Set([1, 2, 3, 4]);\nlet b;\nb = new Set(['a', 'b', 'c', 'd', 'a']); // the second `a` is not added\nlet c;\nc = new Set([1, 'b', true]);\nconsole.log(a);\nconsole.log(b);\nconsole.log(c);\nconst someSet = new Set();\nsomeSet.add('me');\nsomeSet.add('you');\nsomeSet.add('they');\nconsole.log(someSet);\n"} {"doc_id": "1b1f21665cbee3a326de1898d7872652", "text": "// 1. Declare uma vari\u00e1vel de nome weight\n let weight;\n\n// 2. Que tipo de dado \u00e9 a vari\u00e1vel acima?\n console.log(typeof weight)\n\n/*\n\n 3. Declare um vari\u00e1vel e atribua valores para cada um dos dados:\n * name: String\n * age: Number (integer)\n * stars: Number (float)\n * isSubscribed: Boolean\n\n */\n\n let name = 'mateus'\n let age = 46\n let stars = 5.0\n let inSubscribed = true\n\n \n\n /*\n 4. A vari\u00e1vel student abaixo \u00e9 de que tipo de dados?\n\n 4.1 Atribua a ela as mesmas propriedades e valores do exerc\u00edcio 3\n\n 4.2 Mostre no console a seguinte mensagem:\n\n de idade pesa kg.\n\n Aten\u00e7\u00e3o, substitua e pelos valores de cada propriedade do objeto\n */\n\n let student = {\n name: \"Mateus\",\n age: 46,\n stars: 5.0,\n isSubscribed: true,\n weight: 90\n };\n\n console.log(typeof student)\n console.log(student)\n console.log(`${student.name} de idade ${student.age} pesa ${student.weight}`)\n\n console.log(\"------------------------\")\n\n /*\n 5. Declare uma vari\u00e1vel do tipo Array, de nome students e atribua a ela nenhum valor, ou seja, somente o array vazio \n \n 6. Reatribua valor para a vari\u00e1vel acima, colocando dentro dela o objeto student da quest\u00e3o 4. (n\u00e3o copiar e colar o objeto, mas usar o objeto criado e inserir ele no array)\n */\n\n let students = [student]\n //console.log(students)\n\n /*\n 7. Coloque no console o valor da posi\u00e7\u00e3o zero do Array acima\n */\n //console.log(students[0])\n\n /* \n 8. Crie um novo student e coloque na posi\u00e7\u00e3o 1 do Array students\n */\n\n let student2 = {\n name: \"Eduarda\",\n age: \"47\",\n stars: 4.7,\n isSubscribed: false,\n weight: 65\n };\n\n students[1] = student2\n console.log(students)\n\n /*\n 9. Sem rodar o c\u00f3digo responda qual \u00e9 a resposta do c\u00f3digo abaixo e por que? Ap\u00f3s sua resposta, rode o c\u00f3digo e veja se voc\u00ea acertou. R= undefined\n */\n console.log(typeof a)\n var a = 1\n \n"} {"doc_id": "1b5bc4256a358b5a81a614c0ef0e0eec", "text": "/*\n

    Say you have an array for which the ith element is the price of a given stock on day i.

    \n\n

    Design an algorithm to find the maximum profit. You may complete at most two transactions.

    \n\n

    Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

    \n\n

    Example 1:

    \n\n
    \nInput: [3,3,5,0,0,3,1,4]\nOutput: 6\nExplanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
    \n\n

    Example 2:

    \n\n
    \nInput: [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are\n             engaging multiple transactions at the same time. You must sell before buying again.\n
    \n\n

    Example 3:

    \n\n
    \nInput: [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u6570\u7ec4\uff0c\u5b83\u7684\u7b2c i \u4e2a\u5143\u7d20\u662f\u4e00\u652f\u7ed9\u5b9a\u7684\u80a1\u7968\u5728\u7b2c i \u5929\u7684\u4ef7\u683c\u3002

    \n\n

    \u8bbe\u8ba1\u4e00\u4e2a\u7b97\u6cd5\u6765\u8ba1\u7b97\u4f60\u6240\u80fd\u83b7\u53d6\u7684\u6700\u5927\u5229\u6da6\u3002\u4f60\u6700\u591a\u53ef\u4ee5\u5b8c\u6210 \u4e24\u7b14 \u4ea4\u6613\u3002

    \n\n

    \u6ce8\u610f: \u4f60\u4e0d\u80fd\u540c\u65f6\u53c2\u4e0e\u591a\u7b14\u4ea4\u6613\uff08\u4f60\u5fc5\u987b\u5728\u518d\u6b21\u8d2d\u4e70\u524d\u51fa\u552e\u6389\u4e4b\u524d\u7684\u80a1\u7968\uff09\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \u8f93\u5165: [3,3,5,0,0,3,1,4]\n\u8f93\u51fa: 6\n\u89e3\u91ca: \u5728\u7b2c 4 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 0\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 6 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 3\uff09\u7684\u65f6\u5019\u5356\u51fa\uff0c\u8fd9\u7b14\u4ea4\u6613\u6240\u80fd\u83b7\u5f97\u5229\u6da6 = 3-0 = 3 \u3002\n     \u968f\u540e\uff0c\u5728\u7b2c 7 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 1\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 8 \u5929 \uff08\u80a1\u7968\u4ef7\u683c = 4\uff09\u7684\u65f6\u5019\u5356\u51fa\uff0c\u8fd9\u7b14\u4ea4\u6613\u6240\u80fd\u83b7\u5f97\u5229\u6da6 = 4-1 = 3 \u3002
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \u8f93\u5165: [1,2,3,4,5]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u5728\u7b2c 1 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 1\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 5 \u5929 \uff08\u80a1\u7968\u4ef7\u683c = 5\uff09\u7684\u65f6\u5019\u5356\u51fa, \u8fd9\u7b14\u4ea4\u6613\u6240\u80fd\u83b7\u5f97\u5229\u6da6 = 5-1 = 4 \u3002   \n     \u6ce8\u610f\u4f60\u4e0d\u80fd\u5728\u7b2c 1 \u5929\u548c\u7b2c 2 \u5929\u63a5\u8fde\u8d2d\u4e70\u80a1\u7968\uff0c\u4e4b\u540e\u518d\u5c06\u5b83\u4eec\u5356\u51fa\u3002   \n     \u56e0\u4e3a\u8fd9\u6837\u5c5e\u4e8e\u540c\u65f6\u53c2\u4e0e\u4e86\u591a\u7b14\u4ea4\u6613\uff0c\u4f60\u5fc5\u987b\u5728\u518d\u6b21\u8d2d\u4e70\u524d\u51fa\u552e\u6389\u4e4b\u524d\u7684\u80a1\u7968\u3002\n
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \u8f93\u5165: [7,6,4,3,1] \n\u8f93\u51fa: 0 \n\u89e3\u91ca: \u5728\u8fd9\u4e2a\u60c5\u51b5\u4e0b, \u6ca1\u6709\u4ea4\u6613\u5b8c\u6210, \u6240\u4ee5\u6700\u5927\u5229\u6da6\u4e3a 0\u3002
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u6570\u7ec4\uff0c\u5b83\u7684\u7b2c i \u4e2a\u5143\u7d20\u662f\u4e00\u652f\u7ed9\u5b9a\u7684\u80a1\u7968\u5728\u7b2c i \u5929\u7684\u4ef7\u683c\u3002

    \n\n

    \u8bbe\u8ba1\u4e00\u4e2a\u7b97\u6cd5\u6765\u8ba1\u7b97\u4f60\u6240\u80fd\u83b7\u53d6\u7684\u6700\u5927\u5229\u6da6\u3002\u4f60\u6700\u591a\u53ef\u4ee5\u5b8c\u6210 \u4e24\u7b14 \u4ea4\u6613\u3002

    \n\n

    \u6ce8\u610f: \u4f60\u4e0d\u80fd\u540c\u65f6\u53c2\u4e0e\u591a\u7b14\u4ea4\u6613\uff08\u4f60\u5fc5\u987b\u5728\u518d\u6b21\u8d2d\u4e70\u524d\u51fa\u552e\u6389\u4e4b\u524d\u7684\u80a1\u7968\uff09\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \u8f93\u5165: [3,3,5,0,0,3,1,4]\n\u8f93\u51fa: 6\n\u89e3\u91ca: \u5728\u7b2c 4 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 0\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 6 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 3\uff09\u7684\u65f6\u5019\u5356\u51fa\uff0c\u8fd9\u7b14\u4ea4\u6613\u6240\u80fd\u83b7\u5f97\u5229\u6da6 = 3-0 = 3 \u3002\n     \u968f\u540e\uff0c\u5728\u7b2c 7 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 1\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 8 \u5929 \uff08\u80a1\u7968\u4ef7\u683c = 4\uff09\u7684\u65f6\u5019\u5356\u51fa\uff0c\u8fd9\u7b14\u4ea4\u6613\u6240\u80fd\u83b7\u5f97\u5229\u6da6 = 4-1 = 3 \u3002
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \u8f93\u5165: [1,2,3,4,5]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u5728\u7b2c 1 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 1\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 5 \u5929 \uff08\u80a1\u7968\u4ef7\u683c = 5\uff09\u7684\u65f6\u5019\u5356\u51fa, \u8fd9\u7b14\u4ea4\u6613\u6240\u80fd\u83b7\u5f97\u5229\u6da6 = 5-1 = 4 \u3002   \n     \u6ce8\u610f\u4f60\u4e0d\u80fd\u5728\u7b2c 1 \u5929\u548c\u7b2c 2 \u5929\u63a5\u8fde\u8d2d\u4e70\u80a1\u7968\uff0c\u4e4b\u540e\u518d\u5c06\u5b83\u4eec\u5356\u51fa\u3002   \n     \u56e0\u4e3a\u8fd9\u6837\u5c5e\u4e8e\u540c\u65f6\u53c2\u4e0e\u4e86\u591a\u7b14\u4ea4\u6613\uff0c\u4f60\u5fc5\u987b\u5728\u518d\u6b21\u8d2d\u4e70\u524d\u51fa\u552e\u6389\u4e4b\u524d\u7684\u80a1\u7968\u3002\n
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \u8f93\u5165: [7,6,4,3,1] \n\u8f93\u51fa: 0 \n\u89e3\u91ca: \u5728\u8fd9\u4e2a\u60c5\u51b5\u4e0b, \u6ca1\u6709\u4ea4\u6613\u5b8c\u6210, \u6240\u4ee5\u6700\u5927\u5229\u6da6\u4e3a 0\u3002
    \n*/\n\n\n/**\n * @param {number[]} prices\n * @return {number}\n */\nvar maxProfit = function(prices) {\n \n};"} {"doc_id": "1da7cb263670719bcea288b07867b8a7", "text": "/*\n

    We are given two strings, A and B.

    \n\n

    A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.

    \n\n
    \nExample 1:\nInput: A = 'abcde', B = 'cdeab'\nOutput: true\n\nExample 2:\nInput: A = 'abcde', B = 'abced'\nOutput: false\n
    \n\n

    Note:

    \n\n
      \n\t
    • A and B will have length at most 100.
    • \n
    \n

    \u7ed9\u5b9a\u4e24\u4e2a\u5b57\u7b26\u4e32, A \u548c B\u3002

    \n\n

    A \u7684\u65cb\u8f6c\u64cd\u4f5c\u5c31\u662f\u5c06 A \u6700\u5de6\u8fb9\u7684\u5b57\u7b26\u79fb\u52a8\u5230\u6700\u53f3\u8fb9\u3002 \u4f8b\u5982, \u82e5 A = 'abcde'\uff0c\u5728\u79fb\u52a8\u4e00\u6b21\u4e4b\u540e\u7ed3\u679c\u5c31\u662f'bcdea' \u3002\u5982\u679c\u5728\u82e5\u5e72\u6b21\u65cb\u8f6c\u64cd\u4f5c\u4e4b\u540e\uff0cA \u80fd\u53d8\u6210B\uff0c\u90a3\u4e48\u8fd4\u56deTrue\u3002

    \n\n
    \n\u793a\u4f8b 1:\n\u8f93\u5165: A = 'abcde', B = 'cdeab'\n\u8f93\u51fa: true\n\n\u793a\u4f8b 2:\n\u8f93\u5165: A = 'abcde', B = 'abced'\n\u8f93\u51fa: false
    \n\n

    \u6ce8\u610f\uff1a

    \n\n
      \n\t
    • A \u548c B \u957f\u5ea6\u4e0d\u8d85\u8fc7 100\u3002
    • \n
    \n

    \u7ed9\u5b9a\u4e24\u4e2a\u5b57\u7b26\u4e32, A \u548c B\u3002

    \n\n

    A \u7684\u65cb\u8f6c\u64cd\u4f5c\u5c31\u662f\u5c06 A \u6700\u5de6\u8fb9\u7684\u5b57\u7b26\u79fb\u52a8\u5230\u6700\u53f3\u8fb9\u3002 \u4f8b\u5982, \u82e5 A = 'abcde'\uff0c\u5728\u79fb\u52a8\u4e00\u6b21\u4e4b\u540e\u7ed3\u679c\u5c31\u662f'bcdea' \u3002\u5982\u679c\u5728\u82e5\u5e72\u6b21\u65cb\u8f6c\u64cd\u4f5c\u4e4b\u540e\uff0cA \u80fd\u53d8\u6210B\uff0c\u90a3\u4e48\u8fd4\u56deTrue\u3002

    \n\n
    \n\u793a\u4f8b 1:\n\u8f93\u5165: A = 'abcde', B = 'cdeab'\n\u8f93\u51fa: true\n\n\u793a\u4f8b 2:\n\u8f93\u5165: A = 'abcde', B = 'abced'\n\u8f93\u51fa: false
    \n\n

    \u6ce8\u610f\uff1a

    \n\n
      \n\t
    • A \u548c B \u957f\u5ea6\u4e0d\u8d85\u8fc7 100\u3002
    • \n
    \n*/\n\n\n/**\n * @param {string} A\n * @param {string} B\n * @return {boolean}\n */\nvar rotateString = function(A, B) {\n \n};"} {"doc_id": "1df4208c236dd32a15ff634c74a33425", "text": "/*\n

    The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

    \n\n

    Now your job is to find the total Hamming distance between all pairs of the given numbers.\n\n\n

    Example:
    \n

    \nInput: 4, 14, 2\n\nOutput: 6\n\nExplanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case). So the answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n
    \n

    \n\n

    Note:
    \n

      \n
    1. Elements of the given array are in the range of 0 to 10^9\n
    2. Length of the array will not exceed 10^4.
    3. \n
    \n

    \u4e24\u4e2a\u6574\u6570\u7684 \u6c49\u660e\u8ddd\u79bb \u6307\u7684\u662f\u8fd9\u4e24\u4e2a\u6570\u5b57\u7684\u4e8c\u8fdb\u5236\u6570\u5bf9\u5e94\u4f4d\u4e0d\u540c\u7684\u6570\u91cf\u3002

    \n\n

    \u8ba1\u7b97\u4e00\u4e2a\u6570\u7ec4\u4e2d\uff0c\u4efb\u610f\u4e24\u4e2a\u6570\u4e4b\u95f4\u6c49\u660e\u8ddd\u79bb\u7684\u603b\u548c\u3002

    \n\n

    \u793a\u4f8b:

    \n\n
    \n\u8f93\u5165: 4, 14, 2\n\n\u8f93\u51fa: 6\n\n\u89e3\u91ca: \u5728\u4e8c\u8fdb\u5236\u8868\u793a\u4e2d\uff0c4\u8868\u793a\u4e3a0100\uff0c14\u8868\u793a\u4e3a1110\uff0c2\u8868\u793a\u4e3a0010\u3002\uff08\u8fd9\u6837\u8868\u793a\u662f\u4e3a\u4e86\u4f53\u73b0\u540e\u56db\u4f4d\u4e4b\u95f4\u5173\u7cfb\uff09\n\u6240\u4ee5\u7b54\u6848\u4e3a\uff1a\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n
    \n\n

    \u6ce8\u610f:

    \n\n
      \n\t
    1. \u6570\u7ec4\u4e2d\u5143\u7d20\u7684\u8303\u56f4\u4e3a\u4ece 0\u5230 10^9\u3002
    2. \n\t
    3. \u6570\u7ec4\u7684\u957f\u5ea6\u4e0d\u8d85\u8fc7 10^4\u3002
    4. \n
    \n

    \u4e24\u4e2a\u6574\u6570\u7684 \u6c49\u660e\u8ddd\u79bb \u6307\u7684\u662f\u8fd9\u4e24\u4e2a\u6570\u5b57\u7684\u4e8c\u8fdb\u5236\u6570\u5bf9\u5e94\u4f4d\u4e0d\u540c\u7684\u6570\u91cf\u3002

    \n\n

    \u8ba1\u7b97\u4e00\u4e2a\u6570\u7ec4\u4e2d\uff0c\u4efb\u610f\u4e24\u4e2a\u6570\u4e4b\u95f4\u6c49\u660e\u8ddd\u79bb\u7684\u603b\u548c\u3002

    \n\n

    \u793a\u4f8b:

    \n\n
    \n\u8f93\u5165: 4, 14, 2\n\n\u8f93\u51fa: 6\n\n\u89e3\u91ca: \u5728\u4e8c\u8fdb\u5236\u8868\u793a\u4e2d\uff0c4\u8868\u793a\u4e3a0100\uff0c14\u8868\u793a\u4e3a1110\uff0c2\u8868\u793a\u4e3a0010\u3002\uff08\u8fd9\u6837\u8868\u793a\u662f\u4e3a\u4e86\u4f53\u73b0\u540e\u56db\u4f4d\u4e4b\u95f4\u5173\u7cfb\uff09\n\u6240\u4ee5\u7b54\u6848\u4e3a\uff1a\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n
    \n\n

    \u6ce8\u610f:

    \n\n
      \n\t
    1. \u6570\u7ec4\u4e2d\u5143\u7d20\u7684\u8303\u56f4\u4e3a\u4ece 0\u5230 10^9\u3002
    2. \n\t
    3. \u6570\u7ec4\u7684\u957f\u5ea6\u4e0d\u8d85\u8fc7 10^4\u3002
    4. \n
    \n*/\n\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar totalHammingDistance = function(nums) {\n \n};"} {"doc_id": "1e9b401f9e4a8f788ff7e551117d47e8", "text": "/*\n

    \nGiven an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.\n

    \n\n\n

    Example 1:
    \n

    \nInput: [3, 1, 4, 1, 5], k = 2\nOutput: 2\nExplanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
    Although we have two 1s in the input, we should only return the number of unique pairs.\n
    \n

    \n\n

    Example 2:
    \n

    \nInput:[1, 2, 3, 4, 5], k = 1\nOutput: 4\nExplanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).\n
    \n

    \n\n

    Example 3:
    \n

    \nInput: [1, 3, 1, 5, 4], k = 0\nOutput: 1\nExplanation: There is one 0-diff pair in the array, (1, 1).\n
    \n

    \n\n

    Note:
    \n

      \n
    1. The pairs (i, j) and (j, i) count as the same pair.
    2. \n
    3. The length of the array won't exceed 10,000.
    4. \n
    5. All the integers in the given input belong to the range: [-1e7, 1e7].
    6. \n
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u6570\u7ec4\u548c\u4e00\u4e2a\u6574\u6570 k, \u4f60\u9700\u8981\u5728\u6570\u7ec4\u91cc\u627e\u5230\u4e0d\u540c\u7684 k-diff \u6570\u5bf9\u3002\u8fd9\u91cc\u5c06 k-diff \u6570\u5bf9\u5b9a\u4e49\u4e3a\u4e00\u4e2a\u6574\u6570\u5bf9 (i, j), \u5176\u4e2d i \u548c j \u90fd\u662f\u6570\u7ec4\u4e2d\u7684\u6570\u5b57\uff0c\u4e14\u4e24\u6570\u4e4b\u5dee\u7684\u7edd\u5bf9\u503c\u662f k.

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: [3, 1, 4, 1, 5], k = 2\n\u8f93\u51fa: 2\n\u89e3\u91ca: \u6570\u7ec4\u4e2d\u6709\u4e24\u4e2a 2-diff \u6570\u5bf9, (1, 3) \u548c (3, 5)\u3002\n\u5c3d\u7ba1\u6570\u7ec4\u4e2d\u6709\u4e24\u4e2a1\uff0c\u4f46\u6211\u4eec\u53ea\u5e94\u8fd4\u56de\u4e0d\u540c\u7684\u6570\u5bf9\u7684\u6570\u91cf\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165:[1, 2, 3, 4, 5], k = 1\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u6570\u7ec4\u4e2d\u6709\u56db\u4e2a 1-diff \u6570\u5bf9, (1, 2), (2, 3), (3, 4) \u548c (4, 5)\u3002\n
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \n\u8f93\u5165: [1, 3, 1, 5, 4], k = 0\n\u8f93\u51fa: 1\n\u89e3\u91ca: \u6570\u7ec4\u4e2d\u53ea\u6709\u4e00\u4e2a 0-diff \u6570\u5bf9\uff0c(1, 1)\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n
      \n\t
    1. \u6570\u5bf9 (i, j) \u548c\u6570\u5bf9 (j, i) \u88ab\u7b97\u4f5c\u540c\u4e00\u6570\u5bf9\u3002
    2. \n\t
    3. \u6570\u7ec4\u7684\u957f\u5ea6\u4e0d\u8d85\u8fc710,000\u3002
    4. \n\t
    5. \u6240\u6709\u8f93\u5165\u7684\u6574\u6570\u7684\u8303\u56f4\u5728 [-1e7, 1e7]\u3002
    6. \n
    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u6570\u7ec4\u548c\u4e00\u4e2a\u6574\u6570 k, \u4f60\u9700\u8981\u5728\u6570\u7ec4\u91cc\u627e\u5230\u4e0d\u540c\u7684 k-diff \u6570\u5bf9\u3002\u8fd9\u91cc\u5c06 k-diff \u6570\u5bf9\u5b9a\u4e49\u4e3a\u4e00\u4e2a\u6574\u6570\u5bf9 (i, j), \u5176\u4e2d i \u548c j \u90fd\u662f\u6570\u7ec4\u4e2d\u7684\u6570\u5b57\uff0c\u4e14\u4e24\u6570\u4e4b\u5dee\u7684\u7edd\u5bf9\u503c\u662f k.

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: [3, 1, 4, 1, 5], k = 2\n\u8f93\u51fa: 2\n\u89e3\u91ca: \u6570\u7ec4\u4e2d\u6709\u4e24\u4e2a 2-diff \u6570\u5bf9, (1, 3) \u548c (3, 5)\u3002\n\u5c3d\u7ba1\u6570\u7ec4\u4e2d\u6709\u4e24\u4e2a1\uff0c\u4f46\u6211\u4eec\u53ea\u5e94\u8fd4\u56de\u4e0d\u540c\u7684\u6570\u5bf9\u7684\u6570\u91cf\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165:[1, 2, 3, 4, 5], k = 1\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u6570\u7ec4\u4e2d\u6709\u56db\u4e2a 1-diff \u6570\u5bf9, (1, 2), (2, 3), (3, 4) \u548c (4, 5)\u3002\n
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \n\u8f93\u5165: [1, 3, 1, 5, 4], k = 0\n\u8f93\u51fa: 1\n\u89e3\u91ca: \u6570\u7ec4\u4e2d\u53ea\u6709\u4e00\u4e2a 0-diff \u6570\u5bf9\uff0c(1, 1)\u3002\n
    \n\n

    \u6ce8\u610f:

    \n\n
      \n\t
    1. \u6570\u5bf9 (i, j) \u548c\u6570\u5bf9 (j, i) \u88ab\u7b97\u4f5c\u540c\u4e00\u6570\u5bf9\u3002
    2. \n\t
    3. \u6570\u7ec4\u7684\u957f\u5ea6\u4e0d\u8d85\u8fc710,000\u3002
    4. \n\t
    5. \u6240\u6709\u8f93\u5165\u7684\u6574\u6570\u7684\u8303\u56f4\u5728 [-1e7, 1e7]\u3002
    6. \n
    \n*/\n\n\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar findPairs = function(nums, k) {\n \n};"} {"doc_id": "1ed6e767cf91f5ec692806e3df55c80e", "text": "/*\n

    There are N rooms and you start in room 0.  Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. 

    \n\n

    Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length.  A key rooms[i][j] = v opens the room with number v.

    \n\n

    Initially, all the rooms start locked (except for room 0). 

    \n\n

    You can walk back and forth between rooms freely.

    \n\n

    Return true if and only if you can enter every room.

    \n\n
      \n
    \n\n

    Example 1:

    \n\n
    \nInput: [[1],[2],[3],[]]\nOutput: true\nExplanation:  \nWe start in room 0, and pick up key 1.\nWe then go to room 1, and pick up key 2.\nWe then go to room 2, and pick up key 3.\nWe then go to room 3.  Since we were able to go to every room, we return true.\n
    \n\n

    Example 2:

    \n\n
    \nInput: [[1,3],[3,0,1],[2],[0]]\nOutput: false\nExplanation: We can't enter the room with number 2.\n
    \n\n

    Note:

    \n\n
      \n\t
    1. 1 <= rooms.length <= 1000
    2. \n\t
    3. 0 <= rooms[i].length <= 1000
    4. \n\t
    5. The number of keys in all rooms combined is at most 3000.
    6. \n

    \u6709 N \u4e2a\u623f\u95f4\uff0c\u5f00\u59cb\u65f6\u4f60\u4f4d\u4e8e 0 \u53f7\u623f\u95f4\u3002\u6bcf\u4e2a\u623f\u95f4\u6709\u4e0d\u540c\u7684\u53f7\u7801\uff1a0\uff0c1\uff0c2\uff0c...\uff0cN-1\uff0c\u5e76\u4e14\u623f\u95f4\u91cc\u53ef\u80fd\u6709\u4e00\u4e9b\u94a5\u5319\u80fd\u4f7f\u4f60\u8fdb\u5165\u4e0b\u4e00\u4e2a\u623f\u95f4\u3002

    \n\n

    \u5728\u5f62\u5f0f\u4e0a\uff0c\u5bf9\u4e8e\u6bcf\u4e2a\u623f\u95f4 i \u90fd\u6709\u4e00\u4e2a\u94a5\u5319\u5217\u8868 rooms[i]\uff0c\u6bcf\u4e2a\u94a5\u5319 rooms[i][j] \u7531 [0,1\uff0c...\uff0cN-1] \u4e2d\u7684\u4e00\u4e2a\u6574\u6570\u8868\u793a\uff0c\u5176\u4e2d N = rooms.length\u3002 \u94a5\u5319 rooms[i][j] = v \u53ef\u4ee5\u6253\u5f00\u7f16\u53f7\u4e3a v \u7684\u623f\u95f4\u3002

    \n\n

    \u6700\u521d\uff0c\u9664 0 \u53f7\u623f\u95f4\u5916\u7684\u5176\u4f59\u6240\u6709\u623f\u95f4\u90fd\u88ab\u9501\u4f4f\u3002

    \n\n

    \u4f60\u53ef\u4ee5\u81ea\u7531\u5730\u5728\u623f\u95f4\u4e4b\u95f4\u6765\u56de\u8d70\u52a8\u3002

    \n\n

    \u5982\u679c\u80fd\u8fdb\u5165\u6bcf\u4e2a\u623f\u95f4\u8fd4\u56de true\uff0c\u5426\u5219\u8fd4\u56de false\u3002

    \n\n
      \n
    \n\n

    \u793a\u4f8b 1\uff1a

    \n\n
    \u8f93\u5165: [[1],[2],[3],[]]\n\u8f93\u51fa: true\n\u89e3\u91ca:  \n\u6211\u4eec\u4ece 0 \u53f7\u623f\u95f4\u5f00\u59cb\uff0c\u62ff\u5230\u94a5\u5319 1\u3002\n\u4e4b\u540e\u6211\u4eec\u53bb 1 \u53f7\u623f\u95f4\uff0c\u62ff\u5230\u94a5\u5319 2\u3002\n\u7136\u540e\u6211\u4eec\u53bb 2 \u53f7\u623f\u95f4\uff0c\u62ff\u5230\u94a5\u5319 3\u3002\n\u6700\u540e\u6211\u4eec\u53bb\u4e86 3 \u53f7\u623f\u95f4\u3002\n\u7531\u4e8e\u6211\u4eec\u80fd\u591f\u8fdb\u5165\u6bcf\u4e2a\u623f\u95f4\uff0c\u6211\u4eec\u8fd4\u56de true\u3002\n
    \n\n

    \u793a\u4f8b 2\uff1a

    \n\n
    \u8f93\u5165\uff1a[[1,3],[3,0,1],[2],[0]]\n\u8f93\u51fa\uff1afalse\n\u89e3\u91ca\uff1a\u6211\u4eec\u4e0d\u80fd\u8fdb\u5165 2 \u53f7\u623f\u95f4\u3002\n
    \n\n

    \u63d0\u793a\uff1a

    \n\n
      \n\t
    1. 1 <= rooms.length <= 1000
    2. \n\t
    3. 0 <= rooms[i].length <= 1000
    4. \n\t
    5. \u6240\u6709\u623f\u95f4\u4e2d\u7684\u94a5\u5319\u6570\u91cf\u603b\u8ba1\u4e0d\u8d85\u8fc7 3000\u3002
    6. \n
    \n

    \u6709 N \u4e2a\u623f\u95f4\uff0c\u5f00\u59cb\u65f6\u4f60\u4f4d\u4e8e 0 \u53f7\u623f\u95f4\u3002\u6bcf\u4e2a\u623f\u95f4\u6709\u4e0d\u540c\u7684\u53f7\u7801\uff1a0\uff0c1\uff0c2\uff0c...\uff0cN-1\uff0c\u5e76\u4e14\u623f\u95f4\u91cc\u53ef\u80fd\u6709\u4e00\u4e9b\u94a5\u5319\u80fd\u4f7f\u4f60\u8fdb\u5165\u4e0b\u4e00\u4e2a\u623f\u95f4\u3002

    \n\n

    \u5728\u5f62\u5f0f\u4e0a\uff0c\u5bf9\u4e8e\u6bcf\u4e2a\u623f\u95f4 i \u90fd\u6709\u4e00\u4e2a\u94a5\u5319\u5217\u8868 rooms[i]\uff0c\u6bcf\u4e2a\u94a5\u5319 rooms[i][j] \u7531 [0,1\uff0c...\uff0cN-1] \u4e2d\u7684\u4e00\u4e2a\u6574\u6570\u8868\u793a\uff0c\u5176\u4e2d N = rooms.length\u3002 \u94a5\u5319 rooms[i][j] = v \u53ef\u4ee5\u6253\u5f00\u7f16\u53f7\u4e3a v \u7684\u623f\u95f4\u3002

    \n\n

    \u6700\u521d\uff0c\u9664 0 \u53f7\u623f\u95f4\u5916\u7684\u5176\u4f59\u6240\u6709\u623f\u95f4\u90fd\u88ab\u9501\u4f4f\u3002

    \n\n

    \u4f60\u53ef\u4ee5\u81ea\u7531\u5730\u5728\u623f\u95f4\u4e4b\u95f4\u6765\u56de\u8d70\u52a8\u3002

    \n\n

    \u5982\u679c\u80fd\u8fdb\u5165\u6bcf\u4e2a\u623f\u95f4\u8fd4\u56de true\uff0c\u5426\u5219\u8fd4\u56de false\u3002

    \n\n
      \n
    \n\n

    \u793a\u4f8b 1\uff1a

    \n\n
    \u8f93\u5165: [[1],[2],[3],[]]\n\u8f93\u51fa: true\n\u89e3\u91ca:  \n\u6211\u4eec\u4ece 0 \u53f7\u623f\u95f4\u5f00\u59cb\uff0c\u62ff\u5230\u94a5\u5319 1\u3002\n\u4e4b\u540e\u6211\u4eec\u53bb 1 \u53f7\u623f\u95f4\uff0c\u62ff\u5230\u94a5\u5319 2\u3002\n\u7136\u540e\u6211\u4eec\u53bb 2 \u53f7\u623f\u95f4\uff0c\u62ff\u5230\u94a5\u5319 3\u3002\n\u6700\u540e\u6211\u4eec\u53bb\u4e86 3 \u53f7\u623f\u95f4\u3002\n\u7531\u4e8e\u6211\u4eec\u80fd\u591f\u8fdb\u5165\u6bcf\u4e2a\u623f\u95f4\uff0c\u6211\u4eec\u8fd4\u56de true\u3002\n
    \n\n

    \u793a\u4f8b 2\uff1a

    \n\n
    \u8f93\u5165\uff1a[[1,3],[3,0,1],[2],[0]]\n\u8f93\u51fa\uff1afalse\n\u89e3\u91ca\uff1a\u6211\u4eec\u4e0d\u80fd\u8fdb\u5165 2 \u53f7\u623f\u95f4\u3002\n
    \n\n

    \u63d0\u793a\uff1a

    \n\n
      \n\t
    1. 1 <= rooms.length <= 1000
    2. \n\t
    3. 0 <= rooms[i].length <= 1000
    4. \n\t
    5. \u6240\u6709\u623f\u95f4\u4e2d\u7684\u94a5\u5319\u6570\u91cf\u603b\u8ba1\u4e0d\u8d85\u8fc7 3000\u3002
    6. \n
    \n*/\n\n\n/**\n * @param {number[][]} rooms\n * @return {boolean}\n */\nvar canVisitAllRooms = function(rooms) {\n \n};"} {"doc_id": "1ef5df206fa7a01d72b89112dec3e342", "text": "\"use strict\";\n\n/**\n * Creates a clone of an object, \n * adds new properties via an object spread. \n * \n * @param {object} obj Object to clone.\n * @param {object} addedProperty Property to add.\n * @returns {object} Cloned object with added property.\n */\nconst deepCloneAndAddProperty = (obj, addedProperty) => {\n // grab object key from added property\n var objectKey = Object.keys(addedProperty)[0];\n\n // add new property and return\n return {\n ...obj,\n [objectKey]: addedProperty[objectKey]\n };\n};\n\n// examples\nconst user = {\n id: 100,\n name: 'Jeremy Cantu'\n};\n\nconst userWithPassword = deepCloneAndAddProperty(user, {\n password: 'Password!'\n});\n\nconsole.log(userWithPassword);\n\n/**\n * Merges two objects using the spread operator\n * \n * @param {object} objOne Object to merge.\n * @param {object} objTwo Second obj to merge.\n * @returns {object} Merged object.\n */\nconst mergeObjects = (objOne, objTwo) => {\n // merge both objects and return\n return {\n ...objOne,\n ...objTwo\n };\n};\n\n// examples\nconst userOne = {\n id: 100,\n name: 'Jeremy Merged'\n};\n\nconst userWithPasswordTwo = {\n id: 100,\n password: 'PasswordM3rg3d!'\n};\n\nconst mergedUserObjects = mergeObjects(userOne, userWithPasswordTwo);\n\nconsole.log(mergedUserObjects);\n\n/**\n * Dynamically excludes properties using computed object property names\n * \n * @param {object} prop Property to dynamically remove.\n * @returns {object} Object sans property specified.\n */\nconst removeProperty = prop => ({\n // dynamic destructuring\n [prop]: _,\n ...rest\n}) => rest;\n\n// examples \nconst userToRemovePropsFrom = {\n id: 100,\n name: 'Howard Moon',\n password: 'Password!'\n};\n\nconst removePassword = removeProperty('password');\nconst removeId = removeProperty('id');\n\nconsole.log(removePassword(userToRemovePropsFrom)); //=> { id: 100, name: 'Howard Moon' }\nconsole.log(removeId(userToRemovePropsFrom)); //=> { name: 'Howard Moon', password: 'Password!' }\n\n/**\n * Get unique values from an array\n * \n * @param {array} arr Array to derive unique values from.\n * @returns {array} Return array with unique values.\n */\nconst createUniqueValuesArrayFromArray = arr => {\n return [...new Set(arr)];\n};\n\n// examples \nconst arrayWithNonUniqueValues = [1, 2, 3, 3]\n\nconst arrayWithUniqueValues = createUniqueValuesArrayFromArray(arrayWithNonUniqueValues);\n\nconsole.log(arrayWithUniqueValues);\n"} {"doc_id": "1f634822ce7788a7344a062a2d195d59", "text": "\"use strict\";\n// Interfaces\n// Interfaces in TypeScript are a useful tool\n// that you can use for your classes to ensure that\n// they conform to any specific rules that you want \n// them to. This is especially useful if there are\n// many people working on the same code base, and any\n// classes need to follow any specific rules.\n/*\ninterface IAnimal {\n name: string\n age: number\n\n feed(food: string, amount: number): void\n}\n\nclass Cat implements IAnimal {\n name: string\n age: number\n\n constructor(name: string, age: number) {\n this.name = name\n this.age = age\n }\n\n feed(food: string, amount: number): void {\n console.log(\n 'Feeding ' +\n this.name +\n ' the Cat ' +\n amount +\n ' kg of ' +\n food\n )\n }\n}\n// When a class implements interface,\n// the class must implement all of the methods and properties that\n// are described in the interface.\n// But that doesn't mean that a\n// class can't have its own custom methods and properties\n\nclass Dog implements IAnimal {\n name: string\n age: number\n\n constructor(name: string, age: number) {\n this.name = name\n this.age = age\n }\n\n feed(food: string, amount: number): void {\n console.log(\n 'Feeding ' +\n this.name +\n ' the Dog ' +\n amount +\n ' kg of ' +\n food\n )\n }\n}\n\nconst CAT = new Cat('Cosmo', 8)\nconst DOG = new Dog('Rusty', 12)\nCAT.feed('Fish', 0.1)\nDOG.feed('Beef', 0.25) */ \n"} {"doc_id": "1f7bba964216b2bb95a0438d9b8ad759", "text": "/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n * 80. Remove Duplicates From Sorted Array II\n *\n * Medium\n * Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at\n * most twice and return the new length.\n *\n * Do not allocate extra space for another array; you must do this by modifying the input array\n * in-place with O(1) extra memory.\n *\n * Clarification:\n * Confused why the returned value is an integer, but your answer is an array?\n *\n * Note that the input array is passed in by reference, which means a modification to the\n * input array will be known to the caller.\n *\n * Internally you can think of this:\n * // nums is passed in by reference. (i.e., without making a copy)\n * int len = removeDuplicates(nums);\n * // any modification to nums in your function would be known by the caller.\n * // using the length returned by your function, it prints the first len elements.\n *\n * for (int i = 0; i < len; i++) {\n * print(nums[i]);\n * }\n *\n * Example 1:\n * Input: nums = [1,1,1,2,2,3]\n * Output: 5, nums = [1,1,2,2,3]\n * Explanation: Your function should return length = 5, with the first five elements of nums being\n * 1, 1, 2, 2 and 3 respectively. It doesn't matter what you leave beyond the returned length.\n *\n * Example 2:\n * Input: nums = [0,0,1,1,1,1,2,3,3]\n * Output: 7, nums = [0,0,1,1,2,3,3]\n * Explanation: Your function should return length = 7, with the first seven elements of nums\n * being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set\n * beyond the returned length.\n *\n * Constraints:\n * 1 <= nums.length <= 3 * 104\n * -104 <= nums[i] <= 104\n * nums is sorted in ascending order.\n *** =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar removeDuplicates = function (nums) {\n var oc = 1;\n var sorted = 0;\n\n for (var i = 1; i < nums.length; i++) {\n if (nums[i] === nums[sorted]) {\n if (oc === 2) {\n continue;\n }\n\n oc++;\n } else {\n oc = 1;\n }\n\n sorted++;\n nums[sorted] = nums[i];\n }\n\n return sorted + 1;\n};"} {"doc_id": "2149f6fb0a2c0354fc56532f0dc364d6", "text": "\"use strict\";\n/*\n\u4f7f\u7528 class \u5173\u952e\u5b57\u521b\u5efa\u4e00\u4e2a\u7c7b\n \u5bf9\u8c61\u4e2d\u4e3b\u8981\u5305\u542b\u4e86\u4e24\u4e2a\u90e8\u5206\n - \u5c5e\u6027\n 1. \u76f4\u63a5\u5b9a\u4e49\u7684\u5c5e\u6027\u4e3a\u5b9e\u4f8b\u5c5e\u6027\uff0c\u53ea\u80fd\u901a\u8fc7\u5b9e\u4f8b\u5bf9\u8c61\u8bbf\u95ee\n 2. \u4f7f\u7528 static \u5173\u952e\u5b57\u5b9a\u4e49\u7684\u5c5e\u6027\u4e3a \u7c7b\u5c5e\u6027(\u9759\u6001\u5c5e\u6027)\uff0c\u53ef\u4ee5\u901a\u8fc7\u7c7b\u76f4\u63a5\u8bbf\u95ee\n 3. \u4f7f\u7528 readonly \u5173\u952e\u5b57\u5b9a\u4e49\u7684\u53ea\u8bfb\u5c5e\u6027\n - \u65b9\u6cd5\uff1a\u548c\u5c5e\u6027\u76841\uff0c2\u76f8\u540c\n*/\nclass Person {\n constructor() {\n //\u5b9a\u4e49\u5b9e\u4f8b\u5c5e\u6027\n this.name = \"\u5df4\u5fa1\u524d\";\n this.age = 18;\n //\u4f7f\u7528 readonly \u5b9a\u4e49\u53ea\u8bfb\u5c5e\u6027\n this.tags = \"suki\";\n }\n //\u5b9e\u4f8b\u65b9\u6cd5\n testA() {\n console.log(\"testA\");\n }\n //\u9759\u6001\u65b9\u6cd5\n static testB() {\n console.log(\"testB\");\n }\n}\n//\u4f7f\u7528 static \u5b9a\u4e49\u7c7b\u5c5e\u6027(\u9759\u6001\u5c5e\u6027)\nPerson.info = \"\u6211\u662f\u4eba\";\nconst per = new Person();\nconsole.log(per);\nconsole.log(per.name, per.age);\n//\u901a\u8fc7\u7c7b\u53bb\u8bbf\u95ee\u9759\u6001\u5c5e\u6027\nconsole.log(Person.info);\nconsole.log(per.tags);\n// per.tags = \"\u6b38\u563f\u563f\u563f\"; //\u65e0\u6cd5\u5206\u914d\u5230 \"tags\" \uff0c\u56e0\u4e3a\u5b83\u662f\u53ea\u8bfb\u5c5e\u6027\u3002ts(2540)\nper.testA();\nPerson.testB();\n"} {"doc_id": "214a7071e83057f54c859e15af476816", "text": "/**\n You can assume that there will only be one closest value.\n\n Each BST node has an integer value, a\n left child node, and a right child node. A node is\n said to be a valid BST node if and only if it satisfies the BST\n property: its value is strictly greater than the values of every\n node to its left; its value is less than or equal to the values\n of every node to its right; and its children nodes are either valid\n BST nodes themselves or None/null.\n\n\n Sample Input\n = 10\n / \\\n 5 15\n / \\ / \\\n 2 5 13 22\n / \\\n1 14\n\ntarget\n = 12\n\n Sample Output\n = 13\n */\n\nfunction bstClosestValue(tree, target) {\n return bstTraversalToClosest(tree, target, closest = Infinity)\n}\n\nfunction bstTraversalToClosest(tree, target, closest) {\n if (tree === null) return closest;\n if (Math.abs(target - closest) > Math.abs(target - tree.value)) {\n closest = tree.value;\n }\n if (target < tree.value) {\n return bstTraversalToClosest(tree.left, target, closest);\n }\n else if (target > tree.value) {\n return bstTraversalToClosest(tree.right, targer, closest);\n } else return closet\n}\n\n// This is the class of the input tree. Do not edit.\nclass BST {\n constructor(value) {\n this.value = value;\n this.left = null;\n this.right = null;\n }\n}"} {"doc_id": "21dcd530b934c0f41794dcfa83414bb3", "text": "const userInput = prompt(\"Enter something to see if it is \\\"Truthy\\\" or \\\"Falsy\\\"\");\n\nif (userInput) {\n console.log(\"Truthy!\");\n} else {\n console.log(\"Falsy!\");\n}\n\n// AND, OR, NOT\n// AND = &&\n// OR = ||\n// Not = !\n\nconst password = prompt(\"Enter your password: \");\n// Password valid if length is 6 or greater, and no spaces\nif (password.length >= 6 && password.indexOf(' ') === -1) {\n console.log(\"Valid Password. Access Granted.\")\n} else {\n console.log(\"Incorrect password format.\")\n}\n\n// SWITCH Example\nconst day = 2;\nswitch(day) {\n case 1:\n console.log(\"Sunday\");\n break;\n case 2:\n console.log(\"Monday\");\n break;\n case 3:\n console.log(\"Tuesday\");\n break;\n case 4:\n console.log(\"Wednesday\");\n break;\n case 5:\n console.log(\"Thursday\");\n break;\n case 6:\n console.log(\"Friday\");\n break;\n case 7:\n console.log(\"Saturday\");\n break;\n default:\n console.log(\"Invalid number for day of week.\")\n \n}"} {"doc_id": "223de3687b9d57adbd6a58f36058f373", "text": "\"use strict\";\n\nconst numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n(async () => {\n // async function is ES2017 Feature\n if (numbers.includes(5)) {\n // Array.prototype.includes is ES2016 Feature\n console.log('array includes 5'); // trailing commas in function is ES2017 Feature\n }\n\n for (const number of numbers) {\n // for..of.. is ES2015 Feature\n await console.log(number);\n }\n})();\n"} {"doc_id": "22f1d6f0d54c81b2dcb80b1f56e365fe", "text": "// Objetos em JavaScript\nvar paulo = {\n nome: \"Paulo\",\n vitorias: 2,\n empates: 1,\n derrotas: 1,\n pontos: 0 \n}\n\nvar irlene = {\n nome: \"Irlene\",\n vitorias: 3,\n empates: 5,\n derrotas: 7,\n pontos: 0\n}\n\n// calcJogo(irlene)\n// calcJogo(paulo)\n\n\nconsole.log(irlene.pontos)\nirlene.pontos = calcJogo(irlene)\npaulo.pontos = calcJogo(paulo)\n\n// console.log(irlene.pontos)\n// ao colocar um retorno da fun\u00e7\u00e3o, \u00e9 necess\u00e1rio ter um local para guardar o valor retornado, nesse caso, onde ser\u00e1 guardado esse valor \u00e9 na vari\u00e1vel do objeto \"irlene.pontos\".\n\nfunction calcJogo(jogador){\n var totalPontos = (jogador.vitorias * 3) + jogador.empates\n return totalPontos\n}\n// os par\u00e2metros s\u00e3o os que entram na fun\u00e7\u00e3o\n// o retorno \u00e9 o que retorna da fun\u00e7\u00e3o\n\nvar jogadores = [paulo, irlene]\n// chamando a fun\u00e7\u00e3o\nexibirJogadorTela(jogadores)\n\nfunction exibirJogadorTela(jogadores){\n var html = \"\"\n for(var i = 0; i < jogadores.length; i++){\n// quer dizer linha (uma nova linha)\n// quer dizer a coluna no HTML\n html += \"\" + jogadores[i].nome + \"\"\n html += \"\" + jogadores[i].vitorias + \"\"\n html += \"\" + jogadores[i].empates + \"\"\n html += \"\" + jogadores[i].derrotas + \"\"\n html += \"\" + jogadores[i].pontos + \"\"\n html += \"\"\n html += \"\"\n html += \"\"\n// dizer ao javascript onde se quer que ele mostre as informa\u00e7\u00f5es\n }\n var tabelaJogadores = document.getElementById(\"tabelaJogadores\")\n tabelaJogadores.innerHTML = html \n}\n\nfunction adicionarVitoria(i){\n// trabalha encima do indice do jogador indicado\n var jogador = jogadores[i]\n// esta express\u00e3o significa que ir\u00e1 ser somado mais uma vit\u00f3ria\n jogador.vitorias++\n jogador.pontos = calcJogo(jogador)\n// atualizar os pontos do jogador\n// chamar a fun\u00e7\u00e3o para exibir na tela\n exibirJogadorTela(jogadores)\n \n}\n\nfunction adicionarEmpate(i){\n var jogador = jogadores[i]\n jogador.empates++\n jogador.pontos = calcJogo(jogador)\n exibirJogadorTela(jogadores)\n}\n\nfunction adicionarDerrota(i){\n var jogador = jogadores[i]\n jogador.derrotas++\n jogador.pontos = calcJogo(jogador)\n exibirJogadorTela(jogadores)\n}\n\n/* \nTABELA DE CLASSIFICA\u00c7\u00c3O E OBJETOS NO JAVASCRIPT\nPARTICIPE E V\u00c1 MAIS FUNDO\n\nNesta sexta aula da Imers\u00e3o Dev, vamos criar uma tabela de classifica\u00e7\u00e3o e aprender o que s\u00e3o objetos no Javascript! O c\u00f3digo da aula para voc\u00ea acompanhar est\u00e1 aqui:\n\nhttps://codepen.io/imersao-dev/pen/yLgLLNY\n\nNeste programa, focamos em objetos no universo Javascript, criando uma tabela de classifica\u00e7\u00e3o, onde manipulamos os valores, realizamos c\u00e1lculos e inclu\u00edmos no HTML.\n\nConte\u00fado detalhado dessa aula\nRemover o c\u00f3digo est\u00e1tico do HTML;\nCriar um objeto no Javascript para cada jogador;\nCriar uma fun\u00e7\u00e3o que receba um objeto como par\u00e2metro para calcular os pontos;\nExibir o objeto na p\u00e1gina HTML;\nCriar uma fun\u00e7\u00e3o para adicionar vit\u00f3ria;\nCriar uma fun\u00e7\u00e3o para adicionar empate e outra para adicionar derrota;\nRecalcular os pontos quando vit\u00f3ria ou empate for adicionado.\n\nDesafios dessa aula!\nIncluir uma imagem na linha de cada jogador;\nUm bot\u00e3o que adiciona um novo jogador na tabela de classifica\u00e7\u00e3o.\n\nLinks importantes para voc\u00ea acompanhar a aula\nCodepen - editor de c\u00f3digo online\n-HTML, CSS e JavaScript, quais as diferen\u00e7as(https://www.alura.com.br/artigos/html-css-e-js-definicoes)\n-Reposit\u00f3rio do c\u00f3digo final da aula 5(https://codepen.io/imersao-dev/pen/KKaKKKK)\n\nLinks citados nessa aula\n-Mais sobre vari\u00e1veis(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Grammar_and_types#vari%C3%A1veis)\n\n-Mais sobre a fun\u00e7\u00e3o parseFloat(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/parseFloat)\n\nConte\u00fados extras:\nUsando o VSCode(https://www.youtube.com/watch?v=xvkuNF_8Coc)\nPrimeira aula da imers\u00e3o com Python(https://www.youtube.com/watch?v=DsFb24TgJ0c)\nPrimeiros passos na programa\u00e7\u00e3o(https://hipsters.tech/primeiros-passos-na-programacao-a-imersao-dev-hipsters-ponto-tech-243/)\n5 minutos de HTML(https://www.youtube.com/watch?v=3oSIqIqzN3M)\n\nComo compartilhar seu CodePen:\nClique na op\u00e7\u00e3o Settings no canto superior direito;\nSelecione a op\u00e7\u00e3o Pen Details (Detalhes);\nNo campo Pen Title voc\u00ea pode dar o nome do seu projeto;\nNo campo Pen Description, voc\u00ea pode dar detalhes sobre o projeto (o que ele faz, qual objetivo do projeto);\nPara compartilhar seu projeto, no campo Tags, voc\u00ea pode adicionar #imersaodev,#alura\nAgora s\u00f3 salvar seu projeto e compartilhar o link marcando a Alura nas redes sociais!\n*/"} {"doc_id": "22ff9c43fbaedb055d622f5d5f2d49f6", "text": "export default ` React Components can have local state. This state is not shared with the component's parent or the component's child by default. It is fully owned and controlled by the component itself.\n\nRemember when we looked at different ways of creating React component in the first page of this tutorial, we said there are things that component extending \\`React.Component\\` can do that a \\`function\\` component cannot do? Well state is one of them. \\`React.Component\\` can have states but \\`function\\` cannot have states.\n\n*Note: There's a new feature in React called hooks that let's us use state within function component but that's still in alpha so if we want to use state right now on a component we still need to use \\`React.Component\\`*\n\nBelow is a simple component that has a state. \n\n\\`\\`\\`jsx\nclass Component extends React.Component {\n constructor(props){\n super(props);\n this.state = {\n counter: 0 \n }\n }\n\n render() {\n return
    {this.state.counter}
    \n }\n}\n\\`\\`\\`\n\n\\`state\\` is just an object. If you notice the constructor, we initialized the state with \\`{counter: 0}\\`. And we used the state inside the \\`return\\` of the \\`render\\` function as \\`{this.state.counter}\\`.\n\nWe initialized the \\`state\\` in the constructor but how do we update it? For eg. in the above example how do we change the \\`counter\\` to lets say 1? For that React provides a function called \\`setState\\`. You should **always** use \\`setState\\` function to change \\`state\\` and **never** mutate it directly.\n\n\\`\\`\\`jsx\n//\u274c NEVER DO THIS\nthis.state.counter = 2;\n\n// \u2705 ALWAYS DO THIS\nthis.setState({\n counter: 2\n});\n\\`\\`\\`\nIf \\`state\\` is just an instance variable in the component, can we call it some other name and why do we **have** to use \\`setState\\`? Well no we cannot call it by some other name and we have to use \\`setState\\` to update the \\`state\\` mainly because React understands \\`state\\`. When \\`state\\` of your component changes, React re-renders your component (by re-render I mean calls the \\`render\\` function again to see if the DOM will change as a result of change in \\`state\\`). This is fundamental to the declarative nature of React.\n\n### setState\n\nLet's look deeper into \\`setState\\` function. First argument of \\`setState\\` function can take either a new state object or a function. It also has a optional second argument, which is a callback which is executed when the state is updated.\n\n\\`\\`\\`jsx\nsetState(newState || function, optional callback)\n\\`\\`\\`\n\nThe way \\`setState\\` updates the state is:\n- If the first argument of the \\`setState\\` function is an object, it merges the current \\`state\\` object with whatever you passed to the \\`setState\\` function. For example:\n\n\\`\\`\\`jsx\nstate = { a: 1, b: 2, c: 3} //current state\nthis.setState({ a: 3 }); //we call setState with just one key value pair\n\n//it will **merge** the initial state with the object passed to setState\n//as a result only the value for that one key is updated\nstate = { a: 3, b: 2, c: 3 } //state after setState is flushed\n\\`\\`\\`\n\n- If the first argument is a function then it first executes the function by passing the current \\`state\\` as it's argument. The function must return an object. It then merges this output with the current \\`state\\` just like it did above. For example:\n\n\\`\\`\\`jsx\nstate = { a: 1, b: 2, c: 3} //initial state\n//we called setState with a function\nthis.setState(currentState => ({\n a: currentState.a + 1\n}));\n//it executes the function by passing the current state object as argument.\n//since currentState.a is 1, function returns { a: 2 }\n//it now merges this returned object with the original state\nstate = { a: 2, b: 2, c: 3 } //state after setState is called\n\\`\\`\\`\n\nOne thing you must know about \\`setState\\` function is that it may be asynchronous. So **do not** rely on it to update the state immediately. This is not a bug, it's by design. If you want to read up on the design decision behind \\`setState\\` call being asynchonous, here's a [nice explanation](https://github.com/facebook/react/issues/11527#issuecomment-360199710).\n\nSince \\`setState\\` can be asynchronous below code will not give you the right result because by the time we \\`console.log\\` the \\`state.counter\\` value, it won't be updated.\n\n\\`\\`\\`jsx\n//\u274c WRONG RESULT. Do not rely on setState to be synchronous\nconsole.log(this.state.counter);//prints 0\nthis.setState({\n counter: this.state.counter + 1\n}); //this is asynchronous call\nconsole.log(this.state.counter);//still prints 0\n\\`\\`\\`\n\nAlso if you want to update \\`state\\` using the current state value **always** use the updater function inside \\`setState\\` instead of passing object. For example below code will not work.\n\n\\`\\`\\`jsx\n//\u274c DONT DO THIS\n//If you are using the current state value to update the state, never use this.state directly inside setState\nconsole.log(this.state.counter); //prints 0\nthis.setState({ counter: this.state.counter + 1 });\nthis.setState({ counter: this.state.counter + 1 });\nthis.setState({ counter: this.state.counter + 1 });\n//the state will be 1 when all of the calls are flushed\n//because since the calls were asynchronous, this.state.counter \n//on all three calls were 0 and adding 1 resulted in 1.\n\n\n//\u2705 ALWAYS DO THIS\n//If you are using current state value to update the state, always use updater function\nconsole.log(this.state.counter); //prints 0\nthis.setState((state) => ({ counter: state.counter + 1}) );\nthis.setState((state) => ({ counter: state.counter + 1}) );\nthis.setState((state) => ({ counter: state.counter + 1}) );\n//this is guaranted to work!\n//when all three calls are flushed the value of\n//this.state.counter will be 3\n\\`\\`\\`\n\nLet's look at an exercise. Click the '+', '-' on the right side to see the expected behavior. Now please open the exercise file and make changes as instructed in the exercise file to achieve the expected behavior.\n\n\n\nI know we discussed several things about \\`state\\` and it must be overwhelming. Let's just recap the rules:\n- Never mutate \\`this.state\\` directly. Always use \\`this.setState\\` to update the \\`state\\`.\n- If your new \\`state\\` doesn't depend on the old \\`state\\` then you can use \\`this.setState(object)\\` construct.\n- If your new \\`state\\` depends on the old \\`state\\` then use \\`this.setState(function(currentState){ .. })\\` construct.\n\n#### Props and State\nSince we now have looked into both \\`state\\` and \\`props\\` how are they different and how are they similar?\n\nThe difference between \\`state\\` and \\`props\\` is that \\`state\\` is owned by the component itself while \\`props\\` is something that is passed down to the component by it's parent.\n\nAnd the similarity (sort of) is that React automatically re-renders your component when either the component's \\`state\\` changes or when the component's \\`props\\` changes.\n\nYour component's \\`render\\` function is a function of both \\`state\\` and \\`props\\` meaning it defines what your component should look like given the \\`state\\` and \\`props\\`. It should be pure function in a sense that if the component has same \\`state\\` and \\`props\\` it should render exactly same content no matter how many times it's called and shouldn't have any side effects.\n `"} {"doc_id": "23073a705210451070f0da9122729826", "text": "/*\n

    There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:

    \n\n
      \n\t
    1. Serve 100 ml of soup A and 0 ml of soup B
    2. \n\t
    3. Serve 75 ml of soup A and 25 ml of soup B
    4. \n\t
    5. Serve 50 ml of soup A and 50 ml of soup B
    6. \n\t
    7. Serve 25 ml of soup A and 75 ml of soup B
    8. \n
    \n\n

    When we serve some soup, we give it to someone and we no longer have it.  Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can.  We stop once we no longer have some quantity of both types of soup.

    \n\n

    Note that we do not have the operation where all 100 ml's of soup B are used first.  

    \n\n

    Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.

    \n\n

     

    \n\n
    \nExample:\nInput: N = 50\nOutput: 0.625\nExplanation: \nIf we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.\n\n
    \n\n

    Notes:

    \n\n
      \n\t
    • 0 <= N <= 10^9. 
    • \n\t
    • Answers within 10^-6 of the true value will be accepted as correct.
    • \n

    \u6709 A \u548c B \u4e24\u79cd\u7c7b\u578b\u7684\u6c64\u3002\u4e00\u5f00\u59cb\u6bcf\u79cd\u7c7b\u578b\u7684\u6c64\u6709 N \u6beb\u5347\u3002\u6709\u56db\u79cd\u5206\u914d\u64cd\u4f5c\uff1a

    \n\n
      \n\t
    1. \u63d0\u4f9b 100ml \u7684\u6c64A \u548c 0ml \u7684\u6c64B\u3002
    2. \n\t
    3. \u63d0\u4f9b 75ml \u7684\u6c64A \u548c 25ml \u7684\u6c64B\u3002
    4. \n\t
    5. \u63d0\u4f9b 50ml \u7684\u6c64A \u548c 50ml \u7684\u6c64B\u3002
    6. \n\t
    7. \u63d0\u4f9b 25ml \u7684\u6c64A \u548c 75ml \u7684\u6c64B\u3002
    8. \n
    \n\n

    \u5f53\u6211\u4eec\u628a\u6c64\u5206\u914d\u7ed9\u67d0\u4eba\u4e4b\u540e\uff0c\u6c64\u5c31\u6ca1\u6709\u4e86\u3002\u6bcf\u4e2a\u56de\u5408\uff0c\u6211\u4eec\u5c06\u4ece\u56db\u79cd\u6982\u7387\u540c\u4e3a0.25\u7684\u64cd\u4f5c\u4e2d\u8fdb\u884c\u5206\u914d\u9009\u62e9\u3002\u5982\u679c\u6c64\u7684\u5269\u4f59\u91cf\u4e0d\u8db3\u4ee5\u5b8c\u6210\u67d0\u6b21\u64cd\u4f5c\uff0c\u6211\u4eec\u5c06\u5c3d\u53ef\u80fd\u5206\u914d\u3002\u5f53\u4e24\u79cd\u7c7b\u578b\u7684\u6c64\u90fd\u5206\u914d\u5b8c\u65f6\uff0c\u505c\u6b62\u64cd\u4f5c\u3002

    \n\n

    \u6ce8\u610f\u4e0d\u5b58\u5728\u5148\u5206\u914d100 ml\u6c64B\u7684\u64cd\u4f5c\u3002

    \n\n

    \u9700\u8981\u8fd4\u56de\u7684\u503c\uff1a \u6c64A\u5148\u5206\u914d\u5b8c\u7684\u6982\u7387 + \u6c64A\u548c\u6c64B\u540c\u65f6\u5206\u914d\u5b8c\u7684\u6982\u7387 / 2\u3002

    \n\n
    \n\u793a\u4f8b:\n\u8f93\u5165: N = 50\n\u8f93\u51fa: 0.625\n\u89e3\u91ca:\n\u5982\u679c\u6211\u4eec\u9009\u62e9\u524d\u4e24\u4e2a\u64cd\u4f5c\uff0cA\u5c06\u9996\u5148\u53d8\u4e3a\u7a7a\u3002\u5bf9\u4e8e\u7b2c\u4e09\u4e2a\u64cd\u4f5c\uff0cA\u548cB\u4f1a\u540c\u65f6\u53d8\u4e3a\u7a7a\u3002\u5bf9\u4e8e\u7b2c\u56db\u4e2a\u64cd\u4f5c\uff0cB\u5c06\u9996\u5148\u53d8\u4e3a\u7a7a\u3002\n\u6240\u4ee5A\u53d8\u4e3a\u7a7a\u7684\u603b\u6982\u7387\u52a0\u4e0aA\u548cB\u540c\u65f6\u53d8\u4e3a\u7a7a\u7684\u6982\u7387\u7684\u4e00\u534a\u662f 0.25 *(1 + 1 + 0.5 + 0)= 0.625\u3002\n
    \n\n

    \u6ce8\u91ca:

    \n\n
      \n\t
    • 0 <= N <= 10^9\u3002
    • \n\t
    • \n\t

      \u8fd4\u56de\u503c\u5728 10^-6 \u7684\u8303\u56f4\u5c06\u88ab\u8ba4\u4e3a\u662f\u6b63\u786e\u7684\u3002

      \n\t
    • \n
    \n

    \u6709 A \u548c B \u4e24\u79cd\u7c7b\u578b\u7684\u6c64\u3002\u4e00\u5f00\u59cb\u6bcf\u79cd\u7c7b\u578b\u7684\u6c64\u6709 N \u6beb\u5347\u3002\u6709\u56db\u79cd\u5206\u914d\u64cd\u4f5c\uff1a

    \n\n
      \n\t
    1. \u63d0\u4f9b 100ml \u7684\u6c64A \u548c 0ml \u7684\u6c64B\u3002
    2. \n\t
    3. \u63d0\u4f9b 75ml \u7684\u6c64A \u548c 25ml \u7684\u6c64B\u3002
    4. \n\t
    5. \u63d0\u4f9b 50ml \u7684\u6c64A \u548c 50ml \u7684\u6c64B\u3002
    6. \n\t
    7. \u63d0\u4f9b 25ml \u7684\u6c64A \u548c 75ml \u7684\u6c64B\u3002
    8. \n
    \n\n

    \u5f53\u6211\u4eec\u628a\u6c64\u5206\u914d\u7ed9\u67d0\u4eba\u4e4b\u540e\uff0c\u6c64\u5c31\u6ca1\u6709\u4e86\u3002\u6bcf\u4e2a\u56de\u5408\uff0c\u6211\u4eec\u5c06\u4ece\u56db\u79cd\u6982\u7387\u540c\u4e3a0.25\u7684\u64cd\u4f5c\u4e2d\u8fdb\u884c\u5206\u914d\u9009\u62e9\u3002\u5982\u679c\u6c64\u7684\u5269\u4f59\u91cf\u4e0d\u8db3\u4ee5\u5b8c\u6210\u67d0\u6b21\u64cd\u4f5c\uff0c\u6211\u4eec\u5c06\u5c3d\u53ef\u80fd\u5206\u914d\u3002\u5f53\u4e24\u79cd\u7c7b\u578b\u7684\u6c64\u90fd\u5206\u914d\u5b8c\u65f6\uff0c\u505c\u6b62\u64cd\u4f5c\u3002

    \n\n

    \u6ce8\u610f\u4e0d\u5b58\u5728\u5148\u5206\u914d100 ml\u6c64B\u7684\u64cd\u4f5c\u3002

    \n\n

    \u9700\u8981\u8fd4\u56de\u7684\u503c\uff1a \u6c64A\u5148\u5206\u914d\u5b8c\u7684\u6982\u7387 + \u6c64A\u548c\u6c64B\u540c\u65f6\u5206\u914d\u5b8c\u7684\u6982\u7387 / 2\u3002

    \n\n
    \n\u793a\u4f8b:\n\u8f93\u5165: N = 50\n\u8f93\u51fa: 0.625\n\u89e3\u91ca:\n\u5982\u679c\u6211\u4eec\u9009\u62e9\u524d\u4e24\u4e2a\u64cd\u4f5c\uff0cA\u5c06\u9996\u5148\u53d8\u4e3a\u7a7a\u3002\u5bf9\u4e8e\u7b2c\u4e09\u4e2a\u64cd\u4f5c\uff0cA\u548cB\u4f1a\u540c\u65f6\u53d8\u4e3a\u7a7a\u3002\u5bf9\u4e8e\u7b2c\u56db\u4e2a\u64cd\u4f5c\uff0cB\u5c06\u9996\u5148\u53d8\u4e3a\u7a7a\u3002\n\u6240\u4ee5A\u53d8\u4e3a\u7a7a\u7684\u603b\u6982\u7387\u52a0\u4e0aA\u548cB\u540c\u65f6\u53d8\u4e3a\u7a7a\u7684\u6982\u7387\u7684\u4e00\u534a\u662f 0.25 *(1 + 1 + 0.5 + 0)= 0.625\u3002\n
    \n\n

    \u6ce8\u91ca:

    \n\n
      \n\t
    • 0 <= N <= 10^9\u3002
    • \n\t
    • \n\t

      \u8fd4\u56de\u503c\u5728 10^-6 \u7684\u8303\u56f4\u5c06\u88ab\u8ba4\u4e3a\u662f\u6b63\u786e\u7684\u3002

      \n\t
    • \n
    \n*/\n\n\n/**\n * @param {number} N\n * @return {number}\n */\nvar soupServings = function(N) {\n \n};"} {"doc_id": "24c96253a06459fed1440d8eea5ecef5", "text": "function onSubmit(){\n var myInt = parseInt(document.getElementById('user-input').value);\n let myFunc = num => Number(num);\n var intArr = Array.from(String(myInt), myFunc);\n \n document.getElementById('value-output').innerHTML = \"Odd Value: \" + solution(intArr);\n \n}\n\n\n\n//GENERAL NOTE\n//Assigning properties to a given object containing an Array.\n//We are able to eliminate duplicate values containing the same property\n\n//Each repetitive value teachnically contains the same property right?\n//stay open minded\n\nfunction solution(A) {\n //Creating our Object before assigning property values\n object = new Object()\n \n //Looping through the length of the given Array\n //Example: A= [1,2,1,2,1,3,1] which is the length of 6\n for(let i=0; i < A.length; i++){\n //Remember what I said about repetitive values containing the same properties\n //Now we need to check if that index contains a property\n if(object.hasOwnProperty(A[i])){\n //If it does contain a property, we delete that assigned property\n //Now this is the core to the whole function, allowing us to delete all\n //duplicate values containing the same property, which allows to find the odd occurance, which does NOT\n //have a repetitive value\n delete object[A[i]]\n }\n else {\n //Applies the property value of 1\n object[A[i]] = 1;\n }\n }\n //Display all the values that contains a property, meaning if A= [1,2,1,2,1, 3 ,1],\n //3 would standout right?\n solution = Object.keys(object)\n return parseInt(solution[0])\n}\n\n\n//QUESTION (TOTAL 100%)\n\n//A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.\n\n//For example, in array A such that:\n\n //A[0] = 9 A[1] = 3 A[2] = 9\n //A[3] = 3 A[4] = 9 A[5] = 7\n //A[6] = 9\n//the elements at indexes 0 and 2 have value 9,\n//the elements at indexes 1 and 3 have value 3,\n//the elements at indexes 4 and 6 have value 9,\n//the element at index 5 has value 7 and is unpaired.\n//Write a function:\n\n//function solution(A);\n\n//that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.\n\n//For example, given array A such that:\n\n //A[0] = 9 A[1] = 3 A[2] = 9\n //A[3] = 3 A[4] = 9 A[5] = 7\n //A[6] = 9\n//the function should return 7, as explained in the example above.\n\n//Write an efficient algorithm for the following assumptions:\n\n//N is an odd integer within the range [1..1,000,000];\n//each element of array A is an integer within the range [1..1,000,000,000];\n//all but one of the values in A occur an even number of times."} {"doc_id": "24ed16158efa7201bcc36ed5823bc0a9", "text": "/*\n

    In a 2D grid of 0s and 1s, we change at most one 0 to a 1.

    \n\n

    After, what is the size of the largest island? (An island is a 4-directionally connected group of 1s).

    \n\n

    Example 1:

    \n\n
    \nInput: [[1, 0], [0, 1]]\nOutput: 3\nExplanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\n
    \n\n

    Example 2:

    \n\n
    \nInput: [[1, 1], [1, 0]]\nOutput: 4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 1.
    \n\n

    Example 3:

    \n\n
    \nInput: [[1, 1], [1, 1]]\nOutput: 4\nExplanation: Can't change any 0 to 1, only one island with area = 1.
    \n\n

     

    \n\n

    Notes:

    \n\n
      \n\t
    • 1 <= grid.length = grid[0].length <= 50.
    • \n\t
    • 0 <= grid[i][j] <= 1.
    • \n
    \n\n

     

    \u5728\u4e8c\u7ef4\u5730\u56fe\u4e0a\uff0c 0\u4ee3\u8868\u6d77\u6d0b\uff0c 1\u4ee3\u8868\u9646\u5730\uff0c\u6211\u4eec\u6700\u591a\u53ea\u80fd\u5c06\u4e00\u683c 0 \u6d77\u6d0b\u53d8\u6210 1\u53d8\u6210\u9646\u5730\u3002

    \n\n

    \u8fdb\u884c\u586b\u6d77\u4e4b\u540e\uff0c\u5730\u56fe\u4e0a\u6700\u5927\u7684\u5c9b\u5c7f\u9762\u79ef\u662f\u591a\u5c11\uff1f\uff08\u4e0a\u3001\u4e0b\u3001\u5de6\u3001\u53f3\u56db\u4e2a\u65b9\u5411\u76f8\u8fde\u7684 1 \u53ef\u5f62\u6210\u5c9b\u5c7f\uff09

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: [[1, 0], [0, 1]]\n\u8f93\u51fa: 3\n\u89e3\u91ca: \u5c06\u4e00\u683c0\u53d8\u62101\uff0c\u6700\u7ec8\u8fde\u901a\u4e24\u4e2a\u5c0f\u5c9b\u5f97\u5230\u9762\u79ef\u4e3a 3 \u7684\u5c9b\u5c7f\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: [[1, 1], [1, 0]]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u5c06\u4e00\u683c0\u53d8\u62101\uff0c\u5c9b\u5c7f\u7684\u9762\u79ef\u6269\u5927\u4e3a 4\u3002
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \n\u8f93\u5165: [[1, 1], [1, 1]]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u6ca1\u67090\u53ef\u4ee5\u8ba9\u6211\u4eec\u53d8\u62101\uff0c\u9762\u79ef\u4f9d\u7136\u4e3a 4\u3002
    \n\n

    \u8bf4\u660e:

    \n\n
      \n\t
    • 1 <= grid.length = grid[0].length <= 50
    • \n\t
    • 0 <= grid[i][j] <= 1
    • \n
    \n

    \u5728\u4e8c\u7ef4\u5730\u56fe\u4e0a\uff0c 0\u4ee3\u8868\u6d77\u6d0b\uff0c 1\u4ee3\u8868\u9646\u5730\uff0c\u6211\u4eec\u6700\u591a\u53ea\u80fd\u5c06\u4e00\u683c 0 \u6d77\u6d0b\u53d8\u6210 1\u53d8\u6210\u9646\u5730\u3002

    \n\n

    \u8fdb\u884c\u586b\u6d77\u4e4b\u540e\uff0c\u5730\u56fe\u4e0a\u6700\u5927\u7684\u5c9b\u5c7f\u9762\u79ef\u662f\u591a\u5c11\uff1f\uff08\u4e0a\u3001\u4e0b\u3001\u5de6\u3001\u53f3\u56db\u4e2a\u65b9\u5411\u76f8\u8fde\u7684 1 \u53ef\u5f62\u6210\u5c9b\u5c7f\uff09

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \n\u8f93\u5165: [[1, 0], [0, 1]]\n\u8f93\u51fa: 3\n\u89e3\u91ca: \u5c06\u4e00\u683c0\u53d8\u62101\uff0c\u6700\u7ec8\u8fde\u901a\u4e24\u4e2a\u5c0f\u5c9b\u5f97\u5230\u9762\u79ef\u4e3a 3 \u7684\u5c9b\u5c7f\u3002\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \n\u8f93\u5165: [[1, 1], [1, 0]]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u5c06\u4e00\u683c0\u53d8\u62101\uff0c\u5c9b\u5c7f\u7684\u9762\u79ef\u6269\u5927\u4e3a 4\u3002
    \n\n

    \u793a\u4f8b 3:

    \n\n
    \n\u8f93\u5165: [[1, 1], [1, 1]]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u6ca1\u67090\u53ef\u4ee5\u8ba9\u6211\u4eec\u53d8\u62101\uff0c\u9762\u79ef\u4f9d\u7136\u4e3a 4\u3002
    \n\n

    \u8bf4\u660e:

    \n\n
      \n\t
    • 1 <= grid.length = grid[0].length <= 50
    • \n\t
    • 0 <= grid[i][j] <= 1
    • \n
    \n*/\n\n\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar largestIsland = function(grid) {\n \n};"} {"doc_id": "2534f4d86d0d1be19344c5213e30dea4", "text": "/**\n * Adds together all the elements of a list.\n *\n * @param {Array} arr An array of numbers\n * @return {Number} The sum of all the numbers in the list.\n * @example\n *\n * sum([2,4,6,8,100,1]); //=> 121\n */\nexport default (arr = []) => {\n let sum = 0;\n\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n\n return sum;\n};\n"} {"doc_id": "25792f260ccaf0ced6cae6849d8f3080", "text": "/*\n

    Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii".  Here, we have groups, of adjacent letters that are all the same character, and adjacent characters to the group are different.  A group is extended if that group is length 3 or more, so "e" and "o" would be extended in the first example, and "i" would be extended in the second example.  As another example, the groups of "abbcccaaaa" would be "a", "bb", "ccc", and "aaaa"; and "ccc" and "aaaa" are the extended groups of that string.

    \n\n

    For some given string S, a query word is stretchy if it can be made to be equal to S by extending some groups.  Formally, we are allowed to repeatedly choose a group (as defined above) of characters c, and add some number of the same character c to it so that the length of the group is 3 or more.  Note that we cannot extend a group of size one like "h" to a group of size two like "hh" - all extensions must leave the group extended - ie., at least 3 characters long.

    \n\n

    Given a list of query words, return the number of words that are stretchy. 

    \n\n
    \nExample:\nInput: \nS = "heeellooo"\nwords = ["hello", "hi", "helo"]\nOutput: 1\nExplanation: \nWe can extend "e" and "o" in the word "hello" to get "heeellooo".\nWe can't extend "helo" to get "heeellooo" because the group "ll" is not extended.\n
    \n\n

    Notes:

    \n\n
      \n\t
    • 0 <= len(S) <= 100.
    • \n\t
    • 0 <= len(words) <= 100.
    • \n\t
    • 0 <= len(words[i]) <= 100.
    • \n\t
    • S and all words in words consist only of lowercase letters
    • \n
    \n\n

     

    \n

    \u6709\u65f6\u5019\u4eba\u4eec\u4f1a\u7528\u989d\u5916\u7684\u5b57\u6bcd\u6765\u8868\u793a\u989d\u5916\u7684\u60c5\u611f\uff0c\u6bd4\u5982 "hello" -> "heeellooo", "hi" -> "hiii"\u3002\u6211\u4eec\u5c06\u8fde\u7eed\u7684\u76f8\u540c\u7684\u5b57\u6bcd\u5206\u7ec4\uff0c\u5e76\u4e14\u76f8\u90bb\u7ec4\u7684\u5b57\u6bcd\u90fd\u4e0d\u76f8\u540c\u3002\u6211\u4eec\u5c06\u4e00\u4e2a\u62e5\u6709\u4e09\u4e2a\u6216\u4ee5\u4e0a\u5b57\u6bcd\u7684\u7ec4\u5b9a\u4e49\u4e3a\u6269\u5f20\u72b6\u6001\uff08extended\uff09\uff0c\u5982\u7b2c\u4e00\u4e2a\u4f8b\u5b50\u4e2d\u7684 "e" \u548c" o" \u4ee5\u53ca\u7b2c\u4e8c\u4e2a\u4f8b\u5b50\u4e2d\u7684 "i"\u3002 \u6b64\u5916\uff0c"abbcccaaaa" \u5c06\u6709\u5206\u7ec4 "a" , "bb" , "ccc" , "dddd"\uff1b\u5176\u4e2d "ccc" \u548c "aaaa" \u5904\u4e8e\u6269\u5f20\u72b6\u6001\u3002

    \n\n

    \u5bf9\u4e8e\u4e00\u4e2a\u7ed9\u5b9a\u7684\u5b57\u7b26\u4e32 S \uff0c\u5982\u679c\u53e6\u4e00\u4e2a\u5355\u8bcd\u80fd\u591f\u901a\u8fc7\u5c06\u4e00\u4e9b\u5b57\u6bcd\u7ec4\u6269\u5f20\u4ece\u800c\u4f7f\u5176\u548c S \u76f8\u540c\uff0c\u6211\u4eec\u5c06\u8fd9\u4e2a\u5355\u8bcd\u5b9a\u4e49\u4e3a\u53ef\u6269\u5f20\u7684\uff08stretchy\uff09\u3002\u6211\u4eec\u5141\u8bb8\u9009\u62e9\u4e00\u4e2a\u5b57\u6bcd\u7ec4\uff08\u5982\u5305\u542b\u5b57\u6bcd c \uff09\uff0c\u7136\u540e\u5f80\u5176\u4e2d\u6dfb\u52a0\u76f8\u540c\u7684\u5b57\u6bcd c \u4f7f\u5176\u957f\u5ea6\u8fbe\u5230 3 \u6216\u4ee5\u4e0a\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u4e0d\u80fd\u5c06\u4e00\u4e2a\u53ea\u5305\u542b\u4e00\u4e2a\u5b57\u6bcd\u7684\u5b57\u6bcd\u7ec4\uff0c\u5982 "h"\uff0c\u6269\u5f20\u5230\u4e00\u4e2a\u5305\u542b\u4e24\u4e2a\u5b57\u6bcd\u7684\u7ec4\uff0c\u5982 "hh"\uff1b\u6240\u6709\u7684\u6269\u5f20\u5fc5\u987b\u4f7f\u8be5\u5b57\u6bcd\u7ec4\u53d8\u6210\u6269\u5f20\u72b6\u6001\uff08\u81f3\u5c11\u5305\u542b\u4e09\u4e2a\u5b57\u6bcd\uff09\u3002

    \n\n

    \u8f93\u5165\u4e00\u7ec4\u5355\u8bcd\uff0c\u8f93\u51fa\u5176\u4e2d\u53ef\u6269\u5f20\u7684\u5355\u8bcd\u6570\u91cf\u3002

    \n\n
    \n\u793a\u4f8b\uff1a\n\u8f93\u5165\uff1a \nS = "heeellooo"\nwords = ["hello", "hi", "helo"]\n\u8f93\u51fa\uff1a1\n\u89e3\u91ca\uff1a\n\u6211\u4eec\u80fd\u901a\u8fc7\u6269\u5f20"hello"\u7684"e"\u548c"o"\u6765\u5f97\u5230"heeellooo"\u3002\n\u6211\u4eec\u4e0d\u80fd\u901a\u8fc7\u6269\u5f20"helo"\u6765\u5f97\u5230"heeellooo"\u56e0\u4e3a"ll"\u4e0d\u5904\u4e8e\u6269\u5f20\u72b6\u6001\u3002\n
    \n\n

    \u8bf4\u660e\uff1a

    \n\n
      \n\t
    • 0 <= len(S) <= 100\u3002
    • \n\t
    • 0 <= len(words) <= 100\u3002
    • \n\t
    • 0 <= len(words[i]) <= 100\u3002
    • \n\t
    • S \u548c\u6240\u6709\u5728 words \u4e2d\u7684\u5355\u8bcd\u90fd\u53ea\u7531\u5c0f\u5199\u5b57\u6bcd\u7ec4\u6210\u3002
    • \n
    \n

    \u6709\u65f6\u5019\u4eba\u4eec\u4f1a\u7528\u989d\u5916\u7684\u5b57\u6bcd\u6765\u8868\u793a\u989d\u5916\u7684\u60c5\u611f\uff0c\u6bd4\u5982 "hello" -> "heeellooo", "hi" -> "hiii"\u3002\u6211\u4eec\u5c06\u8fde\u7eed\u7684\u76f8\u540c\u7684\u5b57\u6bcd\u5206\u7ec4\uff0c\u5e76\u4e14\u76f8\u90bb\u7ec4\u7684\u5b57\u6bcd\u90fd\u4e0d\u76f8\u540c\u3002\u6211\u4eec\u5c06\u4e00\u4e2a\u62e5\u6709\u4e09\u4e2a\u6216\u4ee5\u4e0a\u5b57\u6bcd\u7684\u7ec4\u5b9a\u4e49\u4e3a\u6269\u5f20\u72b6\u6001\uff08extended\uff09\uff0c\u5982\u7b2c\u4e00\u4e2a\u4f8b\u5b50\u4e2d\u7684 "e" \u548c" o" \u4ee5\u53ca\u7b2c\u4e8c\u4e2a\u4f8b\u5b50\u4e2d\u7684 "i"\u3002 \u6b64\u5916\uff0c"abbcccaaaa" \u5c06\u6709\u5206\u7ec4 "a" , "bb" , "ccc" , "dddd"\uff1b\u5176\u4e2d "ccc" \u548c "aaaa" \u5904\u4e8e\u6269\u5f20\u72b6\u6001\u3002

    \n\n

    \u5bf9\u4e8e\u4e00\u4e2a\u7ed9\u5b9a\u7684\u5b57\u7b26\u4e32 S \uff0c\u5982\u679c\u53e6\u4e00\u4e2a\u5355\u8bcd\u80fd\u591f\u901a\u8fc7\u5c06\u4e00\u4e9b\u5b57\u6bcd\u7ec4\u6269\u5f20\u4ece\u800c\u4f7f\u5176\u548c S \u76f8\u540c\uff0c\u6211\u4eec\u5c06\u8fd9\u4e2a\u5355\u8bcd\u5b9a\u4e49\u4e3a\u53ef\u6269\u5f20\u7684\uff08stretchy\uff09\u3002\u6211\u4eec\u5141\u8bb8\u9009\u62e9\u4e00\u4e2a\u5b57\u6bcd\u7ec4\uff08\u5982\u5305\u542b\u5b57\u6bcd c \uff09\uff0c\u7136\u540e\u5f80\u5176\u4e2d\u6dfb\u52a0\u76f8\u540c\u7684\u5b57\u6bcd c \u4f7f\u5176\u957f\u5ea6\u8fbe\u5230 3 \u6216\u4ee5\u4e0a\u3002\u6ce8\u610f\uff0c\u6211\u4eec\u4e0d\u80fd\u5c06\u4e00\u4e2a\u53ea\u5305\u542b\u4e00\u4e2a\u5b57\u6bcd\u7684\u5b57\u6bcd\u7ec4\uff0c\u5982 "h"\uff0c\u6269\u5f20\u5230\u4e00\u4e2a\u5305\u542b\u4e24\u4e2a\u5b57\u6bcd\u7684\u7ec4\uff0c\u5982 "hh"\uff1b\u6240\u6709\u7684\u6269\u5f20\u5fc5\u987b\u4f7f\u8be5\u5b57\u6bcd\u7ec4\u53d8\u6210\u6269\u5f20\u72b6\u6001\uff08\u81f3\u5c11\u5305\u542b\u4e09\u4e2a\u5b57\u6bcd\uff09\u3002

    \n\n

    \u8f93\u5165\u4e00\u7ec4\u5355\u8bcd\uff0c\u8f93\u51fa\u5176\u4e2d\u53ef\u6269\u5f20\u7684\u5355\u8bcd\u6570\u91cf\u3002

    \n\n
    \n\u793a\u4f8b\uff1a\n\u8f93\u5165\uff1a \nS = "heeellooo"\nwords = ["hello", "hi", "helo"]\n\u8f93\u51fa\uff1a1\n\u89e3\u91ca\uff1a\n\u6211\u4eec\u80fd\u901a\u8fc7\u6269\u5f20"hello"\u7684"e"\u548c"o"\u6765\u5f97\u5230"heeellooo"\u3002\n\u6211\u4eec\u4e0d\u80fd\u901a\u8fc7\u6269\u5f20"helo"\u6765\u5f97\u5230"heeellooo"\u56e0\u4e3a"ll"\u4e0d\u5904\u4e8e\u6269\u5f20\u72b6\u6001\u3002\n
    \n\n

    \u8bf4\u660e\uff1a

    \n\n
      \n\t
    • 0 <= len(S) <= 100\u3002
    • \n\t
    • 0 <= len(words) <= 100\u3002
    • \n\t
    • 0 <= len(words[i]) <= 100\u3002
    • \n\t
    • S \u548c\u6240\u6709\u5728 words \u4e2d\u7684\u5355\u8bcd\u90fd\u53ea\u7531\u5c0f\u5199\u5b57\u6bcd\u7ec4\u6210\u3002
    • \n
    \n*/\n\n\n/**\n * @param {string} S\n * @param {string[]} words\n * @return {number}\n */\nvar expressiveWords = function(S, words) {\n \n};"} {"doc_id": "26e29aac0ca218db041d48b0cc22ba3a", "text": "/**\n * String\u4e5f\u662f\u4e00\u4e2a\u7c7b\u6570\u7ec4\u5bf9\u8c61\n * \n * \u7531\u4e8e\u5b57\u7b26\u4e32\u5bf9\u8c61\u4e5f\u5b58\u5728length\uff0c\u4e14\u5e8f\u53f7\u4ece0\u5f00\u59cb\u589e\u52a0\uff0c\u56e0\u6b64\u5b57\u7b26\u4e32\u4e5f\u53ef\u4ee5\u770b\u505a\u4e00\u4e2a\u53ea\u8bfb\u7684\u7c7b\u6570\u7ec4\u5bf9\u8c61\uff0c\u8fd9\u610f\u5473\u7740String\u5bf9\u8c61\u53ef\u4ee5\u4f7f\u7528Array\u7684\u6240\u6709\u539f\u578b\u65b9\u6cd5\u3002\n */\n\nlet str1 = 'hello world'\nconsole.log(Array.prototype.slice.call(str1, 0, 5)) // [\"h\", \"e\", \"l\", \"l\", \"o\"]\n\nconsole.log('--------\u5206\u5272\u7ebf--------')\n\n// String\u4e5f\u53ef\u4ee5\u4f7f\u7528for-of\u8fdb\u884c\u904d\u5386\nlet str2 = 'hello world'\nfor (const s of str2) {\n console.log(s)\n}\n\nconsole.log('--------\u5206\u5272\u7ebf--------')\n\n/**\n * String\u72ec\u6709\u65b9\u6cd5\n * \n * \u9664\u4e86\u4f7f\u7528Array\u539f\u578b\u5bf9\u8c61\u7684\u65b9\u6cd5\uff0cString\u8fd8\u5305\u542b\u5176\u4ed6\u4e00\u4e9b\u81ea\u5df1\u72ec\u6709\u7684\u65b9\u6cd5:\n * \n * \u4e0eArray\u4f7f\u7528\u65b9\u6cd5\u76f8\u540c\u7684\u65b9\u6cd5\n * \n * \u641c\u7d22: indexOf()\u3001lastIndexOf()\u3001concat()\n * \n * \u8f6c\u6362\n * toLowerCase()\u3001toUpperCase()\n * \n * \u622a\u53d6\n * substr(start, len)\n * substring(start, end)\n * slice(start, end)\n*/\n\nlet str3 = 'hello world'\nlet ret31 = str3.substr(6, 5) // \"world\"\nconsole.log(ret31)\n\nlet ret32 = str3.substring(6, 11) // \"world\"\nconsole.log(ret32)\n\nlet ret33 = str3.slice(3, 8) // \"lo wo\"\nconsole.log(ret33)\n\nconsole.log('--------\u5206\u5272\u7ebf--------')\n\n// substring \u662f\u4ee5\u4e24\u4e2a\u53c2\u6570\u4e2d\u8f83\u5c0f\u4e00\u4e2a\u4f5c\u4e3a\u8d77\u59cb\u4f4d\u7f6e\uff0c\u8f83\u5927\u7684\u53c2\u6570\u4f5c\u4e3a\u7ed3\u675f\u4f4d\u7f6e\u3002\n// slice \u662f\u7b2c\u4e00\u53c2\u6570\u4e3a\u8d77\u59cb\u4f4d\u7f6e\uff0c\u7b2c\u4e8c\u53c2\u6570\u4e3a\u7ed3\u675f\u4f4d\u7f6e\uff0c\u5982\u679c\u7ed3\u675f\u4f4d\u7f6e\u5c0f\u4e8e\u8d77\u59cb\u4f4d\u7f6e\u8fd4\u56de\u7a7a\u5b57\u7b26\u4e32\nconsole.log(str3.substring(11, 6) === str3.substring(6, 11)) // true\n\nconsole.log('--------\u5206\u5272\u7ebf--------')\n\n/**\n * \u63a5\u6536\u8d1f\u6570\u4e3a\u53c2\u6570\u65f6:\n * \n * slice\u4f1a\u5c06\u5b83\u5b57\u7b26\u4e32\u7684\u957f\u5ea6\u4e0e\u5bf9\u5e94\u7684\u8d1f\u6570\u76f8\u52a0\uff0c\u7ed3\u679c\u4f5c\u4e3a\u53c2\u6570\uff1b\n * substr\u5219\u4ec5\u4ec5\u662f\u5c06\u7b2c\u4e00\u4e2a\u53c2\u6570\u4e0e\u5b57\u7b26\u4e32\u957f\u5ea6\u76f8\u52a0\u540e\u7684\u7ed3\u679c\u4f5c\u4e3a\u7b2c\u4e00\u4e2a\u53c2\u6570\uff1b\n * substring\u5219\u5e72\u8106\u5c06\u8d1f\u53c2\u6570\u90fd\u76f4\u63a5\u8f6c\u6362\u4e3a0\u3002\n */\nlet str4 = 'hello world'\nlet ret41 = str4.substr(-5) // \"world\"\nlet ret42 = str4.substr(-5, 3) // \"wor\"\nlet ret43 = str4.substring(6, -1) // \"hello\"\nlet ret44 = str4.slice(6, -1) // \"worl\"\n\nconsole.log(ret41 === str4.substr(str4.length - 5)) // true\nconsole.log(ret42 === str4.substr(str4.length - 5, 3)) // true\nconsole.log(ret43 === str4.substring(6, 0)) // true\nconsole.log(ret44 === str4.slice(6, str4.length - 1)) // true\n\nconsole.log('--------\u5206\u5272\u7ebf--------')\n\n/**\n * \u6b63\u5219\n *\n * match()\n * replace()\n * search()\n */\nlet str5 = 'hello world'\nlet ret0 = str5.match(/r/) // \u975e\u5168\u5c40\u641c\u7d22\uff0c\u8fd4\u56de\u5339\u914d\u7684\u7b2c\u4e00\u4e2a\u5b57\u7b26\u4e32\u6570\u7ec4(length\u4e3a1)\uff0c\u5305\u62ecindex\u548cinput\nlet ret1 = str5.match(/o/g) // \u5168\u5c40\u641c\u7d22\uff0c\u8fd4\u56de\u5339\u914d\u7684\u5b57\u7b26\u4e32\u6570\u7ec4\uff0clength\u4e3a\u641c\u7d22\u5230\u7684\u5339\u914d\u6b63\u5219\u8868\u8fbe\u5f0f\u7684\u957f\u5ea6\nlet ret2 = str5.replace(/o/g, 'e') // \u5168\u5c40\u66ff\u6362\nlet ret3 = str5.replace(/O/i, 'e') // \u4e0d\u533a\u5206\u5927\u5c0f\u5199\uff0c\u53ea\u66ff\u6362\u641c\u7d22\u5230\u7684\u7b2c\u4e00\u4e2a\u5b57\u4e32\nlet ret4 = str5.search(/l/) // \u8fd4\u56de\u641c\u7d22\u5230\u7684\u7b2c\u4e00\u4e2a\u5339\u914d\u5b57\u4e32\u7684\u7d22\u5f15\nlet ret5 = str5.search(/l/g) // \u5168\u5c40\u65e0\u6548\uff0c\u540c\u4e0a\n\nconsole.log(ret0) // [\"r\", index: 8, input: \"hello world\"]\nconsole.log(ret1) // [\"o\", \"o\"]\nconsole.log(ret2) // \"helle werld\"\nconsole.log(ret3) // \"helle world\"\nconsole.log(ret4) // 2\nconsole.log(ret5) // 2\nconsole.log(str5) // \u4e0d\u6539\u53d8\u6e90\u5b57\u7b26\u4e32 'hello world'\n"} {"doc_id": "2755d3859dfc763e309e4f6f6c879f6f", "text": "// Summary\n//\n// In this challenge you want to create a simple guessing game. Think in terms of when you were 7 and asked your friends to identify the number you were thinking...\n//\n// Your GuessingGame class should be initialized with an integer called answer.\n//\n// Define an instance method GuessingGame#guess which takes an integer called guess as its input. guess should return the symbol :high if the guess is larger than the answer, :correct if the guess is equal to the answer, and :low if theguess is lower than the answer.\n//\n// Define an instance method GuessingGame#solved? which returns true if the most recent guess was correct and false otherwise.\n//\n// In this case, we're asking you to use symbols for :low, :high, and :correct. This is partly due to the way strings and symbols are stored in memory.\n\n\n\n// pseudocode\n\n// create a variable to hold the answer\n// set the variable to some random number\n//\n// ask the user to supply guess\n//\n// while the user guess is not equal to the answer\n//\n// if users guess is higher than the answer\n// tell the user too high\n// else if the user guess is lower than the answer\n// tell the user too low\n// else\n// tell the user they are correct\n//\n\n// var answer = Math.floor(Math.random() * 1000)\n//\n// // Until the user supplies a number, keep asking to supply a number\n// while (isNaN(userGuess)) {\n// var userGuess = parseInt(prompt(\"Guess a number: \"));\n// }\n//\n// // until the user guesses correctly, take more guesses and give hints\n// while (userGuess != answer) {\n// if (userGuess > answer) {\n// while (isNaN(userGuess)) {\n// userGuess = parseInt(prompt(\"Too high. Guess again: \"));\n// }\n// } else if (userGuess < answer) {\n// while (isNaN(userGuess)) {\n// userGuess = parseInt(prompt(\"Too low. Guess again: \"));\n// }\n// }\n// }\n//\n// // when the user guesses correctly, tell them they are right\n// alert(\"You are correct. The answer was \" + answer);\n\n\n// refactor\n\n// Set answer to some random number between 1 and 1000\nvar answer = Math.floor(Math.random() * 1000);\nvar userGuess;\n\nvar getUserGuess = function(message = \"Guess a number: \") {\n userGuess = parseInt(prompt(message));\n while (isNaN(userGuess)) {\n getUserGuess();\n }\n}\n\ngetUserGuess();\n\n// until the user guesses correctly, take more guesses and give hints\nwhile (userGuess != answer) {\n if (userGuess > answer) {\n getUserGuess(\"Too high. Guess again: \");\n } else {\n getUserGuess(\"Too low. Guess again: \");\n }\n}\n\n// when the user guesses correctly, tell them they are right\nalert(\"You are correct. The answer was \" + answer);\n\n\n///////////////////////////////////////////\n\n// Reflection\n\n// What concepts did you solidify in working on this challenge?\n\n// I solidified the concepts of loops, if/else statements, recursion, and variable assignment.\n\n// What was the most difficult part of this challenge?\n\n// The most dificult part of the assignment was keep track of what a variable was assigned at any given time through the execution of the program.\n\n// Did you solve the problem in a new way this time?\n\n// The program is running automatically in the browser this time, vs running manually in a ruby console. They really arent solving the same problem. They were solved differently as they were in different environments. However, they did include similar elements, such a an if/else statment.\n\n// Was your pseudocode different from the Ruby version? What was the same and what was different?\n\n// The pseudocode was most definitly different than with the solution in ruby. These solutions were in different environments, so they involved different solutions. They involved some similarities.\n"} {"doc_id": "277b4965ad8ca2ac5c8b2f42292a7bf5", "text": "// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class\n// http://www.2ality.com/2015/02/es6-classes-final.html\n\n'use strict';\n\n// Use 'class' to define a new class\nclass Person {\n\tconstructor(name) {\n\t\tthis.name = name;\n\t\tthis._id = name.toLowerCase();\n\t}\n\n\t// read only property, note that the setter is missing\n\tget id() {\n\t\treturn this._id;\n\t}\n\n\t// Example: getter and setters\n\tset password(password) {\n\t\t// store 'encrypted' password\n\t\tthis.encryptedPassword = password.split('').reverse().join('');\n\t}\n\n\tget password() {\n\t\t// return 'decrypted' password\n\t\treturn this.encryptedPassword.split('').reverse().join('');\n\t}\n\n\ttoString() {\n\t\treturn `I'm ${this.name}`;\n\t}\n}\n\n// create new instance of that class\nconst lemmy = new Person('Lemmy');\n\n// Access it's memebers\nconsole.log(lemmy.toString()); // I'm Lemmy\nconsole.log(lemmy.id); // 'lemmy'\n\n// Try getting a read-only property\ntry {\n\t// Won't work, as id is a read-only property\n\tlemmy.id = 'kilmister';\n} catch (e) {\n\t// ERROR: TypeError: Cannot set property id of [object Object] which has only a getter\n\tconsole.log(e);\n}\n\nlemmy.password = 'aceOfSpades';\nconsole.log(lemmy.password); // aceOfSpades\nconsole.log(lemmy.encryptedPassword); //sedapSfOeca\n\n// You can easily create subclasses using the `extends` keyword:\nclass Musician extends Person {\n\tconstructor(name, instrument) {\n\t\t// invoke super constructor first\n\t\tsuper(name);\n\t\tthis.instrument = instrument;\n\t}\n\n\ttoString() {\n\t\treturn `${super.toString()} and I'm playing ${this.instrument}`;\n\t}\n\n\t// You can define static methods\n\tstatic newGuitarPlayer(name) {\n\t\treturn new Musician(name, 'Guitar');\n\t}\n}\n\nconst mikkey = new Musician('Mikkey', 'Drums');\nconsole.log(mikkey.toString()); // I'm Mikkey and I'm playing Drums\nconsole.log((mikkey instanceof Person)); // true\nconsole.log((mikkey instanceof Musician)); // true\nconsole.log(Musician.newGuitarPlayer('Phil').toString()); // I'm Phil and I'm playing Guitar\n\n// And like in the enhanced object literal you can even use computed property names using the square bracket notation:\nfunction secretKey() {\n\treturn 667;\n}\n\nclass NeighbourHood {\n\t[ 'no_' + secretKey() ]() {\n\t\treturn 'Neighbour of the beast';\n\t}\n}\n\nconst hood = new NeighbourHood();\nconsole.log(hood.no_667()); // Neighbour of the beast\n\n// also possible: class as expression\nconst Programmer = class extends Person {\n\tconstructor(name, language) {\n\t\tsuper(name);\n\t\tthis.language = language;\n\t}\n\n\tcode() {\n\t\treturn `${this.name} codes in ${this.language}`;\n\t}\n};\n\nconst olli = new Programmer('Olli', 'JavaScript');\nconsole.log(olli.code());"} {"doc_id": "281045ea02f0f33051503e46ec9a068a", "text": "var firstValue = parseInt(prompt('Digite o primeiro valor: '))\nvar secondValue = parseInt(prompt(\"Digite o segundo valor: \"))\n\nvar escolhaOperacao = parseInt(prompt('Escolha uma op\u00e7\u00e3o: 1 - para efetuar divis\u00e3o, 2 - para efetuar multiplica\u00e7\u00e3o, 3 - para efetuar soma e 4 - para efetuar subtra\u00e7\u00e3o'))\n\nif(escolhaOperacao == 1){\n var finalValue = firstValue / secondValue\n document.write(\"

    \" + firstValue + \" / \" + secondValue + \" = \" + finalValue + \"

    \")\n}else if(escolhaOperacao == 2){\n var finalValue = firstValue * secondValue\n document.write(\"

    \" + firstValue + \" * \" + secondValue + \" = \" + finalValue + \"

    \")\n}else if(escolhaOperacao == 3){\n var finalValue = firstValue + secondValue\n document.write(\"

    \" + firstValue + \" + \" + secondValue + \" = \" + finalValue + \"

    \")\n}else if(escolhaOperacao == 4){\n var finalValue = firstValue - secondValue\n document.write(\"

    \" + firstValue + \" - \" + secondValue + \" = \" + finalValue + \"

    \")\n}else{\n document.write(\"

    Op\u00e7\u00e3o inv\u00e1lida!

    \") \n}\n\n\n// document.write() escreve na tela/no documento HTML\n// if - se\n// else if - sen\u00e3o se\n// else - sen\u00e3o\n// operador + al\u00e9m de somar, tem a fun\u00e7\u00e3o de concatena\u00e7\u00e3o\n// 01 sinal de igual > significa atribuir (var exemploValor = 10)\n// 02 sinais de igual > opera\u00e7\u00e3o de igualdade (if(1 == 1){})"} {"doc_id": "28f9f5936625bb568cd121f19ea7d0ef", "text": "/**\r\n * 1.\u7406\u89e3\u56fe 7-1\r\n * 2.\u53c2\u8003 p181 \u5229\u7528\u95ed\u5305\u548c\u5faa\u73af\u751f\u6210\u4e00\u4e2a\u6570\u7ec4\uff0c\u6570\u7ec4\u7684\u6bcf\u4e00\u9879\u90fd\u662f\u4e00\u4e2a\u51fd\u6570\uff0c\u8be5\u51fd\u6570\u6267\u884c\u7ed3\u679c\u8fd4\u56de\u6570\u7ec4\u4e0b\u6807\u5bf9\u5e94\u7684\u5b57\u7b26\u4e32\r\n * arr[0]() \u8fd4\u56de '0'\uff0carr[1]() \u8fd4\u56de '1'\r\n * 3.\u7ed3\u5408\u524d\u9762\u7ae0\u8282 4.3 \u5783\u573e\u56de\u6536\u7406\u89e3\u5185\u5b58\u6cc4\u6f0f\r\n * 4.\u7ed3\u5408\u95ed\u5305\u521b\u5efa\u4e00\u4e2a\u6784\u9020\u51fd\u6570 Glj\uff0c\u62e5\u6709\u4e00\u4e2a \u79c1\u6709\u53d8\u91cf secret\uff0c\u62e5\u6709\u4e00\u4e2a\u51fd\u6570 seeSecret\uff0c\u51fd\u6570\u8fd4\u56de secret \u7684\u503c\r\n * \u5b9e\u4f8b\u5316\u4e00\u4e2a Glj\uff0c\u5c1d\u8bd5\u8c03\u7528 secret \u5c5e\u6027\uff0c\u518d\u8c03\u7528 seeSecret\uff0c\u7406\u89e3\u5176\u4e2d\u4f5c\u7528\r\n * 5.\u7406\u89e3\u5355\u4f8b\u6a21\u5f0f\uff0c\u5e76\u7ed3\u5408\u95ed\u5305\u521b\u5efa\u4e00\u4e2a\u51fd\u6570 getGlj\uff0c\u6709\u4e00\u4e2a\u79c1\u6709\u53d8\u91cf glj\uff0c\u5f53 glj \u672a\u5b9a\u4e49\u65f6\u5b9e\u4f8b\u5316\u4e00\u4e2a Glj \u5e76\u8d4b\u503c\u7ed9 glj\uff0c\r\n * \u5f53 glj \u5df2\u7ecf\u5b9a\u4e49\u65f6\u8fd4\u56de glj\r\n */\r\n\r\nfunction createArray(num) {\r\n\r\n const result = new Array();\r\n\r\n for (var i = 0; i <= num; i++) {\r\n\r\n result[i] = function (num1) {\r\n return function () {\r\n return num1;\r\n }\r\n }(i);\r\n }\r\n\r\n return result;\r\n}\r\nconst arr = createArray(10);\r\nconsole.log(arr[0](), arr[1]());\r\n\r\nfunction Glj() {\r\n const secret = 'glj is lolikon';\r\n this.seeSecret = function () {\r\n return secret;\r\n }\r\n}\r\nconst glj = new Glj();\r\nconsole.log(glj.seeSecret());\r\n\r\nconst getGlj = (function () {\r\n let glj;\r\n\r\n return function () {\r\n if (!glj) {\r\n glj = new Glj();\r\n }\r\n \r\n return glj;\r\n }\r\n})();\r\n"} {"doc_id": "293f48f55dea173cabafa0de170b6d15", "text": "// \u0418\u043c\u043f\u0435\u0440\u0430\u0442\u0438\u0432\u043d\u044b\u0439 \u043a\u043e\u0434 - \u043d\u0430\u0431\u043e\u0440 \u043f\u043e\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u043d\u044b\u0445 \u0438\u043d\u0441\u0442\u0440\u0443\u043a\u0446\u0438\u0439, \u043e\u0431\u044a\u044f\u0432\u043b\u0435\u043d\u0438\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0439\n// \u0414\u0435\u043a\u043b\u0430\u0440\u0430\u0442\u0438\u0432\u043d\u044b\u0439 \u043a\u043e\u0434 - \u0432\u044b\u0437\u043e\u0432 \u0444\u0443\u043d\u043a\u0446\u0438\u0439\n\n// =============================\nconst arr = [1, 2, 3, 4, 5]\n// \u0427\u0438\u0441\u0442\u044b\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 - \u043d\u0435 \u043c\u0443\u0442\u0438\u0440\u0443\u044e\u0442 \u0433\u043b\u043e\u0431\u0430\u043b\u044c\u043d\u044b\u0435 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0435\n\n// \u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e, \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u044e\u0449\u0443\u044e \u043c\u0430\u0441\u0441\u0438\u0432, \u0445\u0440\u0430\u043d\u044f\u0449\u0438\u0439\u0441\u044f \u0432 \u0433\u043b\u043e\u0431\u0430\u043b\u044c\u043d\u043e\u0439\n// \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439 \u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435,\n// \u0441 \u043a\u043e\u0442\u043e\u0440\u044b\u043c \u044d\u0442\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0431\u0443\u0434\u0435\u0442 \u0438\u0437\u043c\u0435\u043d\u044f\u0442\u044c \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432\n\n// \u0412 \u043b\u043e\u0433\u0438\u043a\u0435 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u043e\u0431\u044a\u044f\u0432\u0438\u043c \u043b\u043e\u043a\u0430\u043b\u044c\u043d\u0443\u044e \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e, \u0432 \u043a\u043e\u0442\u043e\u0440\u0443\u044e \u0437\u0430\u043f\u0438\u0448\u0435\u043c\n// \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439 \u043d\u0430\u0434 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u043c \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u043c\n// \u0420\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u043e\u043c \u0432\u044b\u0437\u043e\u0432\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u0432\u0435\u0440\u043d\u0435\u043c \u043b\u043e\u043a\u0430\u043b\u044c\u043d\u0443\u044e \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u0443\u044e\nfunction pureFunc(array, value) {\n const resultArray = []\n for (let i = 0; i < array.length; i++) {\n // console.log(array[i])\n let result = array[i] * value\n // console.log('result', result)\n resultArray.push(result)\n }\n return resultArray\n}\n// console.log('\u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 \u0447\u0438\u0441\u0442\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438', pureFunc(arr, 2))\n// console.log('\u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432', arr)\n\n// \u0422\u0430\u043a\u043e\u0439 \u043f\u043e\u0434\u0445\u043e\u0434 \u0441\u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044f \u0425\u041e\u0420\u041e\u0428\u0415\u0419 \u041f\u0440\u0430\u043a\u0442\u0438\u043a\u043e\u0439 \u0438 \u0434\u043e\u043b\u0436\u0435\u043d \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f \u043f\u043e\u0432\u0441\u0435\u043c\u0435\u0441\u0442\u043d\u043e\n\n// =============================\n\n// \u0424\u0443\u043d\u043a\u0446\u0438\u0438 \u0441 \u043f\u043e\u0431\u043e\u0447\u043d\u044b\u043c \u044d\u0444\u0444\u0435\u043a\u0442\u043e\u043c - \u043c\u0443\u0442\u0438\u0440\u0443\u044e\u0442\n\n// \u0421\u043e\u0437\u0434\u0430\u0434\u0438\u043c \u0444\u0443\u043d\u043a\u0446\u0438\u044e, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u0442 \u043c\u0430\u0441\u0441\u0438\u0432, \u0445\u0440\u0430\u043d\u044f\u0449\u0438\u0439\u0441\u044f \u0432 \u0433\u043b\u043e\u0431\u0430\u043b\u044c\u043d\u043e\u0439 \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439 \u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435,\n// \u0441 \u043a\u043e\u0442\u043e\u0440\u044b\u043c \u044d\u0442\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0431\u0443\u0434\u0435\u0442 \u0438\u0437\u043c\u0435\u043d\u044f\u0442\u044c \u043f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432\nfunction dirtyFunc(array, value) {\n //\n for (let i = 0; i < array.length; i++) {\n // console.log(array[i])\n array[i] = array[i] * value\n }\n return array\n}\n// \u041f\u0440\u0438 \u0432\u044b\u0437\u043e\u0432\u0435 \u0442\u0430\u043a\u043e\u0439 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 \u0438 \u043f\u0435\u0440\u0435\u0434\u0430\u0447\u0435 \u0435\u0439 \u0430\u0440\u0433\u0443\u043c\u0435\u043d\u0442\u043e\u0432, \u043f\u043e\u043b\u0443\u0447\u0438\u043c \u043c\u0443\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0439 (\u0438\u0437\u043c\u0435\u043d\u0435\u043d\u043d\u044b\u0439)\n// \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432 - \u0447\u0430\u0449\u0435 \u044d\u0442\u043e \u041f\u041b\u041e\u0425\u041e, \u043d\u0435\u0436\u0435\u043b\u0438 \u0445\u043e\u0440\u043e\u0448\u043e\n// console.log('\u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442 dirty \u0444\u0443\u043d\u043a\u0446\u0438\u0438', dirtyFunc(arr, 5))\n// console.log('\u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432', arr)\n\n// =============================\n\n// \u041f\u0435\u0440\u0435\u0431\u0438\u0440\u0430\u044e\u0449\u0438\u0435 (\u0444\u0443\u043d\u043a\u0446\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u044b\u0435) \u043c\u0435\u0442\u043e\u0434\u044b \u043c\u0430\u0441\u0441\u0438\u0432\u0430\n\n// array.metod((elem, idx, arr)=>{ return result})\n// array.metod((elem, idx, arr)=> result)\nconsole.log('\u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0439 \u043c\u0430\u0441\u0441\u0438\u0432', arr)\n// array.forEach((elem)=>{}) // => \u043d\u0438\u0447\u0435\u0433\u043e, \u043f\u0440\u043e\u0441\u0442\u043e \u043f\u0435\u0440\u0435\u0431\u0435\u0440\u0435\u0442 \u043c\u0430\u0441\u0441\u0438\u0432, \u043a\u0430\u043a for...of\nconst forEachArray = []\nconst result = arr.forEach((elem, idx, arr) => {\n // console.log(elem, idx, arr)\n forEachArray.push(elem * 2)\n // return elem - \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442\n})\n// console.log(result)\n// console.log(forEachArray)\nconst students = [\n { name: 'Ira', age: 17 },\n { name: 'Anna', age: 22 },\n { name: 'Andrii', age: 31 },\n { name: 'Ivan', age: 28 },\n]\n// array.map((elem)=>{}) // => \u043c\u0430\u0441\u0441\u0438\u0432 \u0442\u043e\u0439 \u0436\u0435 \u0434\u043b\u0438\u043d\u044b, \u0447\u0442\u043e \u0438 \u0438\u0441\u0445\u043e\u0434\u043d\u044b\u0439\nconst studentsAges = students.map((elem) => {\n // console.log(elem)\n return elem.age + 1\n})\n// console.log(studentsAges)\n// console.log(students);\n\n// array.filter((elem)=>{}) // => \u043c\u0430\u0441\u0441\u0438\u0432 \u043e\u0442\u0444\u0438\u043b\u044c\u0442\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0445 \u044d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432, \u0434\u0430\u0436\u0435, \u0435\u0441\u043b\u0438 \u043e\u043d \u043e\u0434\u0438\u043d \u0438\u043b\u0438 \u043f\u0440\u043e\u0441\u0442\u043e \u043f\u0443\u0441\u0442\u043e\u0439\nconst studentsTo18 = students.filter((elem) => {\n return elem.age < 18\n})\n// console.log(studentsTo18)\n\nconst studentsBy18 = students.filter((elem) => {\n return elem.age >= 18\n})\n// console.log(studentsBy18)\n\nconst studentsBy50 = students.filter((elem) => {\n return elem.age >= 50\n})\n// console.log(studentsBy50)\n\n// \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0438 \u043c\u0430\u0441\u0441\u0438\u0432\u043e\u0432\nfunction arraysCheck(arr, age) {\n // const result = arr.filter((el) => el.age >= age)\n // if (result.length === 0) {\n // return `\u041d\u0438 \u043e\u0434\u0438\u043d \u044d\u043b\u0435\u043c\u0435\u043d\u0442 \u043d\u0435 \u043f\u0440\u043e\u0448\u0435\u043b \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0443!!!`\n // }\n // return result.map((el) => el.name).join(', ')\n\n // \u0447\u0435\u0440\u0435\u0437 \u0446\u0435\u043f\u043e\u0447\u043a\u0443 \u043c\u0435\u0442\u043e\u0434\u043e\u0432\n let res = arr.filter((el) => el.age > age).map((el) => el.name)\n console.log(res)\n if (res.length === 0) return `\u041d\u0438 \u043e\u0434\u0438\u043d \u044d\u043b\u0435\u043c\u0435\u043d\u0442 \u043d\u0435 \u043f\u0440\u043e\u0448\u0435\u043b \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0443!!!`\n}\nconsole.log(arraysCheck(students, 50))\nconsole.log(arraysCheck(students, 18))\n\n// array.find((elem)=>{}) // => \u043f\u0435\u0440\u0432\u044b\u0439 \u044d\u043b\u0435\u043c\u0435\u043d\u0442, \u043f\u0440\u043e\u0448\u0435\u0434\u0448\u0438\u0439 \u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0443, \u043d\u0435 \u043c\u0430\u0441\u0441\u0438\u0432 - \u044d\u043b\u0435\u043c\u0435\u043d\u0442!\nconst To18 = students.find((elem) => {\n return elem.age < 18\n})\n// console.log(To18)\n\nconst By18 = students.find((elem) => {\n return elem.age >= 18\n})\n// console.log(By18)\n\nconst By50 = students.find((elem) => {\n return elem.age >= 50\n})\n// console.log(By50)\n\n// array.reduce((acc, elem)=>{}, []) // => []\n// array.reduce((acc, elem)=>{}, {}) // => {}\n// array.reduce((acc, elem)=>{}, 0) // => number\nlet reduceResult = arr.reduce(\n (acc, elem, idx, arr) => acc + elem / arr.length,\n 0,\n)\n// console.log(reduceResult)\n\nreduceResult = arr.reduce((newArray, number) => {\n newArray.push(number)\n return newArray\n}, [])\n// console.log(reduceResult)\n// console.log(reduceResult === arr)\n// array.reduce((acc, elem)=>{}, \"\") // => string\n\n// array.every((elem)=>{}) // => true, \u0435\u0441\u043b\u0438 \u0432\u0441\u0435 true || false - &&\nlet isEvery = arr.every((elem) => {\n return elem % 2 === 0\n})\n// console.log(isEvery)\n// array.some((elem)=>{}) // => false, \u0435\u0441\u043b\u0438 \u0432\u0441\u0435 false || true - ||\nlet isSome = arr.some((elem) => {\n // return elem % 2 === 0 // true\n return elem > 5 // false\n})\n// console.log(isSome)\n\n// \u0421\u041e\u0420\u0422\u0418\u0420\u041e\u0412\u041a\u0410\n// \u0434\u043b\u044f \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432\nconst names = ['Anna', 'Vitaliy', 'Evheniy', 'Valeriy', 'Vasiliy', 'Marina']\n// array.sort()\n// console.log(names.sort().reverse())\n\n// \u0434\u043b\u044f \u0447\u0438\u0441\u0435\u043b\nconst numbers = [32, 21, 2, 6, 3, 8, 47, 1, 4]\n// console.log(numbers.sort())\n// array.sort((min, max)=>{min - max})\n// console.log(numbers.sort((min, max) => min - max))\n// array.sort((min, max)=>{max - min})\n// console.log(numbers.sort((min, max) => max - min))\n\n// \u0446\u0435\u043f\u043e\u0447\u043a\u0438 \u043c\u0435\u0442\u043e\u0434\u043e\u0432\n// \u0421\u043a\u043e\u043b\u044c\u043a\u043e \u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u043e\u0440\u043e\u0432 \u043e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e \u0434\u043e\u043b\u0436\u043d\u043e \u0431\u044b\u0442\u044c \u0443 \u043a\u043b\u0430\u0441\u0441\u0430?\n"} {"doc_id": "29f5e532de7a35e66d5ea6ef46c85cde", "text": "const botao = document.querySelector('button')\n\nbotao.onclick = () => {\n \nvar valorEmDolar = Number(document.querySelector('input').value.replace(',','.')) \n \ndocument.querySelector('h2').innerHTML = 'R$ '+(valorEmDolar * 5.50).toFixed(2)\n \n}\n\n//var valorEmDolarTexto = prompt(\"Qual o valor em dolar voc\u00ea quer converter?\")\n//var valorEmDolarNumero = parseFloat(valorEmDolarTexto)\n//var valorEmReal = valorEmDolarNumero * 5.50\n//var valorEmRealFixado = valorEmReal.toFixed(2)\n\n//alert(valorEmRealFixado)\n\n// Revis\u00e3o\n// vari\u00e1veis var int - float - string\n// alert - parseInt - parseFloat - prompt\n// opera\u00e7\u00f5es + somar * multiplicar\n// coment\u00e1rio final"} {"doc_id": "29f9502066d52fd9b8c27f6653d9d4ef", "text": "// // push and pop\n// let myArray = [\"Ducati\", \"Harley Davidson\", \"Honda\", \"Yamaha\", \"Suzuki\"];\n// document.getElementById(\"demo\").innerHTML = myArray;\n// //Push()\n// // function myFunction() {\n// // myArray.push(\"Yatri\");\n// // document.getElementById(\"demo\").innerHTML = myArray;\n// // }\n\n// // Pop()\n// function myFunction() {\n// myArray.pop();\n// document.getElementById(\"demo\").innerHTML = myArray;\n// }\n\n\n// Queue()\n\n\n// Splice()\n// let scores = [0,1,2,3,4,5,6,7,8,9];\n// let removeNum = scores.splice(2,7);\n// console.log(scores); // [ 0, 1, 9 ]\n// console.log(removeNum); // [ 2, 3, 4, 5, 6, 7, 8 ]\n\n// // slice()\n// let Laptops = [\"HP\", \"Dell\", \"Mac\", \"ASUS\", \"MSI\", \"ACER\", \"TOSHIBA\", \"MICROSOFT\"];\n// let Brands = Laptops.slice(4,6);\n// console.log(Brands); // [ 'MSI', 'ACER' ]\n\n// indexOf()\n// let numbers = [10, 20, 30, 40, 50, 60, 70, 80];\n// console.log(numbers.indexOf(50)); //4\n\n// lastIndexOf()\n// let numbers = [10, 20, 30, 40, 50, 60, 70, 80];\n// console.log(numbers.lastIndexOf(50)); //4\n\n// // Checking array elements using the for loop\n// let numbers = [1, 3, 5, 7];\n// let result = true;\n// for (let i =0; i< numbers.length; i++){\n// if (numbers[i] <= 0){\n// result = false;\n// break;\n// }\n// }\n// console.log(result); // true\n\n// // every()\n// let myNumbers = [1, 2, 3, 4, 5, 6, 7];\n// let result = myNumbers.every(function(e){\n// return e > 0;\n// });\n// console.log(result); //true\n\n// some()\n// Array without some() method only using for loop\n// let marks = [4, 3, 5, 7, 8, 9, 2, 6];\n\n// let lessThanFive = false;\n\n// for(let index = 0; index < marks.length; index++){\n// if(marks[index] < 5){\n// lessThanFive = true;\n// break;\n// }\n// }\n// console.log(lessThanFive); // true\n\n// // some()\n// let strings = [1, 7, 5, 9, 4, 6, 8, 2, 3];\n// let lessThanFive = strings.some(function(e){\n// return e < 5;\n// });\n// console.log(lessThanFive); //True\n\n\n// // Check if an element exists in the array\n// // The following exists() function uses the some() method to check if a value exists in an array:\n// function exists(value, array){\n// return array.some(e => e===value);\n\n// }\n\n// let marks = [1, 2, 3, 4, 5, 6, 7, 8, 9];\n// console.log(exists(5, marks)); //true\n// console.log(exists(10, marks)); //false\n\n// // sort()\n// let numbers = [0, 1, 3, 5, 7, 9, 2, 4, 6, 8];\n// numbers.sort(function(a,b){\n// if(a > b) return 1;\n// if(a < b) return -1;\n// return 0;\n// });\n// console.log(numbers); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n// filter()\n// let cities = [\n// {name: 'Los Angeles', population: 3792621},\n// {name: 'New York', population: 8175133},\n// {name: 'Chicago', population: 2695598},\n// {name: 'Houston', population: 2099451},\n// {name: 'Philadelphia', population: 1526006}\n// ];\n\n\n// // Without filter method\n// let bigCities = [];\n// for (let i = 0; i < cities.length; i++){\n// if(cities[i].population > 3000000) {\n// bigCities.push(cities[i]);\n// }\n// }\n// console.log(bigCities);\n/*\n { name: 'Los Angeles', population: 3792621 },\n { name: 'New York', population: 8175133 }\n]\n*/\n\n// // With filter method\n\n// let bigCities = cities.filter(function(e){\n// return e.population > 3000000;\n// });\n// console.log(bigCities);\n// /*\n// { name: 'Los Angeles', population: 3792621 },\n// { name: 'New York', population: 8175133 }\n// ]\n// */\n\n// // map()\n// let circles = [\n// 10, 30, 50\n// ];\n\n// function circleArea(radius){\n// return Math.floor(Math.PI * radius * radius);\n// }\n\n// let areas = circles.map(circleArea);\n// console.log(areas); // [ 314, 2827, 7853 ]\n\n// // forEach()\n// let ranks = [\"A\", \"B\", \"C\"];\n// ranks.forEach(function(e){\n// console.log(e)\n// });\n// /*\n// A\n// B\n// C\n// */\n\n// // reduce()\n\n// // sum numbers of array using for loop\n// let numbers = [1, 2, 3, 4, 5, 6, 7];\n// // let sum = 0;\n// // for(let i=0; i{\n// return accumulator + current.qty * current.price;\n// }, 0);\n// console.log(total); // 23500\n\n\n// // reduceRight()\n// let numbers = [1, 3, 5, 7];\n// let sum = numbers.reduceRight(function(accumulator, current){\n// console.log(\"Accumulator: \", accumulator, \"Current:\", current);\n// return accumulator + current;\n// });\n// console.log(\"Total: \", sum);\n\n// /*\n// Accumulator: 7 Current: 5\n// Accumulator: 12 Current: 3\n// Accumulator: 15 Current: 1\n// Total: 16\n// */ \n\n\n// JavaScript Multidimensional Array\nlet activities = [\n [\"Work\", 8],\n [\"Eat\", 1],\n [\"Commute\", 2],\n [\"Play Game\", 1], \n [\"Sleep\", 7]\n];\n\n// console.table(activities);\n\n// // Result\n// /*\n// \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2510\n// \u2502 (index) \u2502 0 \u2502 1 \u2502\n// \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2524\n// \u2502 0 \u2502 'Work' \u2502 8 \u2502\n// \u2502 1 \u2502 'Eat' \u2502 1 \u2502\n// \u2502 2 \u2502 'Commute' \u2502 2 \u2502\n// \u2502 3 \u2502 'Play Game' \u2502 1 \u2502\n// \u2502 4 \u2502 'Sleep' \u2502 7 \u2502\n// */ \n\n// activities.push(['study', 2]);\n// console.log(activities);\n\n// /*\n// [\n// [ 'Work', 8 ],\n// [ 'Eat', 1 ],\n// [ 'Commute', 2 ],\n// [ 'Play Game', 1 ],\n// [ 'Sleep', 7 ],\n// [ 'study', 2 ] // Added new elements here\n// ]\n// */ \n\n// activities.splice(1,0, [\"Promgramming\", 2]);\n// console.table(activities);\n\n// /*\n// \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2510\n// \u2502 (index) \u2502 0 \u2502 1 \u2502\n// \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2524\n// \u2502 0 \u2502 'Work' \u2502 8 \u2502\n// \u2502 1 \u2502 'Promgramming' \u2502 2 \u2502\n// \u2502 2 \u2502 'Eat' \u2502 1 \u2502\n// \u2502 3 \u2502 'Commute' \u2502 2 \u2502\n// \u2502 4 \u2502 'Play Game' \u2502 1 \u2502\n// \u2502 5 \u2502 'Sleep' \u2502 7 \u2502\n// */ \n\n// activities.forEach(activity => {\n// let percentage = ((activity[1]/ 24) * 100).toFixed();\n// activity[2] = percentage + \"%\";\n// });\n\n// console.table(activities);\n\n// /*\n// \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// \u2502 (index) \u2502 0 \u2502 1 \u2502 2 \u2502\n// \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n// \u2502 0 \u2502 'Work' \u2502 8 \u2502 '33%' \u2502\n// \u2502 1 \u2502 'Eat' \u2502 1 \u2502 '4%' \u2502\n// \u2502 2 \u2502 'Commute' \u2502 2 \u2502 '8%' \u2502\n// \u2502 3 \u2502 'Play Game' \u2502 1 \u2502 '4%' \u2502\n// \u2502 4 \u2502 'Sleep' \u2502 7 \u2502 '29%' \u2502\n// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n// */ \n\n\n// activities.pop();\n// console.table(activities);\n// /*\n// \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2510\n// \u2502 (index) \u2502 0 \u2502 1 \u2502\n// \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2524\n// \u2502 0 \u2502 'Work' \u2502 8 \u2502\n// \u2502 1 \u2502 'Eat' \u2502 1 \u2502\n// \u2502 2 \u2502 'Commute' \u2502 2 \u2502\n// \u2502 3 \u2502 'Play Game' \u2502 1 \u2502\n// \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2518\n// */ \n\n// Removing elements from the JavaScript multidimensional array\n\n// activities.forEach((activity) => {\n// activity.pop(2);\n// });\n\n// console.table(activities);\n// /*\n// \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n// \u2502 (index) \u2502 0 \u2502\n// \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n// \u2502 0 \u2502 'Work' \u2502\n// \u2502 1 \u2502 'Eat' \u2502\n// \u2502 2 \u2502 'Commute' \u2502\n// \u2502 3 \u2502 'Play Game' \u2502\n// \u2502 4 \u2502 'Sleep' \u2502\n// */ \n\n// Iterating over elements of the JavaScript multidimensional array\n\n// // loop the outer array\n// for(let i = 0; i < activities.length; i++) {\n// // get the size of the inner array\n// var innerArrayLength = activities[i].length;\n// // loop the inner array\n// for (let j = 0; j < innerArrayLength; j++) {\n// console.log(\"[\" + i + \",\" + j + \"] =\" + activities[i][j]);\n// }\n// }\n\n// /*\n// [0,0] =Work\n// [0,1] =8\n// [1,0] =Eat\n// [1,1] =1\n// [2,0] =Commute\n// [2,1] =2\n// [3,0] =Play Game\n// [3,1] =1\n// [4,0] =Sleep\n// [4,1] =7\n// */ \n\n\n// Use ForEach() method twice in place of inner loop and outer loop\nactivities.forEach((activity) => {\n activity.forEach((data) => {\n console.log(data);\n })\n});\n\n/*\n8\nEat\n1\nCommute\n2\nPlay Game\n1\nSleep\n7\n*/ \n\n\n\n\n\n\n\n\n\n\n\n"} {"doc_id": "2a2ff10b574e498822290813ae53865c", "text": "// --- Directions\n// Write a function that accepts a positive number N.\n// The function should console log a step shape\n// with N levels using the # character. Make sure the\n// step has spaces on the right hand side!\n// --- Examples\n// steps(2)\n// '# '\n// '##'\n// steps(3)\n// '# '\n// '## '\n// '###'\n// steps(4)\n// '# '\n// '## '\n// '### '\n// '####'\n\n/* Using Recursion */\nfunction steps(n, row = 0, stair = '') {\n if (row === n) return\n\n if (stair.length === n) {\n console.log(stair)\n\n return steps(n, row + 1)\n }\n\n if (stair.length <= row) {\n stair += '#'\n } else {\n stair += ' '\n }\n\n steps(n, row, stair)\n}\n\nmodule.exports = steps;\n\n/* Another solution */\n// function steps(n) {\n// for (let row = 0; row < n; row++) {\n// let stair = ''\n\n// for (let column = 0; column < n; column++) {\n// if (column <= row) {\n// stair += '#'\n// } else {\n// stair += ' '\n// }\n// }\n\n// console.log(stair)\n// }\n// }\n\n\n/* Another solution */\n// function steps(n) {\n// for (let i = 1; i <= n; i++) {\n// console.log(characterString('#', i) + characterString(' ', n - i))\n// }\n// }\n\n// function characterString(char, count) {\n// let result = ''\n// let i = 0\n\n// while (i < count) {\n// result += char\n\n// i++\n// }\n\n// return result\n// }\n\n//=========================================\n/* Random recursion exercises\n\n// Print numbers from n to 1\nfunction printNumber(n) {\n if (n === 0) return\n \n console.log(n)\n \n printNumber(n-1)\n}\n\nprintNumber(5)\n\nconsole.log('*****************')\n\n// Print string repeatedly vertically\nfunction repeatString(str, times, counter = 0){\n if (counter === times) {\n return\n }\n \n if (times === 1){\n console.log(str)\n return\n }\n \n console.log(str)\n repeatString(str, times, counter + 1)\n}\n\nrepeatString('a', 5)\n\nconsole.log('##################')\n\n// Print string repeatedly horizontally\nfunction repeatStringHorizontally(str, times, result = '') {\n if (result.length === times) {\n console.log(result)\n \n return\n }\n \n result = result + str\n \n repeatStringHorizontally(str, times, result)\n}\n\nrepeatStringHorizontally('b', 5)\n\n*/\n"} {"doc_id": "2a4d95d5445bb583aff2d07487b94208", "text": "/*\n

    \nIn LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.\n

    \n\n

    You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.

    \n\n

    Example 1:
    \n

    \nInput: [1,4], 2\nOutput: 4\nExplanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. 
    This poisoned status will last 2 seconds until the end of time point 2.
    And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds.
    So you finally need to output 4.\n
    \n

    \n\n\n

    Example 2:
    \n

    \nInput: [1,2], 2\nOutput: 3\nExplanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. 
    This poisoned status will last 2 seconds until the end of time point 2.
    However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status.
    Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3.
    So you finally need to output 3.\n
    \n

    \n\n\n

    Note:
    \n

      \n
    1. You may assume the length of given time series array won't exceed 10000.
    2. \n
    3. You may assume the numbers in the Teemo's attacking time series and his poisoning time duration per attacking are non-negative integers, which won't exceed 10,000,000.
    4. \n
    \n

    \u5728\u300a\u82f1\u96c4\u8054\u76df\u300b\u7684\u4e16\u754c\u4e2d\uff0c\u6709\u4e00\u4e2a\u53eb“\u63d0\u83ab”\u7684\u82f1\u96c4\uff0c\u4ed6\u7684\u653b\u51fb\u53ef\u4ee5\u8ba9\u654c\u65b9\u82f1\u96c4\u827e\u5e0c\uff08\u7f16\u8005\u6ce8\uff1a\u5bd2\u51b0\u5c04\u624b\uff09\u8fdb\u5165\u4e2d\u6bd2\u72b6\u6001\u3002\u73b0\u5728\uff0c\u7ed9\u51fa\u63d0\u83ab\u5bf9\u827e\u5e0c\u7684\u653b\u51fb\u65f6\u95f4\u5e8f\u5217\u548c\u63d0\u83ab\u653b\u51fb\u7684\u4e2d\u6bd2\u6301\u7eed\u65f6\u95f4\uff0c\u4f60\u9700\u8981\u8f93\u51fa\u827e\u5e0c\u7684\u4e2d\u6bd2\u72b6\u6001\u603b\u65f6\u957f\u3002

    \n\n

    \u4f60\u53ef\u4ee5\u8ba4\u4e3a\u63d0\u83ab\u5728\u7ed9\u5b9a\u7684\u65f6\u95f4\u70b9\u8fdb\u884c\u653b\u51fb\uff0c\u5e76\u7acb\u5373\u4f7f\u827e\u5e0c\u5904\u4e8e\u4e2d\u6bd2\u72b6\u6001\u3002

    \n\n

    \u793a\u4f8b1:

    \n\n
    \n\u8f93\u5165: [1,4], 2\n\u8f93\u51fa: 4\n\u539f\u56e0: \u5728\u7b2c1\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u5f00\u59cb\u5bf9\u827e\u5e0c\u8fdb\u884c\u653b\u51fb\u5e76\u4f7f\u5176\u7acb\u5373\u4e2d\u6bd2\u3002\u4e2d\u6bd2\u72b6\u6001\u4f1a\u7ef4\u63012\u79d2\u949f\uff0c\u76f4\u5230\u7b2c2\u79d2\u949f\u7ed3\u675f\u3002\n\u5728\u7b2c4\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u518d\u6b21\u653b\u51fb\u827e\u5e0c\uff0c\u4f7f\u5f97\u827e\u5e0c\u83b7\u5f97\u53e6\u59162\u79d2\u7684\u4e2d\u6bd2\u65f6\u95f4\u3002\n\u6240\u4ee5\u6700\u7ec8\u8f93\u51fa4\u79d2\u3002\n
    \n\n

    \u793a\u4f8b2:

    \n\n
    \n\u8f93\u5165: [1,2], 2\n\u8f93\u51fa: 3\n\u539f\u56e0: \u5728\u7b2c1\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u5f00\u59cb\u5bf9\u827e\u5e0c\u8fdb\u884c\u653b\u51fb\u5e76\u4f7f\u5176\u7acb\u5373\u4e2d\u6bd2\u3002\u4e2d\u6bd2\u72b6\u6001\u4f1a\u7ef4\u63012\u79d2\u949f\uff0c\u76f4\u5230\u7b2c2\u79d2\u949f\u7ed3\u675f\u3002\n\u4f46\u662f\u5728\u7b2c2\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u518d\u6b21\u653b\u51fb\u4e86\u5df2\u7ecf\u5904\u4e8e\u4e2d\u6bd2\u72b6\u6001\u7684\u827e\u5e0c\u3002\n\u7531\u4e8e\u4e2d\u6bd2\u72b6\u6001\u4e0d\u53ef\u53e0\u52a0\uff0c\u63d0\u83ab\u5728\u7b2c2\u79d2\u5f00\u59cb\u65f6\u7684\u8fd9\u6b21\u653b\u51fb\u4f1a\u5728\u7b2c3\u79d2\u949f\u7ed3\u675f\u3002\n\u6240\u4ee5\u6700\u7ec8\u8f93\u51fa3\u3002\n
    \n\n

    \u6ce8\u610f\uff1a

    \n\n
      \n\t
    1. \u4f60\u53ef\u4ee5\u5047\u5b9a\u65f6\u95f4\u5e8f\u5217\u6570\u7ec4\u7684\u603b\u957f\u5ea6\u4e0d\u8d85\u8fc710000\u3002
    2. \n\t
    3. \u4f60\u53ef\u4ee5\u5047\u5b9a\u63d0\u83ab\u653b\u51fb\u65f6\u95f4\u5e8f\u5217\u4e2d\u7684\u6570\u5b57\u548c\u63d0\u83ab\u653b\u51fb\u7684\u4e2d\u6bd2\u6301\u7eed\u65f6\u95f4\u90fd\u662f\u975e\u8d1f\u6574\u6570\uff0c\u5e76\u4e14\u4e0d\u8d85\u8fc710,000,000\u3002
    4. \n
    \n

    \u5728\u300a\u82f1\u96c4\u8054\u76df\u300b\u7684\u4e16\u754c\u4e2d\uff0c\u6709\u4e00\u4e2a\u53eb“\u63d0\u83ab”\u7684\u82f1\u96c4\uff0c\u4ed6\u7684\u653b\u51fb\u53ef\u4ee5\u8ba9\u654c\u65b9\u82f1\u96c4\u827e\u5e0c\uff08\u7f16\u8005\u6ce8\uff1a\u5bd2\u51b0\u5c04\u624b\uff09\u8fdb\u5165\u4e2d\u6bd2\u72b6\u6001\u3002\u73b0\u5728\uff0c\u7ed9\u51fa\u63d0\u83ab\u5bf9\u827e\u5e0c\u7684\u653b\u51fb\u65f6\u95f4\u5e8f\u5217\u548c\u63d0\u83ab\u653b\u51fb\u7684\u4e2d\u6bd2\u6301\u7eed\u65f6\u95f4\uff0c\u4f60\u9700\u8981\u8f93\u51fa\u827e\u5e0c\u7684\u4e2d\u6bd2\u72b6\u6001\u603b\u65f6\u957f\u3002

    \n\n

    \u4f60\u53ef\u4ee5\u8ba4\u4e3a\u63d0\u83ab\u5728\u7ed9\u5b9a\u7684\u65f6\u95f4\u70b9\u8fdb\u884c\u653b\u51fb\uff0c\u5e76\u7acb\u5373\u4f7f\u827e\u5e0c\u5904\u4e8e\u4e2d\u6bd2\u72b6\u6001\u3002

    \n\n

    \u793a\u4f8b1:

    \n\n
    \n\u8f93\u5165: [1,4], 2\n\u8f93\u51fa: 4\n\u539f\u56e0: \u5728\u7b2c1\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u5f00\u59cb\u5bf9\u827e\u5e0c\u8fdb\u884c\u653b\u51fb\u5e76\u4f7f\u5176\u7acb\u5373\u4e2d\u6bd2\u3002\u4e2d\u6bd2\u72b6\u6001\u4f1a\u7ef4\u63012\u79d2\u949f\uff0c\u76f4\u5230\u7b2c2\u79d2\u949f\u7ed3\u675f\u3002\n\u5728\u7b2c4\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u518d\u6b21\u653b\u51fb\u827e\u5e0c\uff0c\u4f7f\u5f97\u827e\u5e0c\u83b7\u5f97\u53e6\u59162\u79d2\u7684\u4e2d\u6bd2\u65f6\u95f4\u3002\n\u6240\u4ee5\u6700\u7ec8\u8f93\u51fa4\u79d2\u3002\n
    \n\n

    \u793a\u4f8b2:

    \n\n
    \n\u8f93\u5165: [1,2], 2\n\u8f93\u51fa: 3\n\u539f\u56e0: \u5728\u7b2c1\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u5f00\u59cb\u5bf9\u827e\u5e0c\u8fdb\u884c\u653b\u51fb\u5e76\u4f7f\u5176\u7acb\u5373\u4e2d\u6bd2\u3002\u4e2d\u6bd2\u72b6\u6001\u4f1a\u7ef4\u63012\u79d2\u949f\uff0c\u76f4\u5230\u7b2c2\u79d2\u949f\u7ed3\u675f\u3002\n\u4f46\u662f\u5728\u7b2c2\u79d2\u5f00\u59cb\u65f6\uff0c\u63d0\u83ab\u518d\u6b21\u653b\u51fb\u4e86\u5df2\u7ecf\u5904\u4e8e\u4e2d\u6bd2\u72b6\u6001\u7684\u827e\u5e0c\u3002\n\u7531\u4e8e\u4e2d\u6bd2\u72b6\u6001\u4e0d\u53ef\u53e0\u52a0\uff0c\u63d0\u83ab\u5728\u7b2c2\u79d2\u5f00\u59cb\u65f6\u7684\u8fd9\u6b21\u653b\u51fb\u4f1a\u5728\u7b2c3\u79d2\u949f\u7ed3\u675f\u3002\n\u6240\u4ee5\u6700\u7ec8\u8f93\u51fa3\u3002\n
    \n\n

    \u6ce8\u610f\uff1a

    \n\n
      \n\t
    1. \u4f60\u53ef\u4ee5\u5047\u5b9a\u65f6\u95f4\u5e8f\u5217\u6570\u7ec4\u7684\u603b\u957f\u5ea6\u4e0d\u8d85\u8fc710000\u3002
    2. \n\t
    3. \u4f60\u53ef\u4ee5\u5047\u5b9a\u63d0\u83ab\u653b\u51fb\u65f6\u95f4\u5e8f\u5217\u4e2d\u7684\u6570\u5b57\u548c\u63d0\u83ab\u653b\u51fb\u7684\u4e2d\u6bd2\u6301\u7eed\u65f6\u95f4\u90fd\u662f\u975e\u8d1f\u6574\u6570\uff0c\u5e76\u4e14\u4e0d\u8d85\u8fc710,000,000\u3002
    4. \n
    \n*/\n\n\n/**\n * @param {number[]} timeSeries\n * @param {number} duration\n * @return {number}\n */\nvar findPoisonedDuration = function(timeSeries, duration) {\n \n};"} {"doc_id": "2a912784921f1428eb0167aff2a34924", "text": "/*\n

    Given a linked list, remove the n-th node from the end of list and return its head.

    \n\n

    Example:

    \n\n
    \nGiven linked list: 1->2->3->4->5, and n = 2.\n\nAfter removing the second node from the end, the linked list becomes 1->2->3->5.\n
    \n\n

    Note:

    \n\n

    Given n will always be valid.

    \n\n

    Follow up:

    \n\n

    Could you do this in one pass?

    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u94fe\u8868\uff0c\u5220\u9664\u94fe\u8868\u7684\u5012\u6570\u7b2c n \u4e2a\u8282\u70b9\uff0c\u5e76\u4e14\u8fd4\u56de\u94fe\u8868\u7684\u5934\u7ed3\u70b9\u3002

    \n\n

    \u793a\u4f8b\uff1a

    \n\n
    \u7ed9\u5b9a\u4e00\u4e2a\u94fe\u8868: 1->2->3->4->5, \u548c n = 2.\n\n\u5f53\u5220\u9664\u4e86\u5012\u6570\u7b2c\u4e8c\u4e2a\u8282\u70b9\u540e\uff0c\u94fe\u8868\u53d8\u4e3a 1->2->3->5.\n
    \n\n

    \u8bf4\u660e\uff1a

    \n\n

    \u7ed9\u5b9a\u7684 n \u4fdd\u8bc1\u662f\u6709\u6548\u7684\u3002

    \n\n

    \u8fdb\u9636\uff1a

    \n\n

    \u4f60\u80fd\u5c1d\u8bd5\u4f7f\u7528\u4e00\u8d9f\u626b\u63cf\u5b9e\u73b0\u5417\uff1f

    \n

    \u7ed9\u5b9a\u4e00\u4e2a\u94fe\u8868\uff0c\u5220\u9664\u94fe\u8868\u7684\u5012\u6570\u7b2c n \u4e2a\u8282\u70b9\uff0c\u5e76\u4e14\u8fd4\u56de\u94fe\u8868\u7684\u5934\u7ed3\u70b9\u3002

    \n\n

    \u793a\u4f8b\uff1a

    \n\n
    \u7ed9\u5b9a\u4e00\u4e2a\u94fe\u8868: 1->2->3->4->5, \u548c n = 2.\n\n\u5f53\u5220\u9664\u4e86\u5012\u6570\u7b2c\u4e8c\u4e2a\u8282\u70b9\u540e\uff0c\u94fe\u8868\u53d8\u4e3a 1->2->3->5.\n
    \n\n

    \u8bf4\u660e\uff1a

    \n\n

    \u7ed9\u5b9a\u7684 n \u4fdd\u8bc1\u662f\u6709\u6548\u7684\u3002

    \n\n

    \u8fdb\u9636\uff1a

    \n\n

    \u4f60\u80fd\u5c1d\u8bd5\u4f7f\u7528\u4e00\u8d9f\u626b\u63cf\u5b9e\u73b0\u5417\uff1f

    \n*/\n\n\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} n\n * @return {ListNode}\n */\nvar removeNthFromEnd = function(head, n) {\n \n};"} {"doc_id": "2b15f8947c7732527d5d6316cebc3bfc", "text": "\"use strict\";\n\nclass Rectangle {\n set width(w) {\n this._width = w;\n }\n\n get width() {\n return this._width;\n }\n\n set height(h) {\n this._height = h;\n }\n\n get height() {\n return this._height;\n }\n}\n\n// A function that operates on an instance of Rectangle\nfunction f(rectangle) {\n rectangle.width = 5;\n rectangle.height = 4;\n\n // Verify expected result\n if (rectangle.width * rectangle.height !== 20) {\n throw new Error(\"Expected the rectangle's area (width * height) to be 20\");\n }\n}\n\n// A square IS-A rectangle... right?\nclass Square extends Rectangle {\n set width(w) {\n super.width = w;\n\n // Maintain square-ness\n super.height = w;\n }\n\n set height(h) {\n super.height = h;\n\n // Maintain square-ness\n super.width = h;\n }\n}\n\n// But can a rectangle be substituted by a square?\nf(new Square()); // error"} {"doc_id": "2b2f1930b6a3e1599d8075cbcfbbd433", "text": "\"use strict\";\n// String\nvar cadena = \"Alex Ku Dzul\";\n// Number\nvar numero = 2;\n// Boolean\nvar bool = true;\n// Any\nvar cualquiera = \"Permite agregar cualquier cosa, y sobre escribir la variable\";\ncualquiera = 22;\n// Arrays\nvar lenguajes = [\"JS\", \"TS\", \"PHP\", \"PYTHON\"];\nvar years = [2, 2, 3, 4];\n// Multiples tipos de datos \nvar cadenaConNumero = \"Cadena\";\ncadenaConNumero = 22;\nvar letraynumero = \"Alfa numerico \" + 2;\n// let vs var\nvar numero1 = 10;\nvar numero2 = 11;\nif (numero1 == 10) {\n var numero1_1 = 20;\n var numero2_1 = 21;\n console.log(numero1_1, numero2_1);\n}\nconsole.log(numero1, numero2);\nconsole.log(cadena, numero, bool, cualquiera, lenguajes, years, cadenaConNumero, letraynumero);\n"} {"doc_id": "2b467bd8d96b68c61619872442a9fde3", "text": "/*\n

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

    \n\n

    The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

    \n\n

    How many possible unique paths are there?

    \n\n


    \nAbove is a 7 x 3 grid. How many possible unique paths are there?

    \n\n

    Note: m and n will be at most 100.

    \n\n

    Example 1:

    \n\n
    \nInput: m = 3, n = 2\nOutput: 3\nExplanation:\nFrom the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Right -> Down\n2. Right -> Down -> Right\n3. Down -> Right -> Right\n
    \n\n

    Example 2:

    \n\n
    \nInput: m = 7, n = 3\nOutput: 28
    \n

    \u4e00\u4e2a\u673a\u5668\u4eba\u4f4d\u4e8e\u4e00\u4e2a m x n \u7f51\u683c\u7684\u5de6\u4e0a\u89d2 \uff08\u8d77\u59cb\u70b9\u5728\u4e0b\u56fe\u4e2d\u6807\u8bb0\u4e3a“Start” \uff09\u3002

    \n\n

    \u673a\u5668\u4eba\u6bcf\u6b21\u53ea\u80fd\u5411\u4e0b\u6216\u8005\u5411\u53f3\u79fb\u52a8\u4e00\u6b65\u3002\u673a\u5668\u4eba\u8bd5\u56fe\u8fbe\u5230\u7f51\u683c\u7684\u53f3\u4e0b\u89d2\uff08\u5728\u4e0b\u56fe\u4e2d\u6807\u8bb0\u4e3a“Finish”\uff09\u3002

    \n\n

    \u95ee\u603b\u5171\u6709\u591a\u5c11\u6761\u4e0d\u540c\u7684\u8def\u5f84\uff1f

    \n\n

    \n\n

    \u4f8b\u5982\uff0c\u4e0a\u56fe\u662f\u4e00\u4e2a7 x 3 \u7684\u7f51\u683c\u3002\u6709\u591a\u5c11\u53ef\u80fd\u7684\u8def\u5f84\uff1f

    \n\n

    \u8bf4\u660e\uff1am \u548c n \u7684\u503c\u5747\u4e0d\u8d85\u8fc7 100\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \u8f93\u5165: m = 3, n = 2\n\u8f93\u51fa: 3\n\u89e3\u91ca:\n\u4ece\u5de6\u4e0a\u89d2\u5f00\u59cb\uff0c\u603b\u5171\u6709 3 \u6761\u8def\u5f84\u53ef\u4ee5\u5230\u8fbe\u53f3\u4e0b\u89d2\u3002\n1. \u5411\u53f3 -> \u5411\u53f3 -> \u5411\u4e0b\n2. \u5411\u53f3 -> \u5411\u4e0b -> \u5411\u53f3\n3. \u5411\u4e0b -> \u5411\u53f3 -> \u5411\u53f3\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \u8f93\u5165: m = 7, n = 3\n\u8f93\u51fa: 28
    \n

    \u4e00\u4e2a\u673a\u5668\u4eba\u4f4d\u4e8e\u4e00\u4e2a m x n \u7f51\u683c\u7684\u5de6\u4e0a\u89d2 \uff08\u8d77\u59cb\u70b9\u5728\u4e0b\u56fe\u4e2d\u6807\u8bb0\u4e3a“Start” \uff09\u3002

    \n\n

    \u673a\u5668\u4eba\u6bcf\u6b21\u53ea\u80fd\u5411\u4e0b\u6216\u8005\u5411\u53f3\u79fb\u52a8\u4e00\u6b65\u3002\u673a\u5668\u4eba\u8bd5\u56fe\u8fbe\u5230\u7f51\u683c\u7684\u53f3\u4e0b\u89d2\uff08\u5728\u4e0b\u56fe\u4e2d\u6807\u8bb0\u4e3a“Finish”\uff09\u3002

    \n\n

    \u95ee\u603b\u5171\u6709\u591a\u5c11\u6761\u4e0d\u540c\u7684\u8def\u5f84\uff1f

    \n\n

    \n\n

    \u4f8b\u5982\uff0c\u4e0a\u56fe\u662f\u4e00\u4e2a7 x 3 \u7684\u7f51\u683c\u3002\u6709\u591a\u5c11\u53ef\u80fd\u7684\u8def\u5f84\uff1f

    \n\n

    \u8bf4\u660e\uff1am \u548c n \u7684\u503c\u5747\u4e0d\u8d85\u8fc7 100\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \u8f93\u5165: m = 3, n = 2\n\u8f93\u51fa: 3\n\u89e3\u91ca:\n\u4ece\u5de6\u4e0a\u89d2\u5f00\u59cb\uff0c\u603b\u5171\u6709 3 \u6761\u8def\u5f84\u53ef\u4ee5\u5230\u8fbe\u53f3\u4e0b\u89d2\u3002\n1. \u5411\u53f3 -> \u5411\u53f3 -> \u5411\u4e0b\n2. \u5411\u53f3 -> \u5411\u4e0b -> \u5411\u53f3\n3. \u5411\u4e0b -> \u5411\u53f3 -> \u5411\u53f3\n
    \n\n

    \u793a\u4f8b 2:

    \n\n
    \u8f93\u5165: m = 7, n = 3\n\u8f93\u51fa: 28
    \n*/\n\n\n/**\n * @param {number} m\n * @param {number} n\n * @return {number}\n */\nvar uniquePaths = function(m, n) {\n \n};"} {"doc_id": "2b508f5ba3c17e52d6c04a2c1e3d94cf", "text": "console.log('-------------------------'); \r\nconsole.log('Task 2');\r\n\r\n/*\u0421\u043e\u0437\u0434\u0430\u0439\u0442\u0435 \u043e\u0431\u044a\u0435\u043a\u0442 \u0441 \u0434\u043d\u044f\u043c\u0438 \u043d\u0435\u0434\u0435\u043b\u0438. \u041a\u043b\u044e\u0447\u0430\u043c\u0438 \u0432 \u043d\u0435\u043c \r\n\u0434\u043e\u043b\u0436\u043d\u044b \u0441\u043b\u0443\u0436\u0438\u0442\u044c \u043d\u043e\u043c\u0435\u0440\u0430 \u0434\u043d\u0435\u0439 \u043e\u0442 \u043d\u0430\u0447\u0430\u043b\u0430 \r\n\u043d\u0435\u0434\u0435\u043b\u0438 (\u043f\u043e\u043d\u0435\u0434\u0435\u043b\u044c\u043d\u0438\u043a - \u043f\u0435\u0440\u0432\u044b\u0439 \u0438 \u0442.\u0434.). \r\n\u0412\u044b\u0432\u0435\u0434\u0438\u0442\u0435 \u043d\u0430 \u044d\u043a\u0440\u0430\u043d \u0442\u0435\u043a\u0443\u0449\u0438\u0439 \u0434\u0435\u043d\u044c \u043d\u0435\u0434\u0435\u043b\u0438.*/\r\n\r\nlet number = prompt('\u0412\u0432\u0435\u0434\u0456\u0442\u044c \u043d\u043e\u043c\u0435\u0440 \u0434\u043d\u044f \u0442\u0438\u0436\u043d\u044f \u0447\u0438\u0441\u043b\u043e\u043c');\r\nlet week = {\r\n 1: 'monday',\r\n 2: 'tuesday',\r\n 3: 'wednesday',\r\n 4: 'thursday',\r\n 5: 'friday',\r\n 6: 'saturday',\r\n 7: 'sunday',\r\n}\r\n\r\nwhile(number < 1 || number > 7 || isNaN(number) || number === null) {\r\n if(number === null){\r\n console.log('\u0421\u043a\u0430\u0441\u043e\u0432\u0430\u043d\u043e!');\r\n break;\r\n }\r\n console.log('\u041f\u043e\u043c\u0438\u043b\u043a\u0430. \u0412\u0432\u0435\u0434\u0456\u0442\u044c \u043d\u043e\u043c\u0435\u0440 \u0434\u043d\u044f \u0442\u0438\u0436\u043d\u044f \u0447\u0438\u0441\u043b\u043e\u043c');\r\n number = prompt(\"\u0412\u0432\u0435\u0434\u0456\u0442\u044c \u043d\u043e\u043c\u0435\u0440 \u0434\u043d\u044f \u0442\u0438\u0436\u043d\u044f \u0447\u0438\u0441\u043b\u043e\u043c\");\r\n}\r\n\r\nif(number >= 1 && number <= 7){\r\n number = Math.floor(number);\r\n console.log(week[number]);\r\n}\r\n"} {"doc_id": "2b9ca386c9a3153fc06df40803bc829b", "text": "// Assignment Code\n\n\n//Variables of different letters, numbers, and symbols\nvar lowerCharArr = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\nvar upperCharArr = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"];\nvar numbers = [0,1,2,3,4,5,6,7,8,9];\nvar specialChar = [\"!\", '\"', \"#\", \"$\", \"%\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \"-\", \".\", \"/\", \":\", \";\", \"<\", \"=\", \">\", \"?\", \"@\", \"[\", '\\\\', \"]\", \"^\", \"_\", \"`\", \"{\", \"|\", \"}\", \"~\"];\n\n//Variable for button in document\nvar generateBtn = document.querySelector(\"#generate\");\n\n// Write password to the #password input\nfunction writePassword() {\n var passwordLength = prompt(\"Enter a number of characters between 8 and 128 for the password:\"); \n\n passwordLength = parseInt(passwordLength);\n if (passwordLength >= 8 && passwordLength <= 128) { \n } \n else {\n return alert(\"Invalid response. Please enter a number between 8 and 128 and DO NOT use letters\"); \n }\n//Prompts user to confirm if they want a specific set of characters to use\n var lowerAlpha = confirm(\"Would you want your password to have lowercase letters? (abcdefg....) \\n (OK = Yes) (Cancel = No)\");\n var upperAlpha = confirm(\"Would you want your password to have uppercase letters? (ABCDEFG....) \\n (OK = Yes) (Cancel = No)\");\n var numChar = confirm(\"Would you want your password to have numbers? (1234567890) \\n (OK = Yes) (Cancel = No)\");\n var specialPick = confirm(\"Do you want your password to have special characters? (~!@#$%^....) \\n (OK = Yes) (Cancel = No)\");\n\n//Creates an array for chosen characters called 'userArray' and puts them together\n var userArray = [];\n \n \n if (lowerAlpha === true) {\n userArray = userArray.concat(lowerCharArr);\n }\n if (upperAlpha === true) {\n userArray = userArray.concat(upperCharArr);\n }\n if (numChar === true) {\n userArray = userArray.concat(numbers);\n }\n if (specialPick === true) {\n userArray = userArray.concat(specialChar);\n }\n\n//this function will take the password length and userArray to perform the random math for the password text\n function generatePassword() {\n var passwordText = \"\";\n for (var i = 0; i < passwordLength; i++) {\n passwordText += userArray[Math.floor(Math.random() * userArray.length)];\n }\n return passwordText;\n }\n\n var passwordTextField = document.querySelector(\"#password\");\n\n passwordTextField.value = generatePassword();\n}\n\n// Add event listener for user click to run function to writePassword\ngenerateBtn.addEventListener(\"click\", writePassword);"} {"doc_id": "2bce935933d89d31099053551695b4a9", "text": "/*\n======================\nCounter Char Recursive\n======================\n\n[INSTRUCTION]\ncounterCharRecursive adalah sebuah function recursive yang menerima dua parameter yaitu array dan string.\nfunction ini akan mereturn jumalah char yang sesuai dengan parameter search.\n\n[EXAMPLE]\ninput: ['ada', 'apa', 'ana', 'ada']\nsearch: 'a'\n\nfunction akan mencari jumlah a dalam input\nresult: 8\n\n[RULE]\n1. WAJIB menggunakan metode recursive\n2. HANYA boleh menggunakan SATU looping\n3. dilarang menggunakan indexOf(), find(), filter()\n4. dilarang menggunakan regex\n*/\n\nfunction counterCharRecursive(input, search) {\n // console.log(input);\n if (input.length == 0) {\n return 0;\n }\n\n return finder(input[0], search) + counterCharRecursive(input.slice(1), search);\n\n}\n\n\nfunction finder(elem, a) {\n // console.log(elem);\n if (elem.length == 0) {\n return 0;\n }\n let result = ((elem[0] == a) ? 1 : 0) + finder(elem.slice(1), a);\n // console.log(typeof result);\n return result;\n\n}\n\n\n\n\n\nconsole.log(counterCharRecursive(['ada', 'apa', 'ana', 'ada'], 'a')) // 8\nconsole.log(counterCharRecursive(['xxxxoxoxoxoxoxoxxxooooo'], 'x')) // 12\nconsole.log(counterCharRecursive(['b', 'o', 'l', 'd', 'f', 'o', 'x'], 'l')) // 1\nconsole.log(counterCharRecursive(['terima', 'kasih', 'sudah', 'selalu', 'berjuang'], 's')) // 3```\n\n\n\n// console.log(finder('k0o0ool', 'o'));\n// console.log(finder('ada', 'a'));\n\nconsole.log('=====one recursive function=====');\nfunction counterCharRecursiveOne(input, search) {\n // console.log(input);\n if (input[0].length == 0) {\n // console.log('trimming=>',input);\n input.shift()\n }\n\n if (input.length == 0) {\n return 0;\n }\n let result = 0;\n if (input[0][0] == search) {\n result = 1;\n }\n\n return result + counterCharRecursiveOne([input[0].slice(1)].concat(input.slice(1)), search);\n\n}\n\n\n// function finder(elem, a) {\n// // console.log(elem);\n// if (elem.length == 0) {\n// return 0;\n// }\n// let result = ((elem[0] == a) ? 1 : 0) + finder(elem.slice(1), a);\n// // console.log(typeof result);\n// return result;\n\n// }\n\n\n\n\n\nconsole.log(counterCharRecursiveOne(['ada', 'apa', 'ana', 'ada'], 'a')) // 8\nconsole.log(counterCharRecursiveOne(['xxxxoxoxoxoxoxoxxxooooo'], 'x')) // 12\nconsole.log(counterCharRecursiveOne(['b', 'o', 'l', 'd', 'f', 'o', 'x'], 'l')) // 1\nconsole.log(counterCharRecursiveOne(['terima', 'kasih', 'sudah', 'selalu', 'berjuang'], 's')) // 3```"} {"doc_id": "2d03e66f3419c5c1f16c23af9d5b6058", "text": "/* \n\nStart Date: August 3rd 2020 - 2:30 am\nFinish Date: September 3rd 2021 - 10:02 pm\n\nDescription: \n\nThe sequence of triangle numbers is generated by adding the natural numbers. \nSo the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:\n\n1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n\nLet us list the factors of the first seven triangle numbers:\n\n 1: 1\n 3: 1,3\n 6: 1,2,3,6\n10: 1,2,5,10\n15: 1,3,5,15\n21: 1,3,7,21\n28: 1,2,4,7,14,28\nWe can see that 28 is the first triangle number to have over five divisors.\n\nWhat is the value of the first triangle number to have over five hundred divisors?\n\nNotes:\n8/03/20 - 2:42 am : I wrote a function that will calculate triangle numbers. Need to check divisors when I'm not as tired.\n8/24/21 - 2:38 pm : I'm not as tired anymore. First issue is that I'm calculating every number consecutively for some reason. \nI'm going to just use a formula to find a specific triangle number. \n9/3/21 - 10:02 pm : Nvm I was still tired. Wrote a quick brute localization algorithm. \n*/\n\n\nfunction findTriangleNumber(nth) {\n let tri_num = nth * (nth + 1) / 2;\n return tri_num;\n}\n\nfunction findFactorCount(num) {\n if (num == 0) return 0;\n if (num == 1) return 1;\n\n let upper_bound = num;\n let factor_count = 2; // 1 and itself\n for (let i = 2; i < upper_bound; i++) {\n if (num % i == 0) {\n upper_bound = num / i;\n if (i != num / i) {\n factor_count += 2;\n }\n else {\n factor_count += 1;\n }\n }\n }\n return factor_count;\n}\n\nfunction bruteLocalization(target) {\n let i = 0;\n let solution = 0;\n while (solution == 0) {\n let num = findTriangleNumber(i)\n let current = findFactorCount(num);\n if (current >= target) {\n console.log(`----------------\\nPointer: ${i}\\nFactors: ${current}\\n----------------`);\n solution = num;\n }\n i++;\n }\n return solution;\n}\n\nconsole.log(`Solution: ${bruteLocalization(500)}`);"} {"doc_id": "2e4833b48ce7cf3cf794d93bb6b55988", "text": "\n// Assignment Code\nlet generateBtn = document.querySelector(\"#generate\");\n\n// Write password to the #password input\nfunction writePassword() {\n let password = generatePassword();\n let passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n\n}\n\n//Function to generate password based in user inputs\nfunction generatePassword() {\n\n // prompt user for password length\n let userLength = prompt(\"Enter a password length between 8 and 128.\");\n \n // If not a number between 8 and 128, alert user\n // This works to return the user to the main page, so they have to click Generate Password again.\n if (userLength < 8 || userLength > 128 || isNaN(userLength)) {\n alert(\"Please enter a valid selection for password length. Click Generate Password to try again.\");\n pwString = \"\";\n return;\n };\n\n //prompt user for password characters\n let userLowerCase = confirm(\"Would you like LOWER CASE letters in your password? Click OK for YES and Cancel for NO.\");\n let userUpperCase = confirm(\"Would you like UPPER CASE letters in your password? Click OK for YES and Cancel for NO.\");\n let userNumbers = confirm(\"Would you like NUMBERS in your password? Click OK for YES and Cancel for NO.\");\n let userSymbols = confirm(\"Would you like SYMBOLS in your password? Click OK for YES and Cancel for NO.\");\n\n // Strings for password\n let lowerCase = \"abcdefghijklmnopqrstuvwxyz\";\n let upperCase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n let numbers = \"0123456789\";\n let symbols = \"!*$%&#@+?:;()^\";\n let pwString = \"\";\n\n // Create pwString based on user inputs\n if (userLowerCase) {\n pwString = pwString + lowerCase;\n }\n\n if (userUpperCase) {\n pwString = pwString + upperCase;\n } \n\n if (userNumbers) {\n pwString = pwString + numbers;\n }\n\n if (userSymbols) {\n pwString = pwString + symbols;\n }\n\n // if pwString has no characters, alert the user\n if (pwString === \"\") {\n alert(\"A password requires some characters. Click Generate Password to try again.\");\n pwString = \"\";\n return;\n }\n\n // generate random string from StackOverflow: \n // https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript\n let userPassword = \"\";\n for (let i = 0; i < userLength; i++) {\n userPassword += pwString.charAt(Math.floor(Math.random() * pwString.length));\n }\n\n // console.log(userPassword);\n // userPWPrompt = alert(\"Your password is \" + userPassword);\n return userPassword;\n}\n\n// Add event listener to generate button\ngenerateBtn.addEventListener(\"click\", writePassword);\n\n// Adding copy password button from w3schools: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp\nfunction copyPassword() {\n /* Get the text field */\n var copyText = document.getElementById(\"password\");\n\n /* Select the text field */\n copyText.select();\n copyText.setSelectionRange(0, 99999); /*For mobile devices*/\n\n /* Copy the text inside the text field */\n document.execCommand(\"copy\");\n\n /* Alert the copied text */\n alert(\"Copied the password: \" + copyText.value);\n}\n"} {"doc_id": "2f441cecf09f41e9cdc20bfb6afc6482", "text": "//Log your name\nconsole.log(\"Abdulmalik Yusuf\");\n\n\n/*Activity One (data types)\n=========================\n\n14 === Number\n-80 === Number\n8.5 === Number\ntrue === Boolean\n(5 < 17) === Boolean\nnull === Undefined\n3.142 === Number\n'Pi' === String\n67+18 === Number\n*/\n\n// Code that converts Integers into Binary numbers\nvar convertToBinary = function(number) {\n var quotient = number;\n var remainder = [];\n\n do {\n remainder.push (quotient % 2);\n quotient = Math.floor(quotient / 2);\n console.log(quotient);\n }\n while (quotient >= 1) {\n console.log(remainder.reverse().join(''));\n }\n}\n\nvar x = 20;\nconvertToBinary();\nconsole.log(x.toString(2));\n\n\n//Code to print student grades\nvar printGrade = function(x) {;\n\nif (x >= 70 && x <= 100) {\n console.log(x+' is A');\n} \nelse if (x >= 50 && x < 70) {\n console.log(x+' is B');\n}\nelse if (x >= 0 && x <= 49) {\n console.log(x+' is C');\n}\nelse {\n console.log('Provide numbers between 0 and 100');\n}\n};\n\nprintGrade();\n\n// Activity (2) Code that returns the number of letter \"B\"\nvar countBs = function (string) {\n var x = \"B\";\n var y = 0;\n for (var i = 0; i < (string.length); i++){\n if (string.charAt(i) === x) {\n y++;\n }\n }\n return y;\n};\n\ncountBs();\n\n\n//Activity (3)\nvar countChar =function(string, letter) {\n var letter = letter;\n var y = 0;\n for (var i = 0; i < (string.length); i++) {\n if (string.charAt(i) === letter) {\n y++;\n }\n }\n \n return y;\n};\n\ncountChar();"} {"doc_id": "2f884675ea92aa7a37457b5f41a39de9", "text": "console.group(\"Arrow Functions / Promesas / Par\u00e1metros / Objetos\");\n// OBJETOS / OBJECTS>>>>\n// (A)>\nlet name = \"Luisa\";\nlet age = 30;\n// Antes ==>\nobj = { name: name, age: age };\nconsole.log(obj);\n// ECMA6>>>\nobj2 = { name, age };\nconsole.log(obj2);\n\n// (B)>\n// Arrow Functions >>\nconst names = [\n { name: `Chris`, age: 30 },\n { name: `Luisa`, age: 21 },\n];\n// Antes==>\nlet listOfNames = names.map(function (item, index) {\n console.log(item.name, index);\n});\n// ECMA6>>>\n// Arrow Functions en variables/method>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n//(1)\nlet listOfNamesTwo = names.map((item, index) => console.log(item.name, index));\n\n// (C)> (2)\npeopleTwo = (user) => {\n return user;\n};\n\nconst peopleThree = (name) => {\n return name;\n};\nconsole.log(peopleThree(\"An\u00edbal\"));\n\n// (D)> (3)\nconst listOfNamesFour = (name) => {\n //Code\n};\n\n// (E)> (4)\nconst square = (num) => num * num;\nconsole.log(square(5));\n\n// Promesas / Promise ======================================================================================\n// (1)\nconst hello = () => {\n // Ejecutar Promesa >\n return new Promise((resolve, reject) => {\n //code>\n if (true) {\n resolve(`Hello Resolved`);\n } else {\n reject(`No!!!!!`);\n }\n });\n};\n//EJECUTAR PROMESA=>\nhello()\n .then((response) => console.log(response))\n .catch((error) => console.error(error));\n//> EXERCISE:\nconst friend = (one) => {\n return new Promise((resolve, reject) => {\n if (one === \"Alma\") {\n true;\n resolve(`Yes! I\u00b4ts she!!!`);\n } else {\n reject(`S\u00f3lo es un sue\u00f1o`);\n }\n });\n};\nfriend(\"Alma\")\n .then((response) => console.log(response))\n .catch((error) => console.error(error));\n\nconsole.groupEnd();\n"} {"doc_id": "309351cb44a0b7c92c112e1e033d8202", "text": "class Calculator {\n factor(n) {\n if (n <= 1) {\n return 1;\n } else {\n return this.factor(n - 1) * n;\n }\n }\n}\n\nconsole.log(\"Hello!\");\n\nconst arr = [1, 2, 3];\narr.push(4);\n\nconsole.log(`n = ${arr.length}, arr[0] = ${arr[0]}`);\n\nconst map = {\n a: 2,\n b: 3\n};\nconsole.log(`map['a'] = ${map[\"a\"]}, arr[1] = ${arr[1]}`);\n\nif (arr[0] == 1) {\n console.log(\"TRUE-X\");\n} else {\n console.log(\"FALSE\");\n}\n\nlet sum = 0;\nfor (let i = 0; i < 10; i++) {\n sum += i + 2;\n}\nconsole.log(sum);\n\nconst calc = new Calculator();\nconsole.log(`5! = ${calc.factor(5)}`);"} {"doc_id": "33441382ea29ec6afef3ffb3765e5d8e", "text": "//Problem 7. First larger than neighbours\n//Write a function that returns the index of the first element in array that is larger than its neighbours or -1, if there\ufffds no such element.\n// Use the function from the previous exercise.\n\nvar numbers = [1, 1, 1, 1, 5, 6, 7, 8, 8, 2, 12];\n\nisBiggerThanNeighbours(numbers);\n\nfunction isBiggerThanNeighbours(numbers){\n numbers = numbers || [];\n\n var len = numbers.length,\n position;\n\n for (position = 0; position < len; position += 1) {\n\n if (!(position)) {\n if (numbers[position] > numbers[position + 1]) {\n return console.log('The position of element is: ' + position);\n }\n } else if (position === (len - 1)) {\n if (numbers[position] > numbers[position - 1]) {\n return console.log('The position of element is: ' + position);\n } else {\n return console.log(-1);\n }\n } else {\n if ((numbers[position] > numbers[position - 1]) && (numbers[position] > numbers[position + 1])) {\n return console.log('The position of element is: ' + position);\n }\n }\n }\n}\n\n\n"} {"doc_id": "349a76cf0263f9cce6f50516ea53f367", "text": "var bool1 = true; // true\nvar bool2 = false; // false\nvar bool3 = 1 === 1; // true\nconsole.log(bool1); // prints true\nconsole.log(bool2); // prints false\nconsole.log(bool3); // prints true\nvar bool4 = Boolean(\"true\"); // true\nvar bool5 = Boolean(\"TRUE\"); // true\nvar bool6 = Boolean(\"false\"); // true\nvar bool7 = Boolean(\"FALSE\"); // true\nvar bool8 = Boolean(NaN); // false\nvar bool9 = new Boolean(\"true\").valueOf(); // true\nvar bool10 = new Boolean(\"false\").valueOf(); // true\nvar bool11 = \"true\"; // true\nvar bool12 = \"false\"; // false\nconsole.log(bool4); // prints true \nconsole.log(bool5); // prints false\nconsole.log(bool6); // prints true\nconsole.log(bool7); // prints true\nconsole.log(bool8); // prints false\nconsole.log(bool9); // prints true\nconsole.log(bool10); // prints true\nconsole.log(bool11); // prints true\nconsole.log(bool12); // prints false\nvar bool13 = isTrue(\"true\"); // true\nvar bool14 = isTrue(\"false\"); // false\nfunction isTrue(s) {\n return s.toLocaleLowerCase() === \"true\";\n}\nconsole.log(bool13); // prints true\nconsole.log(bool14); // prints false\n"} {"doc_id": "34babb3d302e22f375f3450ea617d071", "text": "// tyhle prikazy vypisou zpravu do konzole\r\nconsole.log('Ahoj sv\u011bte!');\r\n\r\n/* */\r\nconsole.error('Hele chyba!');\r\nconsole.warn('Upozorneni!');\r\n\r\n\r\n// var, let, const\r\n\r\nlet age = 42;\r\nconsole.log(age);\r\n\r\nconst height = 170;\r\nconsole.log(height);\r\n\r\nage = 12;\r\nconsole.log(age);\r\n\r\n// height = 100;\r\n// console.log(height);\r\n\r\n\r\n// String, Number, Boolean, null, undefined, Symbol\r\n\r\nconst pi = 3.14; // Number - integer, double, float\r\nconst message = 'Ahoj, jmenuji se Pepa a chci se nau\u010dit JavaScript!';\r\n// \"Ahoj, jmenuji se Pepa a chci se nau\u010dit JavaScript!\";\r\n// `Ahoj, jmenuji se Pepa a chci se nau\u010dit JavaScript!`;\r\n\r\nconsole.log(message);\r\n\r\nconst isLive = true;\r\nconst isMarried = false;\r\n\r\nconsole.log(isLive, isMarried);\r\n\r\nconst something = null;\r\nconst somethingElse = undefined;\r\n\r\nconsole.log(something, somethingElse);\r\n\r\nconsole.log(typeof isLive);\r\nconsole.log(typeof message);\r\nconsole.log(typeof pi);\r\n\r\nconsole.log(Symbol('Toto je Symbor, vsichni vidime.'));\r\n\r\n\r\n// Strings / retezce\r\n\r\nconst string1 = 'Ahoj';\r\nconst string2 = 'svete';\r\n// concatenation / zretezeni;\r\nconst string = string1 + ' ' + string2;\r\nconsole.log(string);\r\n\r\nconsole.log('Hodnota PI = ' + pi);\r\n\r\nconst myAge = 28;\r\nconst myName = 'Bachqwecs';\r\nconst str = `Ahoj, jmenuji se ${myName}, a je mi ${myAge} let`;\r\nconsole.log(str);\r\n\r\nconsole.log(myName.length);\r\nconsole.log(myName.toUpperCase());\r\nconsole.log(myName.toLowerCase());\r\n\r\n\r\nconsole.log(myName.slice(0, 2));\r\nconsole.log(myName.slice(1, 3));\r\nconsole.log(myName.split(''));\r\nconsole.log(myName.split('c'));\r\n\r\n\r\n// pole / arrays\r\nconst fruits = ['ananas', 'banana', 'melon', 'strawberry', null, undefined, false];\r\nconsole.log('We have ' + fruits.length + ' fruits');\r\n\r\nconst numbers = [0, 1, 2, 3, 4];\r\nconsole.log(numbers);\r\n\r\nconsole.log(fruits[0]);\r\nconsole.log(fruits[1]);\r\nconsole.log(fruits[2]);\r\n\r\nconsole.log('------------------------------')\r\nfor (let i = 0; i < fruits.length; i++) {\r\n console.log(fruits[i]);\r\n}\r\n\r\nconsole.log('------------------------------')\r\nlet i = 0;\r\nwhile (i < fruits.length) {\r\n console.log(i, fruits[i]);\r\n i++;\r\n}\r\n\r\nfruits.push('orange');\r\nfruits.pop();\r\nconsole.log(fruits);\r\nfruits.shift();\r\nconsole.log(fruits);\r\nfruits.unshift('apple');\r\nconsole.log(fruits);\r\n\r\n\r\n// objects\r\nconst person = {\r\n age: 42,\r\n nationality: 'Czech Republic',\r\n name: 'Pepa',\r\n surname: 'Mach',\r\n};\r\nconsole.log(person.name + ' ' + person.surname);\r\n\r\nconst people = [\r\n {\r\n age: 12,\r\n name: 'David',\r\n },\r\n {\r\n age: 22,\r\n name: 'Jane',\r\n },\r\n {\r\n age: 16,\r\n name: 'Carl',\r\n },\r\n {\r\n age: 72,\r\n name: 'George',\r\n },\r\n];\r\n\r\n\r\nfor (let i = 0; i < people.length; i++) {\r\n console.log(people[i].name + ' ' + people[i].age);\r\n}\r\n\r\n/*people.forEach((person) => {\r\n console.log(person);\r\n});*/\r\n\r\n\r\nconsole.log('-------')\r\nfor (const person of people) {\r\n console.log(person);\r\n}\r\n\r\n// conditionals, if else\r\n\r\nif (isMarried) {\r\n console.log(123);\r\n} else {\r\n console.log(456);\r\n}\r\n\r\nfunction mojeFunkce(a, b) {\r\n return a + b;\r\n}\r\n\r\nconst tvojeFunkce = (a, b) => {\r\n return a + b;\r\n}\r\n\r\n\r\n// functions\r\n// const add = function () {};\r\nconst add = (a, b) => {\r\n // const result = a + b;\r\n // return result;\r\n return a + b;\r\n};\r\n\r\nconsole.log(add(2, 3));\r\n\r\n\r\n"} {"doc_id": "350829d6161560daf02bf61982778472", "text": "/*\n

    \nEquations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.\n

    \n

    Example:
    \nGiven a / b = 2.0, b / c = 3.0.
    queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
    return [6.0, 0.5, -1.0, 1.0, -1.0 ].\n

    \n

    \nThe input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.\n

    \n\n

    According to the example above:\n

    equations = [ [\"a\", \"b\"], [\"b\", \"c\"] ],\nvalues = [2.0, 3.0],\nqueries = [ [\"a\", \"c\"], [\"b\", \"a\"], [\"a\", \"e\"], [\"a\", \"a\"], [\"x\", \"x\"] ]. 
    \n

    \n\n

    \nThe input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.\n

    \u7ed9\u51fa\u65b9\u7a0b\u5f0f A / B = k, \u5176\u4e2d A \u548c B \u5747\u4e3a\u4ee3\u8868\u5b57\u7b26\u4e32\u7684\u53d8\u91cf\uff0c k \u662f\u4e00\u4e2a\u6d6e\u70b9\u578b\u6570\u5b57\u3002\u6839\u636e\u5df2\u77e5\u65b9\u7a0b\u5f0f\u6c42\u89e3\u95ee\u9898\uff0c\u5e76\u8fd4\u56de\u8ba1\u7b97\u7ed3\u679c\u3002\u5982\u679c\u7ed3\u679c\u4e0d\u5b58\u5728\uff0c\u5219\u8fd4\u56de -1.0\u3002

    \n\n

    \u793a\u4f8b :
    \n\u7ed9\u5b9a a / b = 2.0, b / c = 3.0
    \n\u95ee\u9898: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? 
    \n\u8fd4\u56de [6.0, 0.5, -1.0, 1.0, -1.0 ]

    \n\n

    \u8f93\u5165\u4e3a: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries(\u65b9\u7a0b\u5f0f\uff0c\u65b9\u7a0b\u5f0f\u7ed3\u679c\uff0c\u95ee\u9898\u65b9\u7a0b\u5f0f)\uff0c \u5176\u4e2d equations.size() == values.size()\uff0c\u5373\u65b9\u7a0b\u5f0f\u7684\u957f\u5ea6\u4e0e\u65b9\u7a0b\u5f0f\u7ed3\u679c\u957f\u5ea6\u76f8\u7b49\uff08\u7a0b\u5f0f\u4e0e\u7ed3\u679c\u4e00\u4e00\u5bf9\u5e94\uff09\uff0c\u5e76\u4e14\u7ed3\u679c\u503c\u5747\u4e3a\u6b63\u6570\u3002\u4ee5\u4e0a\u4e3a\u65b9\u7a0b\u5f0f\u7684\u63cf\u8ff0\u3002 \u8fd4\u56devector<double>\u7c7b\u578b\u3002

    \n\n

    \u57fa\u4e8e\u4e0a\u8ff0\u4f8b\u5b50\uff0c\u8f93\u5165\u5982\u4e0b\uff1a

    \n\n
    \nequations(\u65b9\u7a0b\u5f0f) = [ ["a", "b"], ["b", "c"] ],\nvalues(\u65b9\u7a0b\u5f0f\u7ed3\u679c) = [2.0, 3.0],\nqueries(\u95ee\u9898\u65b9\u7a0b\u5f0f) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. \n
    \n\n

    \u8f93\u5165\u603b\u662f\u6709\u6548\u7684\u3002\u4f60\u53ef\u4ee5\u5047\u8bbe\u9664\u6cd5\u8fd0\u7b97\u4e2d\u4e0d\u4f1a\u51fa\u73b0\u9664\u6570\u4e3a0\u7684\u60c5\u51b5\uff0c\u4e14\u4e0d\u5b58\u5728\u4efb\u4f55\u77db\u76fe\u7684\u7ed3\u679c\u3002

    \n

    \u7ed9\u51fa\u65b9\u7a0b\u5f0f A / B = k, \u5176\u4e2d A \u548c B \u5747\u4e3a\u4ee3\u8868\u5b57\u7b26\u4e32\u7684\u53d8\u91cf\uff0c k \u662f\u4e00\u4e2a\u6d6e\u70b9\u578b\u6570\u5b57\u3002\u6839\u636e\u5df2\u77e5\u65b9\u7a0b\u5f0f\u6c42\u89e3\u95ee\u9898\uff0c\u5e76\u8fd4\u56de\u8ba1\u7b97\u7ed3\u679c\u3002\u5982\u679c\u7ed3\u679c\u4e0d\u5b58\u5728\uff0c\u5219\u8fd4\u56de -1.0\u3002

    \n\n

    \u793a\u4f8b :
    \n\u7ed9\u5b9a a / b = 2.0, b / c = 3.0
    \n\u95ee\u9898: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? 
    \n\u8fd4\u56de [6.0, 0.5, -1.0, 1.0, -1.0 ]

    \n\n

    \u8f93\u5165\u4e3a: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries(\u65b9\u7a0b\u5f0f\uff0c\u65b9\u7a0b\u5f0f\u7ed3\u679c\uff0c\u95ee\u9898\u65b9\u7a0b\u5f0f)\uff0c \u5176\u4e2d equations.size() == values.size()\uff0c\u5373\u65b9\u7a0b\u5f0f\u7684\u957f\u5ea6\u4e0e\u65b9\u7a0b\u5f0f\u7ed3\u679c\u957f\u5ea6\u76f8\u7b49\uff08\u7a0b\u5f0f\u4e0e\u7ed3\u679c\u4e00\u4e00\u5bf9\u5e94\uff09\uff0c\u5e76\u4e14\u7ed3\u679c\u503c\u5747\u4e3a\u6b63\u6570\u3002\u4ee5\u4e0a\u4e3a\u65b9\u7a0b\u5f0f\u7684\u63cf\u8ff0\u3002 \u8fd4\u56devector<double>\u7c7b\u578b\u3002

    \n\n

    \u57fa\u4e8e\u4e0a\u8ff0\u4f8b\u5b50\uff0c\u8f93\u5165\u5982\u4e0b\uff1a

    \n\n
    \nequations(\u65b9\u7a0b\u5f0f) = [ ["a", "b"], ["b", "c"] ],\nvalues(\u65b9\u7a0b\u5f0f\u7ed3\u679c) = [2.0, 3.0],\nqueries(\u95ee\u9898\u65b9\u7a0b\u5f0f) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. \n
    \n\n

    \u8f93\u5165\u603b\u662f\u6709\u6548\u7684\u3002\u4f60\u53ef\u4ee5\u5047\u8bbe\u9664\u6cd5\u8fd0\u7b97\u4e2d\u4e0d\u4f1a\u51fa\u73b0\u9664\u6570\u4e3a0\u7684\u60c5\u51b5\uff0c\u4e14\u4e0d\u5b58\u5728\u4efb\u4f55\u77db\u76fe\u7684\u7ed3\u679c\u3002

    \n*/\n\n\n/**\n * @param {string[][]} equations\n * @param {number[]} values\n * @param {string[][]} queries\n * @return {number[]}\n */\nvar calcEquation = function(equations, values, queries) {\n \n};"} {"doc_id": "35325bcea0123ea621ebcf6994dda010", "text": "/*\n

    Given the running logs of n functions that are executed in a nonpreemptive single threaded CPU, find the exclusive time of these functions.

    \n\n

    Each function has a unique id, start from 0 to n-1. A function may be called recursively or by another function.

    \n\n

    A log is a string has this format : function_id:start_or_end:timestamp. For example, \"0:start:0\" means function 0 starts from the very beginning of time 0. \"0:end:0\" means function 0 ends to the very end of time 0.

    \n\n

    Exclusive time of a function is defined as the time spent within this function, the time spent by calling other functions should not be considered as this function's exclusive time. You should return the exclusive time of each function sorted by their function id.

    \n\n

    Example 1:
    \n

    \nInput:\nn = 2\nlogs = \n[\"0:start:0\",\n \"1:start:2\",\n \"1:end:5\",\n \"0:end:6\"]\nOutput:[3, 4]\nExplanation:\nFunction 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1. \nNow function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5.\nFunction 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time. \nSo function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time.\n
    \n

    \n\n

    Note:
    \n

      \n
    1. Input logs will be sorted by timestamp, NOT log id.
    2. \n
    3. Your output should be sorted by function id, which means the 0th element of your output corresponds to the exclusive time of function 0.
    4. \n
    5. Two functions won't start or end at the same time.
    6. \n
    7. Functions could be called recursively, and will always end.
    8. \n
    9. 1 <= n <= 100
    10. \n
    \n

    \u7ed9\u51fa\u4e00\u4e2a\u975e\u62a2\u5360\u5355\u7ebf\u7a0bCPU\u7684 n \u4e2a\u51fd\u6570\u8fd0\u884c\u65e5\u5fd7\uff0c\u627e\u5230\u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u3002

    \n\n

    \u6bcf\u4e2a\u51fd\u6570\u90fd\u6709\u4e00\u4e2a\u552f\u4e00\u7684 Id\uff0c\u4ece 0 \u5230 n-1\uff0c\u51fd\u6570\u53ef\u80fd\u4f1a\u9012\u5f52\u8c03\u7528\u6216\u8005\u88ab\u5176\u4ed6\u51fd\u6570\u8c03\u7528\u3002

    \n\n

    \u65e5\u5fd7\u662f\u5177\u6709\u4ee5\u4e0b\u683c\u5f0f\u7684\u5b57\u7b26\u4e32\uff1afunction_id\uff1astart_or_end\uff1atimestamp\u3002\u4f8b\u5982\uff1a"0:start:0" \u8868\u793a\u51fd\u6570 0 \u4ece 0 \u65f6\u523b\u5f00\u59cb\u8fd0\u884c\u3002"0:end:0" \u8868\u793a\u51fd\u6570 0 \u5728 0 \u65f6\u523b\u7ed3\u675f\u3002

    \n\n

    \u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u5b9a\u4e49\u662f\u5728\u8be5\u65b9\u6cd5\u4e2d\u82b1\u8d39\u7684\u65f6\u95f4\uff0c\u8c03\u7528\u5176\u4ed6\u51fd\u6570\u82b1\u8d39\u7684\u65f6\u95f4\u4e0d\u7b97\u8be5\u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u3002\u4f60\u9700\u8981\u6839\u636e\u51fd\u6570\u7684 Id \u6709\u5e8f\u5730\u8fd4\u56de\u6bcf\u4e2a\u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \u8f93\u5165:\nn = 2\nlogs = \n["0:start:0",\n "1:start:2",\n "1:end:5",\n "0:end:6"]\n\u8f93\u51fa:[3, 4]\n\u8bf4\u660e\uff1a\n\u51fd\u6570 0 \u5728\u65f6\u523b 0 \u5f00\u59cb\uff0c\u5728\u6267\u884c\u4e86  2\u4e2a\u65f6\u95f4\u5355\u4f4d\u7ed3\u675f\u4e8e\u65f6\u523b 1\u3002\n\u73b0\u5728\u51fd\u6570 0 \u8c03\u7528\u51fd\u6570 1\uff0c\u51fd\u6570 1 \u5728\u65f6\u523b 2 \u5f00\u59cb\uff0c\u6267\u884c 4 \u4e2a\u65f6\u95f4\u5355\u4f4d\u540e\u7ed3\u675f\u4e8e\u65f6\u523b 5\u3002\n\u51fd\u6570 0 \u518d\u6b21\u5728\u65f6\u523b 6 \u5f00\u59cb\u6267\u884c\uff0c\u5e76\u5728\u65f6\u523b 6 \u7ed3\u675f\u8fd0\u884c\uff0c\u4ece\u800c\u6267\u884c\u4e86 1 \u4e2a\u65f6\u95f4\u5355\u4f4d\u3002\n\u6240\u4ee5\u51fd\u6570 0 \u603b\u5171\u7684\u6267\u884c\u4e86 2 +1 =3 \u4e2a\u65f6\u95f4\u5355\u4f4d\uff0c\u51fd\u6570 1 \u603b\u5171\u6267\u884c\u4e86 4 \u4e2a\u65f6\u95f4\u5355\u4f4d\u3002\n
    \n\n

    \u8bf4\u660e\uff1a

    \n\n
      \n\t
    1. \u8f93\u5165\u7684\u65e5\u5fd7\u4f1a\u6839\u636e\u65f6\u95f4\u6233\u6392\u5e8f\uff0c\u800c\u4e0d\u662f\u6839\u636e\u65e5\u5fd7Id\u6392\u5e8f\u3002
    2. \n\t
    3. \u4f60\u7684\u8f93\u51fa\u4f1a\u6839\u636e\u51fd\u6570Id\u6392\u5e8f\uff0c\u4e5f\u5c31\u610f\u5473\u7740\u4f60\u7684\u8f93\u51fa\u6570\u7ec4\u4e2d\u5e8f\u53f7\u4e3a 0 \u7684\u5143\u7d20\u76f8\u5f53\u4e8e\u51fd\u6570 0 \u7684\u6267\u884c\u65f6\u95f4\u3002
    4. \n\t
    5. \u4e24\u4e2a\u51fd\u6570\u4e0d\u4f1a\u5728\u540c\u65f6\u5f00\u59cb\u6216\u7ed3\u675f\u3002
    6. \n\t
    7. \u51fd\u6570\u5141\u8bb8\u88ab\u9012\u5f52\u8c03\u7528\uff0c\u76f4\u5230\u8fd0\u884c\u7ed3\u675f\u3002
    8. \n\t
    9. 1 <= n <= 100
    10. \n
    \n

    \u7ed9\u51fa\u4e00\u4e2a\u975e\u62a2\u5360\u5355\u7ebf\u7a0bCPU\u7684 n \u4e2a\u51fd\u6570\u8fd0\u884c\u65e5\u5fd7\uff0c\u627e\u5230\u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u3002

    \n\n

    \u6bcf\u4e2a\u51fd\u6570\u90fd\u6709\u4e00\u4e2a\u552f\u4e00\u7684 Id\uff0c\u4ece 0 \u5230 n-1\uff0c\u51fd\u6570\u53ef\u80fd\u4f1a\u9012\u5f52\u8c03\u7528\u6216\u8005\u88ab\u5176\u4ed6\u51fd\u6570\u8c03\u7528\u3002

    \n\n

    \u65e5\u5fd7\u662f\u5177\u6709\u4ee5\u4e0b\u683c\u5f0f\u7684\u5b57\u7b26\u4e32\uff1afunction_id\uff1astart_or_end\uff1atimestamp\u3002\u4f8b\u5982\uff1a"0:start:0" \u8868\u793a\u51fd\u6570 0 \u4ece 0 \u65f6\u523b\u5f00\u59cb\u8fd0\u884c\u3002"0:end:0" \u8868\u793a\u51fd\u6570 0 \u5728 0 \u65f6\u523b\u7ed3\u675f\u3002

    \n\n

    \u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u5b9a\u4e49\u662f\u5728\u8be5\u65b9\u6cd5\u4e2d\u82b1\u8d39\u7684\u65f6\u95f4\uff0c\u8c03\u7528\u5176\u4ed6\u51fd\u6570\u82b1\u8d39\u7684\u65f6\u95f4\u4e0d\u7b97\u8be5\u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u3002\u4f60\u9700\u8981\u6839\u636e\u51fd\u6570\u7684 Id \u6709\u5e8f\u5730\u8fd4\u56de\u6bcf\u4e2a\u51fd\u6570\u7684\u72ec\u5360\u65f6\u95f4\u3002

    \n\n

    \u793a\u4f8b 1:

    \n\n
    \u8f93\u5165:\nn = 2\nlogs = \n["0:start:0",\n "1:start:2",\n "1:end:5",\n "0:end:6"]\n\u8f93\u51fa:[3, 4]\n\u8bf4\u660e\uff1a\n\u51fd\u6570 0 \u5728\u65f6\u523b 0 \u5f00\u59cb\uff0c\u5728\u6267\u884c\u4e86  2\u4e2a\u65f6\u95f4\u5355\u4f4d\u7ed3\u675f\u4e8e\u65f6\u523b 1\u3002\n\u73b0\u5728\u51fd\u6570 0 \u8c03\u7528\u51fd\u6570 1\uff0c\u51fd\u6570 1 \u5728\u65f6\u523b 2 \u5f00\u59cb\uff0c\u6267\u884c 4 \u4e2a\u65f6\u95f4\u5355\u4f4d\u540e\u7ed3\u675f\u4e8e\u65f6\u523b 5\u3002\n\u51fd\u6570 0 \u518d\u6b21\u5728\u65f6\u523b 6 \u5f00\u59cb\u6267\u884c\uff0c\u5e76\u5728\u65f6\u523b 6 \u7ed3\u675f\u8fd0\u884c\uff0c\u4ece\u800c\u6267\u884c\u4e86 1 \u4e2a\u65f6\u95f4\u5355\u4f4d\u3002\n\u6240\u4ee5\u51fd\u6570 0 \u603b\u5171\u7684\u6267\u884c\u4e86 2 +1 =3 \u4e2a\u65f6\u95f4\u5355\u4f4d\uff0c\u51fd\u6570 1 \u603b\u5171\u6267\u884c\u4e86 4 \u4e2a\u65f6\u95f4\u5355\u4f4d\u3002\n
    \n\n

    \u8bf4\u660e\uff1a

    \n\n
      \n\t
    1. \u8f93\u5165\u7684\u65e5\u5fd7\u4f1a\u6839\u636e\u65f6\u95f4\u6233\u6392\u5e8f\uff0c\u800c\u4e0d\u662f\u6839\u636e\u65e5\u5fd7Id\u6392\u5e8f\u3002
    2. \n\t
    3. \u4f60\u7684\u8f93\u51fa\u4f1a\u6839\u636e\u51fd\u6570Id\u6392\u5e8f\uff0c\u4e5f\u5c31\u610f\u5473\u7740\u4f60\u7684\u8f93\u51fa\u6570\u7ec4\u4e2d\u5e8f\u53f7\u4e3a 0 \u7684\u5143\u7d20\u76f8\u5f53\u4e8e\u51fd\u6570 0 \u7684\u6267\u884c\u65f6\u95f4\u3002
    4. \n\t
    5. \u4e24\u4e2a\u51fd\u6570\u4e0d\u4f1a\u5728\u540c\u65f6\u5f00\u59cb\u6216\u7ed3\u675f\u3002
    6. \n\t
    7. \u51fd\u6570\u5141\u8bb8\u88ab\u9012\u5f52\u8c03\u7528\uff0c\u76f4\u5230\u8fd0\u884c\u7ed3\u675f\u3002
    8. \n\t
    9. 1 <= n <= 100
    10. \n
    \n*/\n\n\n/**\n * @param {number} n\n * @param {string[]} logs\n * @return {number[]}\n */\nvar exclusiveTime = function(n, logs) {\n \n};"} {"doc_id": "356e2833e035049779eda9ff05697498", "text": "// These coding challenges were completed during the precourse work that was\n// required for acceptance into Lambda School's Full Time Full Stack\n// Software Engineering/Computer Science program.\n\n\n\n//*==========* JavaScript: Array Methods *==========*\n\n// The following arrays will be used through the questions:\nconst words = [ 'cattywampus', 'snickersnee', 'lollygag', 'pandiculation', 'ratoon' ];\nconst numbers = [ 8, 3, 22, 0, -73, 15 ];\n\n// Question 1: \n// Use forEach to console.log all the words in the words array. Do not write a for loop. \nfunction logWords(array){\n words.forEach(function(item) {\n console.log(item);\n });\n}\n\nlogWords(words);\n\n\n\n// Question 2: Use forEach to console.log each number in the numbers array divided by two\n// It should console.log: \n// 4\n// 1.5\n// ...etc. \nfunction logHalfNumbers(array){\n numbers.forEach(function(item) {\n console.log(item/2);\n });\n}\n\nlogHalfNumbers(numbers);\n\n\n\n// Question 3: Using the getFirstLetter function below as your callback,\n// use map to create an array contaning the first letter of \n// every word from the words array.\nfunction getFirstLetter(word) {\n let firstChar = word[0];\n return firstChar;\n}\n\nconst firstLetters = words.map(getFirstLetter);\nconsole.log(firstLetters);\n\n\n\n// Question 4: Use map to create an array containing the last letter of every word\n// from the words array. \nconst lastLetters = words.map(function(word) {\n let numOfChars = word.length;\n let lastChar = word[numOfChars-1];\n return lastChar;\n});\nconsole.log(lastLetters);\n\n\n\n// Question 5: Use map to create an array containing the reversed version of each word\n// from the word array. For example, the first entry will be 'supmawyttac'.\nconst reversedWords = words.map(function(item) {\n let arrayOfWord = item.split(\"\").reverse();\n return arrayOfWord.join(\"\");\n});\n\nconsole.log(reversedWords);\n\n\n\n// Question 6: Use map to create an array containing the absolute value of every number\n// in the numbers array.\nconst absoluteNumbers = numbers.map(function(item) {\n return Math.abs(item);\n});\n\nconsole.log(absoluteNumbers);\n\n\n\n// Question 7: Use map to create an array containing each number from the numbers array\n// rounded to the nearest 10. For example: 10, 0, 20, 0, etc. \nconst roundedToTenNumbers = numbers.map(function(item) {\n let tenthOfNum = (Math.abs(item))/10;\n\n if (tenthOfNum < 0.5) {\n return (Math.floor(item/10))*10;\n } else if ((tenthOfNum > 0.5) && (tenthOfNum < 1)) {\n return (Math.ceil(item/10))*10;\n } else if ((tenthOfNum > 1) && (tenthOfNum < 10)) {\n return (Math.round(item/10))*10;\n }\n});\n\nconsole.log(roundedToTenNumbers);\n\n\n\n// Question 8: Use map to create an array that contains only the words from the words\n// array containing 's'. All other words should be replaced with null.\n// For example: 'cattywampus', 'snickersnee', null, etc. \nconst wordsWithS = words.map(function(item) {\n if (item.includes(\"s\") === true) {\n return item;\n } else {\n return null;\n }\n});\n\nconsole.log(wordsWithS);\n\n\n\n// Stretch Questions:\n// The stretch question will use the array method reduce, which was only briefly reviewed \n// in the lecture. Refer to online documentation for more information on reduce. \n\n// Question 9: Use reduce to sum up all of the numbers in the numbers array. \n\n// function sum(currentTotal, nextNumber) {\n\n// }\n\n// const sumTotal = numbers.reduce();\n\n// Question 10: Use reduce to find the word from the words array that is last in the alphabet.\n\n// const alphabeticallyLast = words.reduce(function() {\n\n// });\n\n\n\n//*==========* JavaScript: Higher Order Functions vs. Callbacks *==========*\n\n/* For each example of code please identify \n the higher order function and the callback function(s) */\n \n/* For both types of functions, you will describe the \n parameters and return values (if any) */\n\n// Question 1:\n\n// callback function\n// parameters: none\n// return values: none\nfunction returned() {\n console.log(\"The king hath returned from the hunt!\");\n }\n \n // callback function\n // parameters: none\n // return values: none\n function death() {\n console.log(\"The king is dead!\");\n }\n \n // callback function\n // parameters: none\n // return values: none\n function birth() {\n console.log(\"An heir has been born today!\");\n }\n \n // higher order function\n // parameters: callback function\n // return values: callback function\n function announce(cb) {\n console.log(\"Hear ye! Hear ye!\");\n cb();\n }\n \n announce(returned);\n announce(birth);\n announce(death);\n \n /**\n 1a) What is the higher order function in this example? List the parameters and return values. \n -The higher order function in this example is 'announce'. \n -There is only one parameter for this higher order function (\"callback\" or \"cb\").\n \n 1b) What are the callbacks in this example? List the parameters and return values for each. \n -The callback functions in this example are: \"returned\", \"death\", and \"birth\".\n -Each of the aforementioned callback functions do not have any return values.\n */\n \n // Question 2:\n \n // callback function\n // parameters: x, y\n // return values: the sum of x and y (x + y)\n function addFn(x, y) {\n return x + y;\n }\n \n // callback function\n // parameters: x, y\n // return values: the difference of x and y (x - y)\n function subtractFn(x, y) {\n return x - y;\n }\n \n // higher order function\n // parameters: x, y, cb (or \"callback\")\n // return values: the return value of whichever callback function is passed to it (addFn || subtractFn)\n function combine(x, y, cb) {\n return cb(x, y);\n }\n \n const result1 = combine(1, 4, addFn);\n const result2 = combine(9, -2, subtractFn);\n const result3 = combine(2, 3, function(x, y) {\n return x * y;\n })\n \n /**\n 2a) What is the higher order function? List the parameters and return values. \n -The higher order function in this example is 'combine'. \n -There are three parameters for this higher order function (x, y, and cb (or \"callback\").\n \n 2b) What are the callbacks? List the parameters and return values for each. \n -The callback functions in this example are \"addFn\" and \"subtractFn\".\n -addFn:\n -parameters: x, y\n -return value: (only one) the sum of x and y\n -subtractFn:\n -parameters: x, y\n -return value: (only one) the difference of x and y\n */\n \n \n // Question 3:\n \n function addExcitement(string) {\n return 'string' + '!';\n }\n \n const phrases = [ 'A fish rots from the head down', 'A rolling stone gathers no moss', 'A rose is a rose is a rose'];\n const excitedPhrases = phrases.map(addExcitement);\n \n /**\n 3a) What is the higher order function? List the parameters and return values. \n -The higher order function in this example is '.map( )'. \n -There is only one parameter (a callback function => 'addExcitement') for this higher order function.\n 3b) What are the callbacks? List the parameters and return values for each. \n -The callback function in this example is 'addExcitement'.\n -addExcitement:\n -parameters: \"string\"\n -return value: (only one) the concatenation of \"string\" and \"!\"\n */\n \n \n // Stretch Question 4:\n \n function findLongest(str1, str2) {\n const firstLonger = str1.length >= str2.length;\n \n if (firstLonger) {\n return str1;\n } else {\n return str2;\n }\n }\n \n const words = [ 'cattywampus', 'snickersnee', 'lollygag', 'pandiculation', 'ratoon' ];\n \n const longestWord = words.reduce(findLongest);\n const longestPhrase = phrases.reduce(findLongest);\n \n /**\n 4a) What is the higher order function? List the parameters and return values. \n -The higher order function in this example is '.reduce( )'. \n -There is only one parameter (a callback function => 'findLongest') for this higher order function.\n 4b) What are the callbacks? List the parameters and return values for each. \n -The callback function in this example is 'findLongest'.\n -findLongest:\n -parameters: \"str1\", \"str2\"\n -return value: (only one) str1 OR str2\n */\n \n console.log(longestWord);\n console.log(longestPhrase);\n\n\n\n//*==========* JavaScript: Classes *==========*\n\n/* === DO NOT ALTER CODE BELOW THIS LINE UNTIL LINE 88 === */\n// HtmlElement is a javascript class that represents an HTML element\n// It's constructor takes in two arguments: type and text\n// type is the type of element (example div, p, span, h1, etc)\n// text is an optional argument and represents any text in the element\nconst HtmlElement = function(type, text) {\n this.type = type;\n this.text = text || \"\";\n this.id = null;\n this.classes = [];\n this.children = [];\n };\n \n // The addID method will add an id to an HTML element\n // If an id already exists, it will overwrite it. \n HtmlElement.prototype.addID = function(id) {\n this.id = id;\n };\n \n // The addClass method will add a class to an HTML element\n // addClass can be called multiple times to add different classes\n HtmlElement.prototype.addClass = function(className) {\n this.classes.push(className);\n };\n \n // The addChild method will add children elements\n // The argument must be an HtmlElement object\n HtmlElement.prototype.addChild = function(element) {\n if (!(element instanceof HtmlElement)) {\n throw new Error('Invalid argument for addChild method');\n }\n \n this.children.push(element);\n };\n \n // The toString method returns a string version of the HTML element\n // Note: The following code is quite complicated\n // While you can use this method to check your work,\n // there is no need to read through it or understand it\n // (until you get the stretch question)\n HtmlElement.prototype.toString = function() {\n const openingTag = getOpeningTag(this.type, this.id, this.classes);\n const closingTag = \"\";\n \n return openingTag + this.text + closingTag;\n \n function getID(id) {\n if (!id) {\n return \"\";\n }\n \n return \"id=\\\"\" + id + \"\\\"\";\n }\n \n function getClasses(classes) {\n if (!classes.length) {\n return \"\";\n }\n \n const classList = classes.reduce(function(string, name) {\n return string + ' ' + name;\n });\n \n return \"class=\\\"\" + classList + \"\\\"\";\n }\n \n function getOpeningTag(type, id, classes) {\n const idText = getID(id);\n const classText = getClasses(classes);\n \n let text = type;\n \n if (idText) {\n text += \" \" + idText;\n }\n \n if (classText) {\n text += \" \" + classText;\n }\n \n return \"<\"+text+\">\"\n }\n };\n \n /* === DO NOT ALTER ANY CODE ABOVE THIS LINE === */\n \n \n // Question 1: Create following instances of HtmlElement. \n // You will need to use the method of addID and addClass.\n // The toString method may be used to check your work. \n //\n // a.

    To every action, there is an equal and opposite reaction.

    \n // b.

    Welcome to the Webpage

    \n // c.
    \n // d.
  • Scallion
  • \n // e. \n \n // Assign the following variables correctly:\n const elementA = new HtmlElement('p', 'To every action there is an equal and opposite reaction.');\n \n const elementB = new HtmlElement('h1', 'Welcome to the Webpage');\n elementB.addID('main');\n console.log(elementB.id.toString());\n \n const elementC = new HtmlElement('div');\n elementC.addClass('container');\n elementC.addClass('important');\n console.log(elementC.classes.toString());\n \n const elementD = new HtmlElement('li', 'Scallion');\n elementD.addID('first-item');\n elementD.addClass('stir-fry');\n console.log(elementD.id.toString());\n console.log(elementD.classes.toString());\n \n const elementE = new HtmlElement('span');\n elementE.addID('CTA');\n elementE.addClass('inline');\n elementE.addClass('important');\n console.log(elementE.id.toString());\n console.log(elementE.classes.toString());\n \n // Question 2: Create an element that represents the following ordered list.\n // You will need to create an new element for each of its children\n // and add them to their parent using the addChild method. \n // Note that the toString method won't fully work on elements with \n // children (see stretch question). \n //\n //
      \n //
    1. Discover the secret to prime factorization
    2. \n //
    3. Hack through online banking security
    4. \n //
    5. Blackmail all the major global leaders
    6. \n //
    7. World domination
    8. \n //
    \n \n const stepsToWorldDomination = new HtmlElement('ol');\n stepsToWorldDomination.addID('world-domination');\n \n const childElement1 = new HtmlElement('li', 'Discover the secret to prime factorization');\n stepsToWorldDomination.addChild(childElement1);\n console.log(stepsToWorldDomination.children.toString());\n \n const childElement2 = new HtmlElement('li', 'Hack through online banking security');\n childElement2.addClass('illegal');\n stepsToWorldDomination.addChild(childElement2);\n console.log(stepsToWorldDomination.children.toString());\n \n const childElement3 = new HtmlElement('li', 'Blackmail all the major global leaders');\n childElement3.addClass('illegal');\n stepsToWorldDomination.addChild(childElement3);\n console.log(stepsToWorldDomination.children.toString());\n \n const childElement4 = new HtmlElement('li', 'World domination');\n stepsToWorldDomination.addChild(childElement4);\n console.log(stepsToWorldDomination.children.toString());\n \n // Question 3: Write the removeClass method on the HTMLElement class.\n \n \n // The removeClass method will remove a class from an element\n // by removing that class name from the this.classes array\n // Example: if element.children were equal to ['inline', 'important']\n // and you called element.removeClass('inline'), afterward \n // element.classes would be equal to ['important']\n \n HtmlElement.prototype.removeClass = function(className) {\n \n if (this.classes.length <= 0) {\n return \"Sorry! This class cannot be removed because this element has no classes on it!\";\n \n } else {\n console.log(\"Number of Classes on this Element: \" + this.classes.length);\n \n let matchingIndex = this.classes.findIndex(function(matchingClass) {\n return matchingClass === className;\n });\n \n console.log(\"Index of Matching Class: \" + matchingIndex);\n \n if (matchingIndex < 0) {\n return \"Sorry, but this class name does not exist on this element!\";\n \n } else {\n let oldZeroIndex = this.classes[0];\n let newZeroIndex = this.classes[matchingIndex];\n \n this.classes[0] = newZeroIndex;\n this.classes[matchingIndex] = oldZeroIndex;\n \n console.log(this.classes);\n this.classes.shift();\n console.log(this.classes);\n }\n \n if (this.classes.length < 1) {\n return \"Sorry, there are no classes on this element any more. You have just removed the only class.\";\n \n } else {\n return this.classes;\n }\n }\n };\n \n \n \n // STRETCH QUESTION (NOT REQUIRED)\n // Question 4: Update toString\n //\n // As you notice in Question 2 toString does not work for elements with children.\n // Your job is to update the method so that it prints the element containing it's children.\n // The first step will be to spend some time reading through the existing code and understanding it.\n //\n // Note: The string should not include any new lines or tabbing.\n //\n // Example: stepsToWorldDomination.toString() should yield:\n // \"
    1. Discover the secret to prime factorization
    2. Hack through online banking...\"\n // (Full string not shown because it would be super long, but you get the point...)\n\n\n\n\n//*==========* JavaScript: Arrays & Objects *==========*\n\n// getThird takes in an array \n// it returns the third item in the array\n// if there is no third item, return null\n// Example: getThird(['Doc', 'Biff', 'Marty']) returns 'Marty'\n\nfunction getThird(array) {\n if (array.length >= 3) {\n return array[2];\n } else {\n return null;\n }\n }\n \n \n // stringLengths takes in four strings\n // it returns an array containing the length of each string\n // Example: stringLengths('mushroom', 'onion', '', 'garlic') returns [8, 5, 0, 6] \n \n function stringLengths(str1, str2, str3, str4) {\n let objectOfArgs = arguments;\n const arrayOfArgs = [];\n \n for (let key in objectOfArgs) {\n arrayOfArgs.push(objectOfArgs[key].length);\n }\n \n return arrayOfArgs;\n }\n \n \n // removeFirst takes in an array\n // it returns the same array, but with the first item removed\n // Example: removeFirst(['frog', 'toad', 'cricket', 'skunk']) would\n // return ['toad', 'cricket', 'skunk'] \n \n function removeFirst(array) {\n array.shift();\n return array;\n }\n \n \n // swap takes in an array and two indices \n // it returns the array with the items at i and j swapped\n // Example: swap(['unicycle', 'scooter', 'skateboard', 'canoe'], 0, 2) would\n // return ['skateboard', 'scooter', 'unicycle', 'canoe'];\n \n function swap(array, i, j) {\n let newItemI = array[j];\n let newItemJ = array[i];\n \n array[i] = newItemI;\n array[j] = newItemJ;\n \n return array;\n }\n \n // getValue takes in an object and a key name\n // if the key exists in the object, return the value of that key\n // if not, return null\n // Example: getValue({ first: 'Gordon', last: 'Peppermill'}, 'last') \n // would return 'Peppermill'\n \n function getValue(object, key) {\n if (object[key] !== undefined) {\n return object[key];\n } else {\n return null;\n }\n }\n \n \n // generateCSS takes in three strings containing CSS values\n // it returns an object with the CSS key value pairs\n // Example: generateCSS('100px', '70px', 'blue') would return\n // { height: '100px', width: '70px', color: 'blue' }\n \n function generateCSS(height, width, color) {\n const objectOfValues = arguments;\n const arrayOfCssProperties = ['height', 'width', 'color'];\n const arrayOfValues = [];\n const newObjectOfValues = {};\n \n for (let key in objectOfValues) {\n arrayOfValues.push(objectOfValues[key]);\n }\n \n for (let i = 0; i < arrayOfCssProperties.length; i++) {\n newObjectOfValues[arrayOfCssProperties[i]] = arrayOfValues[i];\n }\n \n return newObjectOfValues;\n }\n \n // getValues takes in an object\n // it returns an array containing the values from that object\n // Example: getValues({ name: 'Ally', age: 27, job: 'hypnotist' })\n // would return ['Ally', 27, 'hypnotist']\n \n function getValues(obj) {\n const newArray = [];\n \n for (var key in obj) {\n newArray.push(obj[key]);\n }\n \n return newArray;\n }\n \n // STRETCH PROBLEMS (NOT REQUIRED)\n \n // wrapAround takes in an array\n // and returns an array with the last item in the first spot\n // and everything else shifted one index over\n // Example: wrapAround(['teaspoon', 'meat grinder', 'spatula', 'salad fork'])\n // would return ['salad fork', 'teaspoon', 'meat grinder', 'spatula']\n \n function wrapAround(array) {\n let poppedItem = array.pop();\n array.unshift(poppedItem);\n return array;\n }\n \n // count takes in an array\n // and returns an object containing a frequency count for each item in the array\n // Example: count(['red', 'blue', 'blue', 'pink', 'blue', 'green', 'red']) would\n // return { red: 2, blue: 3, pink: 1, green: 1}\n \n function count(array) {\n let redCount = 0;\n let blueCount = 0;\n let pinkCount = 0;\n let greenCount = 0;\n const counterObject = {};\n \n for (let i = 0; i < array.length; i++) {\n if (array[i] === 'red') {\n redCount++;\n } else if (array[i] === 'blue') {\n blueCount++;\n } else if (array[i] === 'pink') {\n pinkCount++;\n } else if (array[i] === 'green') {\n greenCount++;\n }\n }\n \n counterObject.red = redCount;\n counterObject.blue = blueCount;\n counterObject.pink = pinkCount;\n counterObject.green = greenCount;\n \n return counterObject;\n }\n\n\n\n//*==========* JavaScript: Functions *==========*\n\n// addOne takes in a number as a parameter \n// and returns that numbers +1\n// Example: addOne(-7) returns -6\n\nfunction addOne(x) {\n let num = x + 1;\n return num;\n }\n \n // divide takes in two numbers as parameters\n // and returns the first divided by the second\n // Example: divide(6, 3) returns 2\n \n function divide(x, y) {\n let answer = x / y;\n return answer;\n }\n \n // getBiggest takes in two numbers\n // and returns the largest of the two\n // if they are the same, return either\n // Example getBiggest(-1, 3) returns 3\n \n function getBiggest(x, y) {\n if (x >= y) {\n return x;\n } else {\n return y;\n }\n }\n \n // getLength takes in a string\n // and returns the length of the string\n // Example: getLength('tazerface') returns 9\n \n function getLength(str) {\n return str.length;\n }\n \n // orderPizza takes in a boolean\n // if it is true return the string 'cheese pizza'\n // if not, return the string 'pepperoni pizza'\n // Example: orderPizza(true) returns 'cheese pizza'\n \n function orderPizza(vegetarian) {\n if (vegetarian === true) {\n let cheese = 'cheese pizza';\n return cheese;\n } else {\n let pepperoni = 'pepperoni pizza';\n return pepperoni;\n }\n }\n \n // countDown takes in a number greater than 0\n // it logs every number starting from the input down to 0\n // there is no return value\n // Example: countDown(3) logs the following\n // 3 \n // 2 \n // 1 \n // 0\n \n function countDown(start) {\n for (let i = start; i >= 0; i--) {\n console.log(i);\n }\n }\n \n // repeat logs a phrase x number of times\n // there is no return value\n // Example: repeat(\"not your mama's edamame\", 4) logs the following\n // \"not your mama's edamame\"\n // \"not your mama's edamame\"\n // \"not your mama's edamame\"\n // \"not your mama's edamame\"\n \n function repeat(phrase, x) {\n for (let i = 0; i < x; i++) {\n console.log(phrase);\n }\n }\n \n // getHTMLTag takes in a tag name \n // and returns the opening and closing tag\n // Example: getHTMLTag('div') would return '
      '\n \n function getHTMLTag(tagName) {\n let openAndClose = '<' + tagName + '>';\n return openAndClose;\n }\n \n \n // STRETCH PROBLEMS (NOT REQUIRED)\n \n // getHeaderTag takes in header text and a header size \n // and returns the opening and closing H tag with the text inside\n // Example: getHeaderTag('Welcome', 2) would return '

      Welcome

      '\n \n function getHeaderTag(text, size) {\n let fullTag = '' + text + '';\n return fullTag;\n }\n \n // logMultiples takes in two numbers \n // and logs any number between 1 and 100 that is a multiple of x or y\n // there is no return value\n // Example: logMultiples(20, 25) would log\n // 20\n // 25\n // 40\n // 50\n // 60\n // 75\n // 80\n // 100\n \n function logMultiples(x, y) {\n for (let i = 1; i <= 100; i++) {\n if ((i % x === 0) || (i % y === 0)) {\n console.log(i)\n } else {\n continue;\n }\n }\n }\n \n // reverseWords takes in a string and reverses every word in the phrase\n // it returns the reversed version of the string\n // Example: reverseWords('good luck') would return 'kcul doog'\n \n function reverseWords(phrase) {\n let phraseArray = phrase.split();\n let newArray = [];\n for (let i = phrase.length; i >= 0; i--) {\n let char = phrase.charAt(i-1);\n newArray.push(char);\n }\n let newPhrase = newArray.join('');\n return newPhrase;\n }\n\n\n\n//*==========* JavaScript: FOR-Loops & IF-Statements *==========*\n\n// example:\n// Write a for loop that logs the numbers 0 through 5\nfor (let i = 0; i < 6; i++) {\n console.log(i);\n }\n \n \n // 1.\n // Write a for loop that logs the numbers 0 through 10\n for (let i = 0; i < 11; i++) {\n console.log(i);\n }\n \n \n \n // 2.\n // Write a loop that logs the numbers 10 through 0\n for (let i = 10; i >= 0; i--) {\n console.log(i);\n }\n \n \n // 3.\n // Write a loop that logs the word \"Hippopotamus\" 17 times. \n for (let i = 0; i < 17; i++) {\n console.log('Hippopotamus');\n }\n \n \n // 4.\n // Write a for loop that logs 2, 4, 6, 8, 10\n for (let i = 2; i <= 10; i = i + 2) {\n console.log(i);\n }\n \n \n // 5.\n // Write a loop that logs the numbers 2, 4, 6, 8.\n // Do not edit the existing code.\n \n for (let i = 0; i < 4; i++) {\n let num = (i * 2) + 2;\n console.log(num);\n }\n \n // 6.\n // Write a loop that logs the numbers 5 through 10. \n // Do not edit the existing code.\n \n for (let i = 0; i < 20; i++) {\n if (i < 5) {\n continue;\n } if (i > 10) {\n continue;\n }\n console.log(i);\n } \n \n // 7. \n // Write a loop that logs \"Marco!\" when i is even,\n // \"Polo!\" when i is odd, \n // and 'Game Over!' when i is 0. \n // Do not edit the existing code.\n \n for (let i = 10; i >= 0; i--) {\n if ((i % 2) === 0) {\n console.log('Marco!');\n } if ((i % 2) !== 0) {\n console.log('Polo!');\n } if (i === 0) {\n console.log('Game Over!');\n }\n }\n \n // 8.\n // Use an else-if statement to assign all four null variables based on the age variable.\n // The code should work regardless of what value age is assigned to. \n // Assume the driving age is 16, voting age is 18, drinking age is 21, and retirement age is 66.\n const age = 26;\n let canDrive = null;\n let canVote = null;\n let canDrink = null;\n let canRetire = null;\n \n // Write all of your code below. Do not change the code above. \n \n if (age < 16) {\n canDrive = false;\n canVote = false;\n canDrink = false;\n canRetire = false;\n } else if (age < 18) {\n canDrive = true;\n canVote = false;\n canDrink = false;\n canRetire = false;\n } else if (age < 21) {\n canDrive = true;\n canVote = true;\n canDrink = true;\n canRetire = false;\n } else if (age < 66) {\n canDrive = true;\n canVote = true;\n canDrink = true;\n canRetire = false;\n } else if (age >= 66) {\n canDrive = true;\n canVote = true;\n canDrink = true;\n canRetire = true;\n }\n \n \n // STRETCH PROBLEMS (NOT REQUIRED)\n \n // 9.\n // Find a second way to write the loop from question 4. \n for (let i = 2; i <= 10; i++) {\n if ((i % 2) !== 0) {\n continue;\n }\n console.log(i);\n }\n \n \n // 10. \n // Write a loop that logs the numbers 0 through 10. \n // Only add code in the parenthesis following the 'for' keyword\n // Finish the code in the parentheses\n \n for (let i = 0; i <= 50; i = i+5) {\n \n //Do not add or edit code below here!\n if (i < 0) {\n continue;\n } else if ( i > 50) {\n break;\n } else {\n console.log(i/5);\n }\n }\n \n // 11.\n // Imagine you throw two six sided dice and sum up the total.\n // Write a loop that logs every possible score you could roll.\n // Used a nested for loop ( a loop inside of a loop)\n // Bonus Challenge: Don't log repeats.\n\n\n\n//*==========* JavaScript: True vs. False *==========*\n\n// Example: \nconst resultExample = true && true;\nlet resultExample_answer = true;\n\n// 1.\nconst result1 = true && false;\nlet result1_answer = false;\n\n// 2.\nconst result2 = true || false;\nlet result2_answer = true;\n\n// 3. \nconst result3 = true && (true || false);\nlet result3_answer = true;\n\n// 4. \nconst result4 = !true || false;\nlet result4_answer = false;\n\n// 5. \nconst result5 = !(true && false);\nlet result5_answer = true;\n\n// 6. \nconst result6 = !undefined;\nlet result6_answer = true;\n\n// 7.\nconst likesPizza = true;\nconst hasPizza = false;\nconst eatsPizza = likesPizza && hasPizza;\nconst result7 = eatsPizza;\nlet result7_answer = false;\n\n// 8. \nconst result8 = (null === undefined);\nlet result8_answer = false;\n\n// 9.\nconst result9 = (0 < 10) && true;\nlet result9_answer = true;\n\n// 10. \nconst ordersPizza = true;\nconst makesPizza = false;\nconst hasPizza1 = ordersPizza || makesPizza;\nconst result10 = hasPizza1;\nlet result10_answer = true;\n\n// 11.\nconst firstName = 'Candice';\nconst lastName = null;\nconst hasFullName = !!firstName && !!lastName;\nconst result11 = hasFullName;\nlet result11_answer = false;\n\n// 12.\nconst emptyStr = '';\nconst result12 = !!emptyStr;\nlet result12_answer = false;\n\n// 13. \nconst result13 = (true || false) === false;\nlet result13_answer = false;\n\n// 14.\nconst result14 = true && !false;\nlet result14_answer = true;\n\n// 15.\nconst hasPizza2 = true;\nconst canAffordGoodPizza = false;\nconst hasLowStandards = true;\nconst enjoysPizza = hasPizza2 && (canAffordGoodPizza || hasLowStandards);\nconst result15 = enjoysPizza;\nlet result15_answer = true;\n\n\n// STRETCH QUESTIONS (NOT REQUIRED)\n\n// 16. \nconst mondayHours = 4;\nconst tuesdayHours = 0;\nconst wednesdayHours = 2;\nconst workedThisWeek = (!!mondayHours || !!tuesdayHours || !!wednesdayHours);\nconst result16 = workedThisWeek;\nlet result16_answer = true;\n// (true || false || true)\n\n// 17.\nconst result17 = !(true && false) || (false && true);\nlet result17_answer = true;\n// true || false\n\n// 18.\nconst result18 = ((0 < 12) || !0) === false;\nlet result18_answer = false;\n// \n\n// 19.\nconst orderedFood = false;\nconst madeFood = false;\nconst hasFood = orderedFood || madeFood;\nconst isHungry = true;\nconst likesFood = false;\nconst wantsFood = !hasFood && isHungry && likesFood;\nconst result19 = wantsFood;\nlet result19_answer = false;\n// hasFood = false;\n// true && true && false;\n\n// 20. \nconst result20 = !(!true || false) && !(false || (true && false));\nlet result20_answer = true;\n// true && true;\n\n\n\n//*==========* JavaScript: Reading Code *==========*\n\nconst var1 = 'Lambda School';\nconst var2 = 9.8;\nconst var3 = var2.toString();\nconst var4 = var2 < 10;\nconst var5 = var4.toString;\n\n// Exercise 1:\n// What are the variables types of var1 - var5?\n// var1: String\n// var2: Number\n// var3: String\n// var4: Boolean\n// var5: Undefined \n\n// Exercise 2:\n// What are the values for of var1 - var5?\n// var1: 'Lambda School'\n// var2: 9.8\n// var3: '9.8'\n// var4: true\n// var5: Undefined\n\n//Exercises 3 - 6\nconst firstName = 'Grace';\nconst lastName = 'Hopper';\nlet length = firstName.length;\nconsole.log(length);\nconst fullName = firstName + lastName;\nconst mysteryVariable = lastName;\n\nlength = lastName.length;\nconsole.log(mysteryVariable);\n\n// 3. How many variables were declared?\nlet answer3 = 5;\n\n// 4. What two values were logged to the console? \nlet answer4Part1 = 5;\nlet answer4Part2 = 'Hopper';\n\n// 5. What does the variable 'fullName' contain? \nlet answer5 = firstName + lastName;\n\n// 6. What is the final value of length?\nlet answer6 = 6;\n\n// Exercises 7 - 9:\nconst x = 7;\nconst y = 3.3;\nconst z = y + 1;\nconst a = Math.ceil(y);\nconst b = Math.random();\nconst c = Math.pow(2, 2);\nconst randomize = Math.random();\n\n\n// 7. How many function calls occur in this piece of code?\nlet answer7 = 4;\n\n// 8. What are the arguments for each function call? Remember, none is valid answer. \n// Answer a: y;\n// Answer b: none;\n// Answer c: (2, 2)\n\n// 9. What are the return values for each?\n// Answer a: 4;\n// Answer b: 0.6662103157470614;\n// Answer c: 4;\n// Answer randomize: 0.04119832560487979;\n\n\n// Exercise 10:\n// const x = '9';\n// const y = 1.4;\n// const z = x++;\n// const sum = console.log(y + 10);\n// const greeting = hello;\n// x = Math.round(y);\n\n// What is wrong with the above code? \n// Answer: (1) 'const greeting' must have quotations around it's value of 'hello', \n// (2) the variable 'x' must be declared with a 'let' instead of a 'const' because\n// lines 76 and 79 call for changes to be made to the value of 'x'; however, because\n// it is has been declared with a 'const', it must remain constant, and therefore,\n// cannot be changed.\n\n\n\n\n//*==========* JavaScript: Variables *==========*\n\nconst noData = null;\n\n// Remove _replaceMe_ and add your own code so that each variable is the type that its name indicates\nconst numberVar = 55;\nconst stringVar = 'Tico';\nconst booleanVar = true;\nconst nullVar = noData;\nconst undefinedVar = undefined;\n\n// Remove _replaceMe_ and use math operators to assign the following variables. Use Math methods where ever possible. \nconst pi = 3.1415926;\nconst piPlusOne = pi+1;\nconst piMinusOne = pi-1;\nconst piDividedByThree = pi/3;\nconst piSquared = Math.pow(pi, 2);\nconst piRoundedDown = Math.floor(pi);\nconst piRoundedUp = Math.ceil(pi);\n\n// Create an if-else statement that will randomly log \"Marco\" half of the time and \"Polo\" the other half. \n\nif (Math.round(Math.random()) === 1) {\n console.log('Marco');\n} else {\n console.log('Polo');\n}\n\n// Remove _replaceMe_ and assign the variables below using x and y. \nconst x = 7.5;\nconst y = -15;\nconst isXLessThanY = x {\n const searchTerm = document.getElementById('search-term').value;\n const API_KEY = '13952251-a04c0a85278dcec07ae2ecd13';\n //terperate literal \n const URL = `https://pixabay.com/api/?key=${API_KEY}&q=${searchTerm}`;\n \n fetch (URL).then(response => {\n return response.json();\n }).then(data => {\n // Work with JSON \n //this will give us the data\n console.log(URL);\n console.log(data);\n let photos = data.hits;\n let i = 0;\n for (i; i < photos.length; i++){\n const img = document.createElement(\"img\");\n img.src = photos[i].largeImageURL;\n document.getElementById(\"images\").append(img);\n }\n \n //If the photo array is empty return this message\n if (photos == 0) {\n document.getElementById(\"images\").innerHTML = \"Sorry, no results found\";\n }\n\n }).catch(err =>{\n //Do this for an error\n document.write('sorry, no results found.');\n })\n}\n\n//this function will delete old image results\nconst clearImages = () => {\n document.getElementById (\"images\").innerHTML = \"\";\n}\n\nconst clickResults = () =>{\n clearImages();\n getImageResults();\n}\n\ndocument.getElementById('btn').addEventListener('click', clickResults);\n\n"} {"doc_id": "3583908c5ff8d93fddeccf448e73da75", "text": "//--------------Estrat\u00e9gias de Cria\u00e7\u00e3o de Objeto-------------//\n\n// Usando a nota\u00e7\u00e3o literal\n\nconst obj1 = {}\nconsole.log(obj1)\n// {}\n\n// Usando operador 'new' e 'Object'\n\nconsole.log(typeof Object, typeof new Object)// repare a diferen\u00e7a entre os dois\n// function object\nconst obj2 = new Object // 'new Object' \u00e9 fun\u00e7\u00e3o construtora\nconsole.log(obj2)\n// {}\n\n// Fun\u00e7\u00f5es construtoras\n\nfunction Produto(nome, preco, desc) { // estando entre () as vari\u00e1veis est\u00e3o encapsuladas\n this.nome = nome // tornando a vari\u00e1vel 'nome' p\u00fablica usando 'this'\n this.getPrecoComDesconto = () => {\n return preco * (1 - desc)\n }\n}\n\nconst p1 = new Produto('Caneta', 7.99, 0.15 )\nconst p2 = new Produto('Caderno', 16.99, 0.25)\n\nconsole.log(p1.getPrecoComDesconto(), p2.getPrecoComDesconto())\n// 6.7915 12.7425\n\n// Fun\u00e7\u00e3o Factory\n\nfunction criarFuncionario (nome, salarioBase, faltas) {\n return {\n nome,\n salarioBase,\n faltas,\n getSalario() {\n return (salarioBase / 30) * (30 - faltas)\n }\n }\n}\n\nconst f1 = criarFuncionario ('Jo\u00e3o', 2560, 4)\nconst f2 = criarFuncionario ('Maria', 2560, 1)\nconsole.log(f1.getSalario(), f2.getSalario() ) \n// 2218.6666666666665 2474.6666666666665\n\n// Object.create\n\nconst filha = Object.create(null) // na aula retorna apenas { nome: 'Ana' } ???\nfilha.nome = 'Ana'\nconsole.log(filha)\n// [Object: null prototype] { nome: 'Ana' } \n\n// Uma fun\u00e7\u00e3o famosa que retorna Objeto... 'JSON.parse'\n\nconst fromJSON = JSON.parse('{\"info\": \"Sou um JSON\"}')\nconsole.log(fromJSON.info) \n// Sou um JSON\n"} {"doc_id": "362bf13cd2e865a41a0ac83a8e31c3e0", "text": "function moda(lista){\n\n const listaCount = {};\n\n lista.map(\n function (elemento){ //aqui guardamos en el objeto listacount\n if(listaCount[elemento]){ //los elementos del array y las veces que\n listaCount[elemento] += 1; //se repiten\n }else{\n listaCount[elemento] = 1;\n }\n }\n );\n \n const listaArray = Object.entries(listaCount).sort( //aqui convertimos el objeto en array\n function(elementoA, elementoB){ //y lo ordenamos de mayor a menor de\n return elementoA[1] - elementoB[1]; //acuerdo a la cantidad que se repite\n }\n )\n\n return listaArray[listaArray.length - 1]; \n //aqui seleccionamos el valor que mas se repite y lo retornamos\n}\n\n\n//ejercicio---------------------\n\n/* const lista1 = [1, 2, 3, 4, 1, 1, 1, 2, 2, 3];\n\nconst lista1Count = {};\n\nlista1.map(\n function (elemento){\n if(lista1Count[elemento]){\n lista1Count[elemento] += 1;\n }else{\n lista1Count[elemento] = 1;\n }\n }\n);\n\nconst lista1Array = Object.entries(lista1Count).sort(\n function(elementoA, elementoB){\n return elementoA[1] - elementoB[1];\n}\n)\n\nconst moda = lista1Array[lista1Array.length - 1]; */"} {"doc_id": "36ac8836be23ca569cf29962ba1fee4f", "text": "/*\n

      We have two integer sequences A and B of the same non-zero length.

      \n\n

      We are allowed to swap elements A[i] and B[i].  Note that both elements are in the same index position in their respective sequences.

      \n\n

      At the end of some number of swaps, A and B are both strictly increasing.  (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.length - 1].)

      \n\n

      Given A and B, return the minimum number of swaps to make both sequences strictly increasing.  It is guaranteed that the given input always makes it possible.

      \n\n
      \nExample:\nInput: A = [1,3,5,4], B = [1,2,3,7]\nOutput: 1\nExplanation: \nSwap A[3] and B[3].  Then the sequences are:\nA = [1, 3, 5, 7] and B = [1, 2, 3, 4]\nwhich are both strictly increasing.\n
      \n\n

      Note:

      \n\n
        \n\t
      • A, B are arrays with the same length, and that length will be in the range [1, 1000].
      • \n\t
      • A[i], B[i] are integer values in the range [0, 2000].
      • \n

      \u6211\u4eec\u6709\u4e24\u4e2a\u957f\u5ea6\u76f8\u7b49\u4e14\u4e0d\u4e3a\u7a7a\u7684\u6574\u578b\u6570\u7ec4 A \u548c B \u3002

      \n\n

      \u6211\u4eec\u53ef\u4ee5\u4ea4\u6362 A[i] \u548c B[i] \u7684\u5143\u7d20\u3002\u6ce8\u610f\u8fd9\u4e24\u4e2a\u5143\u7d20\u5728\u5404\u81ea\u7684\u5e8f\u5217\u4e2d\u5e94\u8be5\u5904\u4e8e\u76f8\u540c\u7684\u4f4d\u7f6e\u3002

      \n\n

      \u5728\u4ea4\u6362\u8fc7\u4e00\u4e9b\u5143\u7d20\u4e4b\u540e\uff0c\u6570\u7ec4 A \u548c B \u90fd\u5e94\u8be5\u662f\u4e25\u683c\u9012\u589e\u7684\uff08\u6570\u7ec4\u4e25\u683c\u9012\u589e\u7684\u6761\u4ef6\u4ec5\u4e3aA[0] < A[1] < A[2] < ... < A[A.length - 1]\uff09\u3002

      \n\n

      \u7ed9\u5b9a\u6570\u7ec4 A \u548c B \uff0c\u8bf7\u8fd4\u56de\u4f7f\u5f97\u4e24\u4e2a\u6570\u7ec4\u5747\u4fdd\u6301\u4e25\u683c\u9012\u589e\u72b6\u6001\u7684\u6700\u5c0f\u4ea4\u6362\u6b21\u6570\u3002\u5047\u8bbe\u7ed9\u5b9a\u7684\u8f93\u5165\u603b\u662f\u6709\u6548\u7684\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165: A = [1,3,5,4], B = [1,2,3,7]\n\u8f93\u51fa: 1\n\u89e3\u91ca: \n\u4ea4\u6362 A[3] \u548c B[3] \u540e\uff0c\u4e24\u4e2a\u6570\u7ec4\u5982\u4e0b:\nA = [1, 3, 5, 7] \uff0c B = [1, 2, 3, 4]\n\u4e24\u4e2a\u6570\u7ec4\u5747\u4e3a\u4e25\u683c\u9012\u589e\u7684\u3002
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • A, B \u4e24\u4e2a\u6570\u7ec4\u7684\u957f\u5ea6\u603b\u662f\u76f8\u7b49\u7684\uff0c\u4e14\u957f\u5ea6\u7684\u8303\u56f4\u4e3a [1, 1000]\u3002
      • \n\t
      • A[i], B[i] \u5747\u4e3a [0, 2000]\u533a\u95f4\u5185\u7684\u6574\u6570\u3002
      • \n
      \n

      \u6211\u4eec\u6709\u4e24\u4e2a\u957f\u5ea6\u76f8\u7b49\u4e14\u4e0d\u4e3a\u7a7a\u7684\u6574\u578b\u6570\u7ec4 A \u548c B \u3002

      \n\n

      \u6211\u4eec\u53ef\u4ee5\u4ea4\u6362 A[i] \u548c B[i] \u7684\u5143\u7d20\u3002\u6ce8\u610f\u8fd9\u4e24\u4e2a\u5143\u7d20\u5728\u5404\u81ea\u7684\u5e8f\u5217\u4e2d\u5e94\u8be5\u5904\u4e8e\u76f8\u540c\u7684\u4f4d\u7f6e\u3002

      \n\n

      \u5728\u4ea4\u6362\u8fc7\u4e00\u4e9b\u5143\u7d20\u4e4b\u540e\uff0c\u6570\u7ec4 A \u548c B \u90fd\u5e94\u8be5\u662f\u4e25\u683c\u9012\u589e\u7684\uff08\u6570\u7ec4\u4e25\u683c\u9012\u589e\u7684\u6761\u4ef6\u4ec5\u4e3aA[0] < A[1] < A[2] < ... < A[A.length - 1]\uff09\u3002

      \n\n

      \u7ed9\u5b9a\u6570\u7ec4 A \u548c B \uff0c\u8bf7\u8fd4\u56de\u4f7f\u5f97\u4e24\u4e2a\u6570\u7ec4\u5747\u4fdd\u6301\u4e25\u683c\u9012\u589e\u72b6\u6001\u7684\u6700\u5c0f\u4ea4\u6362\u6b21\u6570\u3002\u5047\u8bbe\u7ed9\u5b9a\u7684\u8f93\u5165\u603b\u662f\u6709\u6548\u7684\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165: A = [1,3,5,4], B = [1,2,3,7]\n\u8f93\u51fa: 1\n\u89e3\u91ca: \n\u4ea4\u6362 A[3] \u548c B[3] \u540e\uff0c\u4e24\u4e2a\u6570\u7ec4\u5982\u4e0b:\nA = [1, 3, 5, 7] \uff0c B = [1, 2, 3, 4]\n\u4e24\u4e2a\u6570\u7ec4\u5747\u4e3a\u4e25\u683c\u9012\u589e\u7684\u3002
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • A, B \u4e24\u4e2a\u6570\u7ec4\u7684\u957f\u5ea6\u603b\u662f\u76f8\u7b49\u7684\uff0c\u4e14\u957f\u5ea6\u7684\u8303\u56f4\u4e3a [1, 1000]\u3002
      • \n\t
      • A[i], B[i] \u5747\u4e3a [0, 2000]\u533a\u95f4\u5185\u7684\u6574\u6570\u3002
      • \n
      \n*/\n\n\n/**\n * @param {number[]} A\n * @param {number[]} B\n * @return {number}\n */\nvar minSwap = function(A, B) {\n \n};"} {"doc_id": "37603c7b0ddefc29167de0f45858976f", "text": "/*\n

      Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.\n

      \n\n

      Note:
      \n

        \n
      • The length of num is less than 10002 and will be ≥ k.
      • \n
      • The given num does not contain any leading zero.
      • \n
      \n\n

      \n\n

      Example 1:\n

      \nInput: num = \"1432219\", k = 3\nOutput: \"1219\"\nExplanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.\n
      \n

      \n\n

      Example 2:\n

      \nInput: num = \"10200\", k = 1\nOutput: \"200\"\nExplanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.\n
      \n

      \n\n

      Example 3:\n

      \nInput: num = \"10\", k = 2\nOutput: \"0\"\nExplanation: Remove all the digits from the number and it is left with nothing which is 0.\n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u4ee5\u5b57\u7b26\u4e32\u8868\u793a\u7684\u975e\u8d1f\u6574\u6570 num\uff0c\u79fb\u9664\u8fd9\u4e2a\u6570\u4e2d\u7684 k \u4f4d\u6570\u5b57\uff0c\u4f7f\u5f97\u5269\u4e0b\u7684\u6570\u5b57\u6700\u5c0f\u3002

      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • num \u7684\u957f\u5ea6\u5c0f\u4e8e 10002 \u4e14 ≥ k\u3002
      • \n\t
      • num \u4e0d\u4f1a\u5305\u542b\u4efb\u4f55\u524d\u5bfc\u96f6\u3002
      • \n
      \n\n

      \u793a\u4f8b 1 :

      \n\n
      \n\u8f93\u5165: num = "1432219", k = 3\n\u8f93\u51fa: "1219"\n\u89e3\u91ca: \u79fb\u9664\u6389\u4e09\u4e2a\u6570\u5b57 4, 3, \u548c 2 \u5f62\u6210\u4e00\u4e2a\u65b0\u7684\u6700\u5c0f\u7684\u6570\u5b57 1219\u3002\n
      \n\n

      \u793a\u4f8b 2 :

      \n\n
      \n\u8f93\u5165: num = "10200", k = 1\n\u8f93\u51fa: "200"\n\u89e3\u91ca: \u79fb\u6389\u9996\u4f4d\u7684 1 \u5269\u4e0b\u7684\u6570\u5b57\u4e3a 200. \u6ce8\u610f\u8f93\u51fa\u4e0d\u80fd\u6709\u4efb\u4f55\u524d\u5bfc\u96f6\u3002\n
      \n\n

      \u793a\u4f8b 3 :

      \n\n
      \n\u8f93\u5165: num = "10", k = 2\n\u8f93\u51fa: "0"\n\u89e3\u91ca: \u4ece\u539f\u6570\u5b57\u79fb\u9664\u6240\u6709\u7684\u6570\u5b57\uff0c\u5269\u4f59\u4e3a\u7a7a\u5c31\u662f0\u3002\n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u4ee5\u5b57\u7b26\u4e32\u8868\u793a\u7684\u975e\u8d1f\u6574\u6570 num\uff0c\u79fb\u9664\u8fd9\u4e2a\u6570\u4e2d\u7684 k \u4f4d\u6570\u5b57\uff0c\u4f7f\u5f97\u5269\u4e0b\u7684\u6570\u5b57\u6700\u5c0f\u3002

      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • num \u7684\u957f\u5ea6\u5c0f\u4e8e 10002 \u4e14 ≥ k\u3002
      • \n\t
      • num \u4e0d\u4f1a\u5305\u542b\u4efb\u4f55\u524d\u5bfc\u96f6\u3002
      • \n
      \n\n

      \u793a\u4f8b 1 :

      \n\n
      \n\u8f93\u5165: num = "1432219", k = 3\n\u8f93\u51fa: "1219"\n\u89e3\u91ca: \u79fb\u9664\u6389\u4e09\u4e2a\u6570\u5b57 4, 3, \u548c 2 \u5f62\u6210\u4e00\u4e2a\u65b0\u7684\u6700\u5c0f\u7684\u6570\u5b57 1219\u3002\n
      \n\n

      \u793a\u4f8b 2 :

      \n\n
      \n\u8f93\u5165: num = "10200", k = 1\n\u8f93\u51fa: "200"\n\u89e3\u91ca: \u79fb\u6389\u9996\u4f4d\u7684 1 \u5269\u4e0b\u7684\u6570\u5b57\u4e3a 200. \u6ce8\u610f\u8f93\u51fa\u4e0d\u80fd\u6709\u4efb\u4f55\u524d\u5bfc\u96f6\u3002\n
      \n\n

      \u793a\u4f8b 3 :

      \n\n
      \n\u8f93\u5165: num = "10", k = 2\n\u8f93\u51fa: "0"\n\u89e3\u91ca: \u4ece\u539f\u6570\u5b57\u79fb\u9664\u6240\u6709\u7684\u6570\u5b57\uff0c\u5269\u4f59\u4e3a\u7a7a\u5c31\u662f0\u3002\n
      \n*/\n\n\n/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n */\nvar removeKdigits = function(num, k) {\n \n};"} {"doc_id": "377cdde18ed4c6d2abb1fe93bb062385", "text": "/*\n

      Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:

      \n\n
        \n\t
      • B.length >= 3
      • \n\t
      • There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
      • \n
      \n\n

      (Note that B could be any subarray of A, including the entire array A.)

      \n\n

      Given an array A of integers, return the length of the longest mountain. 

      \n\n

      Return 0 if there is no mountain.

      \n\n

       

      \n\n

      Example 1:

      \n\n
      \nInput: [2,1,4,7,3,2,5]\nOutput: 5\nExplanation: The largest mountain is [1,4,7,3,2] which has length 5.\n
      \n\n

      Example 2:

      \n\n
      \nInput: [2,2,2]\nOutput: 0\nExplanation: There is no mountain.\n
      \n\n

       

      \n\n

      Note:

      \n\n
        \n\t
      1. 0 <= A.length <= 10000
      2. \n\t
      3. 0 <= A[i] <= 10000
      4. \n

      \u6211\u4eec\u628a\u6570\u7ec4 A \u4e2d\u7b26\u5408\u4e0b\u5217\u5c5e\u6027\u7684\u4efb\u610f\u8fde\u7eed\u5b50\u6570\u7ec4 B \u79f0\u4e3a “\u5c71\u8109”\uff1a

      \n\n
        \n\t
      • B.length >= 3
      • \n\t
      • \u5b58\u5728 0 < i < B.length - 1 \u4f7f\u5f97 B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
      • \n
      \n\n

      \uff08\u6ce8\u610f\uff1aB \u53ef\u4ee5\u662f A \u7684\u4efb\u610f\u5b50\u6570\u7ec4\uff0c\u5305\u62ec\u6574\u4e2a\u6570\u7ec4 A\u3002\uff09

      \n\n

      \u7ed9\u51fa\u4e00\u4e2a\u6574\u6570\u6570\u7ec4 A\uff0c\u8fd4\u56de\u6700\u957f “\u5c71\u8109” \u7684\u957f\u5ea6\u3002

      \n\n

      \u5982\u679c\u4e0d\u542b\u6709 “\u5c71\u8109” \u5219\u8fd4\u56de 0\u3002

      \n\n

       

      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \u8f93\u5165\uff1a[2,1,4,7,3,2,5]\n\u8f93\u51fa\uff1a5\n\u89e3\u91ca\uff1a\u6700\u957f\u7684 “\u5c71\u8109” \u662f [1,4,7,3,2]\uff0c\u957f\u5ea6\u4e3a 5\u3002\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \u8f93\u5165\uff1a[2,2,2]\n\u8f93\u51fa\uff1a0\n\u89e3\u91ca\uff1a\u4e0d\u542b “\u5c71\u8109”\u3002\n
      \n\n

       

      \n\n

      \u63d0\u793a\uff1a

      \n\n
        \n\t
      1. 0 <= A.length <= 10000
      2. \n\t
      3. 0 <= A[i] <= 10000
      4. \n
      \n

      \u6211\u4eec\u628a\u6570\u7ec4 A \u4e2d\u7b26\u5408\u4e0b\u5217\u5c5e\u6027\u7684\u4efb\u610f\u8fde\u7eed\u5b50\u6570\u7ec4 B \u79f0\u4e3a “\u5c71\u8109”\uff1a

      \n\n
        \n\t
      • B.length >= 3
      • \n\t
      • \u5b58\u5728 0 < i < B.length - 1 \u4f7f\u5f97 B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
      • \n
      \n\n

      \uff08\u6ce8\u610f\uff1aB \u53ef\u4ee5\u662f A \u7684\u4efb\u610f\u5b50\u6570\u7ec4\uff0c\u5305\u62ec\u6574\u4e2a\u6570\u7ec4 A\u3002\uff09

      \n\n

      \u7ed9\u51fa\u4e00\u4e2a\u6574\u6570\u6570\u7ec4 A\uff0c\u8fd4\u56de\u6700\u957f “\u5c71\u8109” \u7684\u957f\u5ea6\u3002

      \n\n

      \u5982\u679c\u4e0d\u542b\u6709 “\u5c71\u8109” \u5219\u8fd4\u56de 0\u3002

      \n\n

       

      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \u8f93\u5165\uff1a[2,1,4,7,3,2,5]\n\u8f93\u51fa\uff1a5\n\u89e3\u91ca\uff1a\u6700\u957f\u7684 “\u5c71\u8109” \u662f [1,4,7,3,2]\uff0c\u957f\u5ea6\u4e3a 5\u3002\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \u8f93\u5165\uff1a[2,2,2]\n\u8f93\u51fa\uff1a0\n\u89e3\u91ca\uff1a\u4e0d\u542b “\u5c71\u8109”\u3002\n
      \n\n

       

      \n\n

      \u63d0\u793a\uff1a

      \n\n
        \n\t
      1. 0 <= A.length <= 10000
      2. \n\t
      3. 0 <= A[i] <= 10000
      4. \n
      \n*/\n\n\n/**\n * @param {number[]} A\n * @return {number}\n */\nvar longestMountain = function(A) {\n \n};"} {"doc_id": "387ff1835bb0a1008daa9f7ae2fad739", "text": "\"use strict\";\n(function() {\n/*\n * name: addFour(argument1)\n * argument1: a numeric value\n * description: Adds 4 to the value passed as argument1\n * returns: a sum of argument1 and 4\n */\n var addFour = function(value) {\n if (parseInt(value, 10) === \"NaN\") {\n console.log(\"Error non-numeric value '\" + value, + \"' passed to addFour function\");\n return \"NaN\";\n }\n return value + 4;\n };\n\n/*\n * name: addTen(argument1)\n * argument1: a numeric value\n * description: Adds 10 to the value passed as argument1\n * returns: a sum of argument1 and 10\n */\n var addTen = function(value) {\n if (typeof value != \"number\") {\n console.log(\"Error: non-numeric value '\" + value + \"' passed to addTen function\");\n return \"NaN\";\n }\n return value + 10;\n };\n\n /*\n * Start of grid.js \n */\n console.log(\"This is grid.js\");\n\n if (addFour(4) != 8) {\n alert(\"Major Error: 4 + 4 did not equal 8\");\n } \n\n if (addTen(\"X\") != \"NaN\") {\n alert(\"Major Error: Added 10 to a non-numeric value\");\n }\n})();"} {"doc_id": "38c0d1499df6d3f291de6cb8cdb5c004", "text": "/*\n

      Given an array of integers nums, write a method that returns the \"pivot\" index of this array.\n

      \nWe define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.\n

      \nIf no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.\n

      \n\n

      Example 1:
      \n

      \nInput: \nnums = [1, 7, 3, 6, 5, 6]\nOutput: 3\nExplanation: \nThe sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.\nAlso, 3 is the first index where this occurs.\n
      \n

      \n\n

      Example 2:
      \n

      \nInput: \nnums = [1, 2, 3]\nOutput: -1\nExplanation: \nThere is no index that satisfies the conditions in the problem statement.\n
      \n

      \n\n

      Note:\n

    3. The length of nums will be in the range [0, 10000].
    4. \n
    5. Each element nums[i] will be an integer in the range [-1000, 1000].
    6. \n

      \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u7c7b\u578b\u7684\u6570\u7ec4 nums\uff0c\u8bf7\u7f16\u5199\u4e00\u4e2a\u80fd\u591f\u8fd4\u56de\u6570\u7ec4“\u4e2d\u5fc3\u7d22\u5f15”\u7684\u65b9\u6cd5\u3002

      \n\n

      \u6211\u4eec\u662f\u8fd9\u6837\u5b9a\u4e49\u6570\u7ec4\u4e2d\u5fc3\u7d22\u5f15\u7684\uff1a\u6570\u7ec4\u4e2d\u5fc3\u7d22\u5f15\u7684\u5de6\u4fa7\u6240\u6709\u5143\u7d20\u76f8\u52a0\u7684\u548c\u7b49\u4e8e\u53f3\u4fa7\u6240\u6709\u5143\u7d20\u76f8\u52a0\u7684\u548c\u3002

      \n\n

      \u5982\u679c\u6570\u7ec4\u4e0d\u5b58\u5728\u4e2d\u5fc3\u7d22\u5f15\uff0c\u90a3\u4e48\u6211\u4eec\u5e94\u8be5\u8fd4\u56de -1\u3002\u5982\u679c\u6570\u7ec4\u6709\u591a\u4e2a\u4e2d\u5fc3\u7d22\u5f15\uff0c\u90a3\u4e48\u6211\u4eec\u5e94\u8be5\u8fd4\u56de\u6700\u9760\u8fd1\u5de6\u8fb9\u7684\u90a3\u4e00\u4e2a\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: \nnums = [1, 7, 3, 6, 5, 6]\n\u8f93\u51fa: 3\n\u89e3\u91ca: \n\u7d22\u5f153 (nums[3] = 6) \u7684\u5de6\u4fa7\u6570\u4e4b\u548c(1 + 7 + 3 = 11)\uff0c\u4e0e\u53f3\u4fa7\u6570\u4e4b\u548c(5 + 6 = 11)\u76f8\u7b49\u3002\n\u540c\u65f6, 3 \u4e5f\u662f\u7b2c\u4e00\u4e2a\u7b26\u5408\u8981\u6c42\u7684\u4e2d\u5fc3\u7d22\u5f15\u3002\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165: \nnums = [1, 2, 3]\n\u8f93\u51fa: -1\n\u89e3\u91ca: \n\u6570\u7ec4\u4e2d\u4e0d\u5b58\u5728\u6ee1\u8db3\u6b64\u6761\u4ef6\u7684\u4e2d\u5fc3\u7d22\u5f15\u3002
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      • nums \u7684\u957f\u5ea6\u8303\u56f4\u4e3a [0, 10000]\u3002
      • \n\t
      • \u4efb\u4f55\u4e00\u4e2a nums[i] \u5c06\u4f1a\u662f\u4e00\u4e2a\u8303\u56f4\u5728 [-1000, 1000]\u7684\u6574\u6570\u3002
      • \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u7c7b\u578b\u7684\u6570\u7ec4 nums\uff0c\u8bf7\u7f16\u5199\u4e00\u4e2a\u80fd\u591f\u8fd4\u56de\u6570\u7ec4“\u4e2d\u5fc3\u7d22\u5f15”\u7684\u65b9\u6cd5\u3002

      \n\n

      \u6211\u4eec\u662f\u8fd9\u6837\u5b9a\u4e49\u6570\u7ec4\u4e2d\u5fc3\u7d22\u5f15\u7684\uff1a\u6570\u7ec4\u4e2d\u5fc3\u7d22\u5f15\u7684\u5de6\u4fa7\u6240\u6709\u5143\u7d20\u76f8\u52a0\u7684\u548c\u7b49\u4e8e\u53f3\u4fa7\u6240\u6709\u5143\u7d20\u76f8\u52a0\u7684\u548c\u3002

      \n\n

      \u5982\u679c\u6570\u7ec4\u4e0d\u5b58\u5728\u4e2d\u5fc3\u7d22\u5f15\uff0c\u90a3\u4e48\u6211\u4eec\u5e94\u8be5\u8fd4\u56de -1\u3002\u5982\u679c\u6570\u7ec4\u6709\u591a\u4e2a\u4e2d\u5fc3\u7d22\u5f15\uff0c\u90a3\u4e48\u6211\u4eec\u5e94\u8be5\u8fd4\u56de\u6700\u9760\u8fd1\u5de6\u8fb9\u7684\u90a3\u4e00\u4e2a\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: \nnums = [1, 7, 3, 6, 5, 6]\n\u8f93\u51fa: 3\n\u89e3\u91ca: \n\u7d22\u5f153 (nums[3] = 6) \u7684\u5de6\u4fa7\u6570\u4e4b\u548c(1 + 7 + 3 = 11)\uff0c\u4e0e\u53f3\u4fa7\u6570\u4e4b\u548c(5 + 6 = 11)\u76f8\u7b49\u3002\n\u540c\u65f6, 3 \u4e5f\u662f\u7b2c\u4e00\u4e2a\u7b26\u5408\u8981\u6c42\u7684\u4e2d\u5fc3\u7d22\u5f15\u3002\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165: \nnums = [1, 2, 3]\n\u8f93\u51fa: -1\n\u89e3\u91ca: \n\u6570\u7ec4\u4e2d\u4e0d\u5b58\u5728\u6ee1\u8db3\u6b64\u6761\u4ef6\u7684\u4e2d\u5fc3\u7d22\u5f15\u3002
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      • nums \u7684\u957f\u5ea6\u8303\u56f4\u4e3a [0, 10000]\u3002
      • \n\t
      • \u4efb\u4f55\u4e00\u4e2a nums[i] \u5c06\u4f1a\u662f\u4e00\u4e2a\u8303\u56f4\u5728 [-1000, 1000]\u7684\u6574\u6570\u3002
      • \n
      \n*/\n\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar pivotIndex = function(nums) {\n \n};"} {"doc_id": "3912808ab13b0b6f4928888f847db7c3", "text": "//@ts-check\r\nconst Vector2 = require('./Vector2')\r\n\r\n/** \r\n * A class representing a line.\r\n * \r\n * @property {Vector2} from The Vector2 defining the start of the line.\r\n * @property {Vector2} to The Vector2 defining the end of the line.\r\n * @property {String} elementFrom The element symbol associated with the start of the line.\r\n * @property {String} elementTo The element symbol associated with the end of the line.\r\n * @property {Boolean} chiralFrom A boolean indicating whether or not the source atom is a chiral center.\r\n * @property {Boolean} chiralTo A boolean indicating whether or tno the target atom is a chiral center.\r\n */\r\nclass Line {\r\n /**\r\n * The constructor for the class Line.\r\n *\r\n * @param {Vector2} [from=new Vector2(0, 0)] A vector marking the beginning of the line.\r\n * @param {Vector2} [to=new Vector2(0, 0)] A vector marking the end of the line.\r\n * @param {string} [elementFrom=null] A one-letter representation of the element associated with the vector marking the beginning of the line.\r\n * @param {string} [elementTo=null] A one-letter representation of the element associated with the vector marking the end of the line.\r\n * @param {Boolean} [chiralFrom=false] Whether or not the from atom is a chiral center.\r\n * @param {Boolean} [chiralTo=false] Whether or not the to atom is a chiral center.\r\n * @param {Boolean} [isDecayPoint=false] Whether or not the edge is a decay point\r\n */\r\n constructor(from = new Vector2(0,0), to = new Vector2(0, 0), elementFrom = null, elementTo = null, chiralFrom = false, chiralTo = false, isDecayPoint = false) {\r\n this.from = from;\r\n this.to = to;\r\n this.elementFrom = elementFrom;\r\n this.elementTo = elementTo;\r\n this.chiralFrom = chiralFrom;\r\n this.chiralTo = chiralTo;\r\n this.isDecayPoint = isDecayPoint;\r\n }\r\n\r\n /**\r\n * Clones this line and returns the clone.\r\n *\r\n * @returns {Line} A clone of this line.\r\n */\r\n clone() {\r\n return new Line(this.from.clone(), this.to.clone(), this.elementFrom, this.elementTo);\r\n }\r\n\r\n /**\r\n * Returns the length of this line.\r\n *\r\n * @returns {Number} The length of this line.\r\n */\r\n getLength() {\r\n return Math.sqrt(Math.pow(this.to.x - this.from.x, 2) + \r\n Math.pow(this.to.y - this.from.y, 2));\r\n }\r\n\r\n\r\n /**\r\n * Returns the angle of the line in relation to the coordinate system (the x-axis).\r\n *\r\n * @returns {Number} The angle in radians.\r\n */\r\n getAngle() {\r\n // Get the angle between the line and the x-axis\r\n let diff = Vector2.subtract(this.getRightVector(), this.getLeftVector());\r\n return diff.angle();\r\n }\r\n\r\n /**\r\n * Returns the right vector (the vector with the larger x value).\r\n *\r\n * @returns {Vector2} The right vector.\r\n */\r\n getRightVector() {\r\n // Return the vector with the larger x value (the right one)\r\n if (this.from.x < this.to.x) {\r\n return this.to;\r\n } else {\r\n return this.from;\r\n }\r\n }\r\n \r\n /**\r\n * Returns the left vector (the vector with the smaller x value).\r\n *\r\n * @returns {Vector2} The left vector.\r\n */\r\n getLeftVector() {\r\n // Return the vector with the smaller x value (the left one)\r\n if (this.from.x < this.to.x) {\r\n return this.from;\r\n } else {\r\n return this.to;\r\n }\r\n }\r\n\r\n /**\r\n * Returns the element associated with the right vector (the vector with the larger x value).\r\n *\r\n * @returns {String} The element associated with the right vector.\r\n */\r\n getRightElement() {\r\n if (this.from.x < this.to.x) {\r\n return this.elementTo;\r\n } else {\r\n return this.elementFrom;\r\n }\r\n }\r\n\r\n /**\r\n * Returns the element associated with the left vector (the vector with the smaller x value).\r\n *\r\n * @returns {String} The element associated with the left vector.\r\n */\r\n getLeftElement() {\r\n if (this.from.x < this.to.x) {\r\n return this.elementFrom;\r\n } else {\r\n return this.elementTo;\r\n }\r\n }\r\n\r\n /**\r\n * Returns whether or not the atom associated with the right vector (the vector with the larger x value) is a chiral center.\r\n *\r\n * @returns {Boolean} Whether or not the atom associated with the right vector is a chiral center.\r\n */\r\n getRightChiral() {\r\n if (this.from.x < this.to.x) {\r\n return this.chiralTo;\r\n } else {\r\n return this.chiralFrom;\r\n }\r\n }\r\n\r\n /**\r\n * Returns whether or not the atom associated with the left vector (the vector with the smaller x value) is a chiral center.\r\n *\r\n * @returns {Boolean} Whether or not the atom associated with the left vector is a chiral center.\r\n */\r\n getLeftChiral() {\r\n if (this.from.x < this.to.x) {\r\n return this.chiralFrom;\r\n } else {\r\n return this.chiralTo;\r\n }\r\n }\r\n\r\n /**\r\n * Set the value of the right vector.\r\n *\r\n * @param {Number} x The x value.\r\n * @param {Number} y The y value.\r\n * @returns {Line} This line.\r\n */\r\n setRightVector(x, y) {\r\n if (this.from.x < this.to.x) {\r\n this.to.x = x;\r\n this.to.y = y;\r\n } else {\r\n this.from.x = x;\r\n this.from.y = y;\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the value of the left vector.\r\n *\r\n * @param {Number} x The x value.\r\n * @param {Number} y The y value.\r\n * @returns {Line} This line.\r\n */\r\n setLeftVector(x, y) {\r\n if (this.from.x < this.to.x) {\r\n this.from.x = x;\r\n this.from.y = y;\r\n } else {\r\n this.to.x = x;\r\n this.to.y = y;\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Rotates this line to be aligned with the x-axis. The center of rotation is the left vector.\r\n *\r\n * @returns {Line} This line.\r\n */\r\n rotateToXAxis() {\r\n let left = this.getLeftVector();\r\n \r\n this.setRightVector(left.x + this.getLength(), left.y);\r\n \r\n return this;\r\n }\r\n\r\n /**\r\n * Rotate the line by a given value (in radians). The center of rotation is the left vector.\r\n *\r\n * @param {Number} theta The angle (in radians) to rotate the line.\r\n * @returns {Line} This line.\r\n */\r\n rotate(theta) {\r\n let l = this.getLeftVector();\r\n let r = this.getRightVector();\r\n let sinTheta = Math.sin(theta);\r\n let cosTheta = Math.cos(theta);\r\n\r\n let x = cosTheta * (r.x - l.x) - sinTheta * (r.y - l.y) + l.x;\r\n let y = sinTheta * (r.x - l.x) - cosTheta * (r.y - l.y) + l.y;\r\n \r\n this.setRightVector(x, y);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Shortens this line from the \"from\" direction by a given value (in pixels).\r\n *\r\n * @param {Number} by The length in pixels to shorten the vector by.\r\n * @returns {Line} This line.\r\n */\r\n shortenFrom(by) {\r\n let f = Vector2.subtract(this.to, this.from);\r\n \r\n f.normalize();\r\n f.multiplyScalar(by);\r\n \r\n this.from.add(f);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Shortens this line from the \"to\" direction by a given value (in pixels).\r\n *\r\n * @param {Number} by The length in pixels to shorten the vector by.\r\n * @returns {Line} This line.\r\n */\r\n shortenTo(by) {\r\n let f = Vector2.subtract(this.from, this.to);\r\n \r\n f.normalize();\r\n f.multiplyScalar(by);\r\n \r\n this.to.add(f);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Shorten the right side.\r\n *\r\n * @param {Number} by The length in pixels to shorten the vector by.\r\n * @returns {Line} Returns itself.\r\n */\r\n shortenRight(by) {\r\n if (this.from.x < this.to.x) {\r\n this.shortenTo(by);\r\n } else {\r\n this.shortenFrom(by);\r\n }\r\n\r\n return this;\r\n }\r\n \r\n /**\r\n * Shorten the left side.\r\n * \r\n * @param {Number} by The length in pixels to shorten the vector by.\r\n * @returns {Line} Returns itself.\r\n */\r\n shortenLeft(by) {\r\n if (this.from.x < this.to.x) {\r\n this.shortenFrom(by);\r\n } else {\r\n this.shortenTo(by);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Shortens this line from both directions by a given value (in pixels).\r\n *\r\n * @param {Number} by The length in pixels to shorten the vector by.\r\n * @returns {Line} This line.\r\n */\r\n shorten(by) {\r\n let f = Vector2.subtract(this.from, this.to);\r\n \r\n f.normalize();\r\n f.multiplyScalar(by / 2.0);\r\n \r\n this.to.add(f);\r\n this.from.subtract(f);\r\n\r\n return this;\r\n }\r\n}\r\n\r\nmodule.exports = Line;"} {"doc_id": "394284f30a4e49d0a084f3251b852d66", "text": "var todos = ['item 1', 'item 2', 'item 3'];\n\n//It should have a function to display todos\nfunction displayTodos() {\n console.log('My todos:', todos);\n}\n// It should have a function to add todos\nfunction addTodos(todo) { //addTodos('newTodo')\n todos.push(todo);\n displayTodos();\n}\n// It should have a function to change todos\nfunction changeTodos(position, newValue) {\n todos[position] = newValue;\n displayTodos();\n}\n// It should have a function to delete todos\nfunction deleteTodos(position) {\n todos.splice(position, 1);\n displayTodos();\n}\n\nvar myName = 'Solomon';\n\nfunction sayName() {\n var secret = 'learnwebdevelopment';\n console.log(myName);\n}\n\nsayName() // 'Solomon'\nconsole.log(secret)\n// if you are inside of a function, you can look out and see data\n// but the opposite is not true. If you're outside, you can't look in.\n\n// Objects\n\nvar myComputer = {\n operatingSystem: 'Window',\n screenSize: '15 inches',\n purchasedYear: '2016',\n memorySize: '8Gb',\n hardDriveSize: '512Gb',\n processsorType: 'Intel i7'\n}\n//Relationships between functions and objects\nvar solomon = {\n name: 'Solomon',\n sayName: function() {\n console.log(this.name) \n }\n}\n// working with list, objects and functions\n\nvar todoList = {\n todos: ['item 1', 'item 2', 'item 3'],\n displayTodos: function() {\n console.log('My todo: ', this.todos)\n },\n addTodos: function(todo) {\n this.todos.push(todo)\n this.displayTodos()\n },\n changeTodos: function(position, newValue) {\n this.todos[position] = newValue\n this.displayTodos()\n },\n deleteTodos: function(position) {\n this.todos.splice(position, 1)\n this.displayTodos()\n }\n}\n\n//version5 working with loops and logic\n\nvar todoList = {\n todos: [],\n displayTodos: function() {\n console.log('My Todos: ', this.todos)\n },\n addTodos: function(todoText) {\n this.todos.push({\n todoText: todoText,\n completed: false\n })\n this.displayTodos() \n //todoList.addTodos('This is a todo')\n },\n changeTodos: function(position, todoText) {\n this.todos[position].todoText = todoText\n this.displayTodos()\n },\n toggleTodos: function(position) {\n var todo = this.todos[position]\n todo.completed = !todo.completed\n this.displayTodos()\n }\n}\n"} {"doc_id": "398c5186ce6000fb978f810de4c861cf", "text": "/*\n

      We are playing the Guess Game. The game is as follows:

      \n\n

      I pick a number from 1 to n. You have to guess which number I picked.

      \n\n

      Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.

      \n\n

      However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

      \n\n

      \nExample:\n

      \nn = 10, I pick 8.\n\nFirst round:  You guess 5, I tell you that it's higher. You pay $5.\nSecond round: You guess 7, I tell you that it's higher. You pay $7.\nThird round:  You guess 9, I tell you that it's lower. You pay $9.\n\nGame over. 8 is the number I picked.\n\nYou end up paying $5 + $7 + $9 = $21.\n
      \n

      \n\n

      Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.

      \n\n

      Credits:
      Special thanks to @agave and @StefanPochmann for adding this problem and creating all test cases.

      \u6211\u4eec\u6b63\u5728\u73a9\u4e00\u4e2a\u731c\u6570\u6e38\u620f\uff0c\u6e38\u620f\u89c4\u5219\u5982\u4e0b\uff1a

      \n\n

      \u6211\u4ece 1 \u5230 n \u4e4b\u95f4\u9009\u62e9\u4e00\u4e2a\u6570\u5b57\uff0c\u4f60\u6765\u731c\u6211\u9009\u4e86\u54ea\u4e2a\u6570\u5b57\u3002

      \n\n

      \u6bcf\u6b21\u4f60\u731c\u9519\u4e86\uff0c\u6211\u90fd\u4f1a\u544a\u8bc9\u4f60\uff0c\u6211\u9009\u7684\u6570\u5b57\u6bd4\u4f60\u7684\u5927\u4e86\u6216\u8005\u5c0f\u4e86\u3002

      \n\n

      \u7136\u800c\uff0c\u5f53\u4f60\u731c\u4e86\u6570\u5b57 x \u5e76\u4e14\u731c\u9519\u4e86\u7684\u65f6\u5019\uff0c\u4f60\u9700\u8981\u652f\u4ed8\u91d1\u989d\u4e3a x \u7684\u73b0\u91d1\u3002\u76f4\u5230\u4f60\u731c\u5230\u6211\u9009\u7684\u6570\u5b57\uff0c\u4f60\u624d\u7b97\u8d62\u5f97\u4e86\u8fd9\u4e2a\u6e38\u620f\u3002

      \n\n

      \u793a\u4f8b:

      \n\n
      \nn = 10, \u6211\u9009\u62e9\u4e868.\n\n\u7b2c\u4e00\u8f6e: \u4f60\u731c\u6211\u9009\u62e9\u7684\u6570\u5b57\u662f5\uff0c\u6211\u4f1a\u544a\u8bc9\u4f60\uff0c\u6211\u7684\u6570\u5b57\u66f4\u5927\u4e00\u4e9b\uff0c\u7136\u540e\u4f60\u9700\u8981\u652f\u4ed85\u5757\u3002\n\u7b2c\u4e8c\u8f6e: \u4f60\u731c\u662f7\uff0c\u6211\u544a\u8bc9\u4f60\uff0c\u6211\u7684\u6570\u5b57\u66f4\u5927\u4e00\u4e9b\uff0c\u4f60\u652f\u4ed87\u5757\u3002\n\u7b2c\u4e09\u8f6e: \u4f60\u731c\u662f9\uff0c\u6211\u544a\u8bc9\u4f60\uff0c\u6211\u7684\u6570\u5b57\u66f4\u5c0f\u4e00\u4e9b\uff0c\u4f60\u652f\u4ed89\u5757\u3002\n\n\u6e38\u620f\u7ed3\u675f\u30028 \u5c31\u662f\u6211\u9009\u7684\u6570\u5b57\u3002\n\n\u4f60\u6700\u7ec8\u8981\u652f\u4ed8 5 + 7 + 9 = 21 \u5757\u94b1\u3002\n
      \n\n

      \u7ed9\u5b9a\u4e00\u4e2a n ≥ 1\uff0c\u8ba1\u7b97\u4f60\u81f3\u5c11\u9700\u8981\u62e5\u6709\u591a\u5c11\u73b0\u91d1\u624d\u80fd\u786e\u4fdd\u4f60\u80fd\u8d62\u5f97\u8fd9\u4e2a\u6e38\u620f\u3002

      \n\n

      \u81f4\u8c22:

      \n\n

      \u7279\u522b\u611f\u8c22 @agave \u548c @StefanPochmann \u6dfb\u52a0\u4e86\u8fd9\u9053\u9898\u76ee\uff0c\u5e76\u4e14\u63d0\u4f9b\u4e86\u6240\u6709\u6d4b\u8bd5\u7528\u4f8b\u3002

      \n

      \u6211\u4eec\u6b63\u5728\u73a9\u4e00\u4e2a\u731c\u6570\u6e38\u620f\uff0c\u6e38\u620f\u89c4\u5219\u5982\u4e0b\uff1a

      \n\n

      \u6211\u4ece 1 \u5230 n \u4e4b\u95f4\u9009\u62e9\u4e00\u4e2a\u6570\u5b57\uff0c\u4f60\u6765\u731c\u6211\u9009\u4e86\u54ea\u4e2a\u6570\u5b57\u3002

      \n\n

      \u6bcf\u6b21\u4f60\u731c\u9519\u4e86\uff0c\u6211\u90fd\u4f1a\u544a\u8bc9\u4f60\uff0c\u6211\u9009\u7684\u6570\u5b57\u6bd4\u4f60\u7684\u5927\u4e86\u6216\u8005\u5c0f\u4e86\u3002

      \n\n

      \u7136\u800c\uff0c\u5f53\u4f60\u731c\u4e86\u6570\u5b57 x \u5e76\u4e14\u731c\u9519\u4e86\u7684\u65f6\u5019\uff0c\u4f60\u9700\u8981\u652f\u4ed8\u91d1\u989d\u4e3a x \u7684\u73b0\u91d1\u3002\u76f4\u5230\u4f60\u731c\u5230\u6211\u9009\u7684\u6570\u5b57\uff0c\u4f60\u624d\u7b97\u8d62\u5f97\u4e86\u8fd9\u4e2a\u6e38\u620f\u3002

      \n\n

      \u793a\u4f8b:

      \n\n
      \nn = 10, \u6211\u9009\u62e9\u4e868.\n\n\u7b2c\u4e00\u8f6e: \u4f60\u731c\u6211\u9009\u62e9\u7684\u6570\u5b57\u662f5\uff0c\u6211\u4f1a\u544a\u8bc9\u4f60\uff0c\u6211\u7684\u6570\u5b57\u66f4\u5927\u4e00\u4e9b\uff0c\u7136\u540e\u4f60\u9700\u8981\u652f\u4ed85\u5757\u3002\n\u7b2c\u4e8c\u8f6e: \u4f60\u731c\u662f7\uff0c\u6211\u544a\u8bc9\u4f60\uff0c\u6211\u7684\u6570\u5b57\u66f4\u5927\u4e00\u4e9b\uff0c\u4f60\u652f\u4ed87\u5757\u3002\n\u7b2c\u4e09\u8f6e: \u4f60\u731c\u662f9\uff0c\u6211\u544a\u8bc9\u4f60\uff0c\u6211\u7684\u6570\u5b57\u66f4\u5c0f\u4e00\u4e9b\uff0c\u4f60\u652f\u4ed89\u5757\u3002\n\n\u6e38\u620f\u7ed3\u675f\u30028 \u5c31\u662f\u6211\u9009\u7684\u6570\u5b57\u3002\n\n\u4f60\u6700\u7ec8\u8981\u652f\u4ed8 5 + 7 + 9 = 21 \u5757\u94b1\u3002\n
      \n\n

      \u7ed9\u5b9a\u4e00\u4e2a n ≥ 1\uff0c\u8ba1\u7b97\u4f60\u81f3\u5c11\u9700\u8981\u62e5\u6709\u591a\u5c11\u73b0\u91d1\u624d\u80fd\u786e\u4fdd\u4f60\u80fd\u8d62\u5f97\u8fd9\u4e2a\u6e38\u620f\u3002

      \n\n

      \u81f4\u8c22:

      \n\n

      \u7279\u522b\u611f\u8c22 @agave \u548c @StefanPochmann \u6dfb\u52a0\u4e86\u8fd9\u9053\u9898\u76ee\uff0c\u5e76\u4e14\u63d0\u4f9b\u4e86\u6240\u6709\u6d4b\u8bd5\u7528\u4f8b\u3002

      \n*/\n\n\n/**\n * @param {number} n\n * @return {number}\n */\nvar getMoneyAmount = function(n) {\n \n};"} {"doc_id": "39936ff2b5270fa7298dad87fb91cbd9", "text": "\"use strict\";\n/*\n * @Description: \u53cd\u8f6c\u5b57\u7b26\u4e32\n * @Author: Moriaty\n * @Date: 2020-09-01 20:34:56\n * @Last modified by: Moriaty\n * @LastEditTime: 2020-09-01 20:41:34\n */\n/**\n * \u8f93\u5165\uff1a[\"h\",\"e\",\"l\",\"l\",\"o\"]\n * \u8f93\u51fa\uff1a[\"o\",\"l\",\"l\",\"e\",\"h\"]\n *\n * \u6765\u6e90\uff1a\u529b\u6263\uff08LeetCode\uff09\n * \u94fe\u63a5\uff1ahttps://leetcode-cn.com/problems/reverse-string\n */\n/**\n * @description: \u7f16\u5199\u4e00\u4e2a\u51fd\u6570\uff0c\u5176\u4f5c\u7528\u662f\u5c06\u8f93\u5165\u7684\u5b57\u7b26\u4e32\u53cd\u8f6c\u8fc7\u6765\u3002\u8f93\u5165\u5b57\u7b26\u4e32\u4ee5\u5b57\u7b26\u6570\u7ec4 char[] \u7684\u5f62\u5f0f\u7ed9\u51fa\u3002\n * \u4e0d\u8981\u7ed9\u53e6\u5916\u7684\u6570\u7ec4\u5206\u914d\u989d\u5916\u7684\u7a7a\u95f4\uff0c\u4f60\u5fc5\u987b\u539f\u5730\u4fee\u6539\u8f93\u5165\u6570\u7ec4\u3001\u4f7f\u7528 O(1) \u7684\u989d\u5916\u7a7a\u95f4\u89e3\u51b3\u8fd9\u4e00\u95ee\u9898\u3002\n * \u4f60\u53ef\u4ee5\u5047\u8bbe\u6570\u7ec4\u4e2d\u7684\u6240\u6709\u5b57\u7b26\u90fd\u662f ASCII \u7801\u8868\u4e2d\u7684\u53ef\u6253\u5370\u5b57\u7b26\n * @param {string[]} s \u5b57\u7b26\u6570\u7ec4\n */\nfunction reverseString(s) {\n // \u5de6\u53f3\u58f0\u660e\u4e24\u6307\u9488\n let left = 0, right = s.length - 1;\n while (left < right) {\n [s[left], s[right]] = [s[right], s[left]];\n ++left;\n --right;\n }\n}\n;\nconsole.log(reverseString([\"h\", \"e\", \"l\", \"l\", \"o\"])); // [\"o\",\"l\",\"l\",\"e\",\"h\"]\n"} {"doc_id": "39a79d650e3f06cb5f2690ee36c6f5f7", "text": "/**\n * Declare a class BuildComputer \n * along with all its methods to help user \n * add different components and attributes \n * to the computer they are building\n */\n\nclass BuildComputer{\n\tconstructor(){\n\t\tthis.computer = {};\n\t}\n\n\t//add a name for the computer\n\taddName(name){ \n\t\tthis.computer.name = name;\n\t}\n\n\t//add a brand name\n\taddBrand(brand){ \n\t\tthis.computer.brand = brand;\n\t}\n\n\t// add memory capacity\n\taddMemory(capacity){ \n\t\tthis.computer.capacity = `${capacity} GB DDR4 RAM`;\n\t}\n\n\t// add display size \n\taddDisplay(length){ \n\t\tthis.computer.length = `${length}-inch`;\n\t}\n\n\t// add storage capacity\n\taddStorage(storageCapacity){ \n\t\tthis.computer.storageCapacity = `${storageCapacity} GB SSD`;\n\t}\n\n\t//add an address for shipping\n\taddShippingAddress(address){ \n\t\tthis.computer.shippingAddress = address;\n\t}\n\n\t// return the computer object for shipping\n\tshipComputer(){ \n\t\treturn this;\n\t}\n}\n\n\n//instantiate build class\nlet build = new BuildComputer(); \n\n//using build class we can add components to our computer\nbuild.addName('MacBook Pro');\nbuild.addBrand('Apple');\nbuild.addMemory(16);\nbuild.addDisplay(13.3);\nbuild.addStorage(250);\nbuild.addShippingAddress('Iris Watson P.O. Box 283 8562 Fusce Rd.');\n\n\nconsole.log(build.shipComputer());\n// log object"} {"doc_id": "39e3daa939f43dba5d1438faee3132f2", "text": "/*\n ================\n Maze Runner\n ================\n\n [INSTRUCTIONS]\n Maze Runner adalah suatu function yang dibuat untuk mengetahui, siapa yang\n akan memenangkan perlombaan maze runner.\n\n [EXAMPLE]\n var persons = ['Andi', 'Betty', 'Ryan', 'Danang'];\n var tracks = ['AABBAABB', 'ABAB', 'BBBBBBAA', 'AAAB'];\n pemenangnya apabila jumlah A dan B atau sebaliknya berupa perbandingan 1 : 3\n Ryan => 2 A dan 6 B => 1 : 3\n Danang => 3 A dan 1 B => 3 : 1\n output yang diharapkan adalah ['Ryan', 'Danang'];\n\n [RULE]\n - Tidak boleh menggunakan built in function selain .push() dan .unshift()\n*/\n\nfunction mazeRunner(people, solves) {\n var winners = [];\n for (var i = 0; i < solves.length; i++) {\n var checked = checkAB(solves[i]);\n if (checked) {\n winners.push(people[i]);\n }\n }\n if (winners.length === 0) {\n return \"Tidak ada pemenangnya\";\n } else {\n return winners;\n }\n};\n\nfunction checkAB (string) {\n var countA = 0;\n var countB = 0;\n for (var i = 0; i < string.length; i++) {\n if (string[i] === \"A\") {\n countA++;\n } else if (string[i] === \"B\") {\n countB++;\n }\n }\n if ( (countA / countB === 3) || (countB / countA) === 3 ) {\n return true;\n } else {\n return false;\n }\n}\n\n// TEST CASES\nvar persons = ['Andi', 'Betty', 'Ryan', 'Danang'];\nvar tracks = ['AABBAABB', 'ABAB', 'BBBBBBAA', 'AAAB'];\nconsole.log(mazeRunner(persons, tracks));\n// [ 'Ryan', 'Danang' ]\nvar persons2 = ['Andi', 'Betty'];\nvar tracks2 = ['AAB', ''];\nconsole.log(mazeRunner(persons2, tracks2));\n// Tidak ada pemenangnya\nvar persons3 = ['Andi', 'Betty'];\nvar tracks3 = ['AAAB', ''];\nconsole.log(mazeRunner(persons3, tracks3));\n// [ 'Andi' ]"} {"doc_id": "3a41e31fc4683a8f185ff7dd4823f807", "text": "/*\n

      A password is considered strong if below conditions are all met:

      \n\n
        \n
      1. It has at least 6 characters and at most 20 characters.
      2. \n
      3. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
      4. \n
      5. It must NOT contain three repeating characters in a row (\"...aaa...\" is weak, but \"...aa...a...\" is strong, assuming other conditions are met).
      6. \n
      \n\n

      Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.

      \n\n

      Insertion, deletion or replace of any one character are all considered as one change.

      \u4e00\u4e2a\u5f3a\u5bc6\u7801\u5e94\u6ee1\u8db3\u4ee5\u4e0b\u6240\u6709\u6761\u4ef6\uff1a

      \n\n
        \n\t
      1. \u7531\u81f3\u5c116\u4e2a\uff0c\u81f3\u591a20\u4e2a\u5b57\u7b26\u7ec4\u6210\u3002
      2. \n\t
      3. \u81f3\u5c11\u5305\u542b\u4e00\u4e2a\u5c0f\u5199\u5b57\u6bcd\uff0c\u4e00\u4e2a\u5927\u5199\u5b57\u6bcd\uff0c\u548c\u4e00\u4e2a\u6570\u5b57\u3002
      4. \n\t
      5. \u540c\u4e00\u5b57\u7b26\u4e0d\u80fd\u8fde\u7eed\u51fa\u73b0\u4e09\u6b21 (\u6bd4\u5982 "...aaa..." \u662f\u4e0d\u5141\u8bb8\u7684, \u4f46\u662f "...aa...a..." \u662f\u53ef\u4ee5\u7684)\u3002
      6. \n
      \n\n

      \u7f16\u5199\u51fd\u6570 strongPasswordChecker(s)\uff0cs \u4ee3\u8868\u8f93\u5165\u5b57\u7b26\u4e32\uff0c\u5982\u679c s \u5df2\u7ecf\u7b26\u5408\u5f3a\u5bc6\u7801\u6761\u4ef6\uff0c\u5219\u8fd4\u56de0\uff1b\u5426\u5219\u8fd4\u56de\u8981\u5c06 s \u4fee\u6539\u4e3a\u6ee1\u8db3\u5f3a\u5bc6\u7801\u6761\u4ef6\u7684\u5b57\u7b26\u4e32\u6240\u9700\u8981\u8fdb\u884c\u4fee\u6539\u7684\u6700\u5c0f\u6b65\u6570\u3002

      \n\n

      \u63d2\u5165\u3001\u5220\u9664\u3001\u66ff\u6362\u4efb\u4e00\u5b57\u7b26\u90fd\u7b97\u4f5c\u4e00\u6b21\u4fee\u6539\u3002

      \n

      \u4e00\u4e2a\u5f3a\u5bc6\u7801\u5e94\u6ee1\u8db3\u4ee5\u4e0b\u6240\u6709\u6761\u4ef6\uff1a

      \n\n
        \n\t
      1. \u7531\u81f3\u5c116\u4e2a\uff0c\u81f3\u591a20\u4e2a\u5b57\u7b26\u7ec4\u6210\u3002
      2. \n\t
      3. \u81f3\u5c11\u5305\u542b\u4e00\u4e2a\u5c0f\u5199\u5b57\u6bcd\uff0c\u4e00\u4e2a\u5927\u5199\u5b57\u6bcd\uff0c\u548c\u4e00\u4e2a\u6570\u5b57\u3002
      4. \n\t
      5. \u540c\u4e00\u5b57\u7b26\u4e0d\u80fd\u8fde\u7eed\u51fa\u73b0\u4e09\u6b21 (\u6bd4\u5982 "...aaa..." \u662f\u4e0d\u5141\u8bb8\u7684, \u4f46\u662f "...aa...a..." \u662f\u53ef\u4ee5\u7684)\u3002
      6. \n
      \n\n

      \u7f16\u5199\u51fd\u6570 strongPasswordChecker(s)\uff0cs \u4ee3\u8868\u8f93\u5165\u5b57\u7b26\u4e32\uff0c\u5982\u679c s \u5df2\u7ecf\u7b26\u5408\u5f3a\u5bc6\u7801\u6761\u4ef6\uff0c\u5219\u8fd4\u56de0\uff1b\u5426\u5219\u8fd4\u56de\u8981\u5c06 s \u4fee\u6539\u4e3a\u6ee1\u8db3\u5f3a\u5bc6\u7801\u6761\u4ef6\u7684\u5b57\u7b26\u4e32\u6240\u9700\u8981\u8fdb\u884c\u4fee\u6539\u7684\u6700\u5c0f\u6b65\u6570\u3002

      \n\n

      \u63d2\u5165\u3001\u5220\u9664\u3001\u66ff\u6362\u4efb\u4e00\u5b57\u7b26\u90fd\u7b97\u4f5c\u4e00\u6b21\u4fee\u6539\u3002

      \n*/\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar strongPasswordChecker = function(s) {\n \n};"} {"doc_id": "3ba2b0aef86096b75bf7fb25b487c46b", "text": "/*\n

      \nYou are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. \n

      \n\n

      Define a pair (u,v) which consists of one element from the first array and one element from the second array.

      \n\n

      Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.\n

      \n\n

      Example 1:
      \n

      \nGiven nums1 = [1,7,11], nums2 = [2,4,6],  k = 3\n\nReturn: [1,2],[1,4],[1,6]\n\nThe first 3 pairs are returned from the sequence:\n[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n
      \n

      \n\n

      Example 2:
      \n

      \nGiven nums1 = [1,1,2], nums2 = [1,2,3],  k = 2\n\nReturn: [1,1],[1,1]\n\nThe first 2 pairs are returned from the sequence:\n[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n
      \n

      \n\n

      Example 3:
      \n

      \nGiven nums1 = [1,2], nums2 = [3],  k = 3 \n\nReturn: [1,3],[2,3]\n\nAll possible pairs are returned from the sequence:\n[1,3],[2,3]\n
      \n

      \n\n

      Credits:
      Special thanks to @elmirap and @StefanPochmann for adding this problem and creating all test cases.

      \u7ed9\u5b9a\u4e24\u4e2a\u4ee5\u5347\u5e8f\u6392\u5217\u7684\u6574\u5f62\u6570\u7ec4 nums1 \u548c nums2, \u4ee5\u53ca\u4e00\u4e2a\u6574\u6570 k\u3002

      \n\n

      \u5b9a\u4e49\u4e00\u5bf9\u503c (u,v)\uff0c\u5176\u4e2d\u7b2c\u4e00\u4e2a\u5143\u7d20\u6765\u81ea nums1\uff0c\u7b2c\u4e8c\u4e2a\u5143\u7d20\u6765\u81ea nums2\u3002

      \n\n

      \u627e\u5230\u548c\u6700\u5c0f\u7684 k \u5bf9\u6570\u5b57 (u1,v1), (u2,v2) ... (uk,vk)\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u7ed9\u51fa\uff1a nums1 = [1,7,11], nums2 = [2,4,6],  k = 3\n\n\u8fd4\u56de\uff1a [1,2],[1,4],[1,6]\n\n\u8fd4\u56de\u5e8f\u5217\u4e2d\u7684\u524d 3 \u5bf9\u6570\uff1a\n[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u7ed9\u51fa\uff1anums1 = [1,1,2], nums2 = [1,2,3],  k = 2\n\n\u8fd4\u56de\uff1a [1,1],[1,1]\n\n\u8fd4\u56de\u5e8f\u5217\u4e2d\u7684\u524d 2 \u5bf9\u6570\uff1a\n[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \n\u7ed9\u51fa\uff1anums1 = [1,2], nums2 = [3],  k = 3 \n\n\u8fd4\u56de\uff1a [1,3],[2,3]\n\n\u4e5f\u53ef\u80fd\u5e8f\u5217\u4e2d\u6240\u6709\u7684\u6570\u5bf9\u90fd\u88ab\u8fd4\u56de:\n[1,3],[2,3]\n
      \n\n

      \u81f4\u8c22:
      \n\u7279\u522b\u611f\u8c22 @elmirap \u548c @StefanPochmann \u6dfb\u52a0\u8fd9\u4e2a\u95ee\u9898\u5e76\u521b\u5efa\u6240\u6709\u7684\u6d4b\u8bd5\u7528\u4f8b\u3002

      \n

      \u7ed9\u5b9a\u4e24\u4e2a\u4ee5\u5347\u5e8f\u6392\u5217\u7684\u6574\u5f62\u6570\u7ec4 nums1 \u548c nums2, \u4ee5\u53ca\u4e00\u4e2a\u6574\u6570 k\u3002

      \n\n

      \u5b9a\u4e49\u4e00\u5bf9\u503c (u,v)\uff0c\u5176\u4e2d\u7b2c\u4e00\u4e2a\u5143\u7d20\u6765\u81ea nums1\uff0c\u7b2c\u4e8c\u4e2a\u5143\u7d20\u6765\u81ea nums2\u3002

      \n\n

      \u627e\u5230\u548c\u6700\u5c0f\u7684 k \u5bf9\u6570\u5b57 (u1,v1), (u2,v2) ... (uk,vk)\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u7ed9\u51fa\uff1a nums1 = [1,7,11], nums2 = [2,4,6],  k = 3\n\n\u8fd4\u56de\uff1a [1,2],[1,4],[1,6]\n\n\u8fd4\u56de\u5e8f\u5217\u4e2d\u7684\u524d 3 \u5bf9\u6570\uff1a\n[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u7ed9\u51fa\uff1anums1 = [1,1,2], nums2 = [1,2,3],  k = 2\n\n\u8fd4\u56de\uff1a [1,1],[1,1]\n\n\u8fd4\u56de\u5e8f\u5217\u4e2d\u7684\u524d 2 \u5bf9\u6570\uff1a\n[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \n\u7ed9\u51fa\uff1anums1 = [1,2], nums2 = [3],  k = 3 \n\n\u8fd4\u56de\uff1a [1,3],[2,3]\n\n\u4e5f\u53ef\u80fd\u5e8f\u5217\u4e2d\u6240\u6709\u7684\u6570\u5bf9\u90fd\u88ab\u8fd4\u56de:\n[1,3],[2,3]\n
      \n\n

      \u81f4\u8c22:
      \n\u7279\u522b\u611f\u8c22 @elmirap \u548c @StefanPochmann \u6dfb\u52a0\u8fd9\u4e2a\u95ee\u9898\u5e76\u521b\u5efa\u6240\u6709\u7684\u6d4b\u8bd5\u7528\u4f8b\u3002

      \n*/\n\n\n/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @param {number} k\n * @return {number[][]}\n */\nvar kSmallestPairs = function(nums1, nums2, k) {\n \n};"} {"doc_id": "3f9cf527e16fe43801919c5959fd9d20", "text": "// lazy evaluiation, avalia\u00e7\u00e3o pregui\u00e7osa\n\nfunction* geradora1() {\n // codigo qualquer\n yield 'Valor1'\n // codigo qualquer\n yield 'Valor2'\n // codigo qualquer\n yield 'Valor3'\n}\n\nconst g1 = geradora1()\n/*\nconsole.log(g1.next().value) // primeira vez que chamo vai at\u00e9 o primeiro yeild\nconsole.log(g1.next().value) // come\u00e7a depois do valor 1 e para no prox yield\nconsole.log(g1.next().value) // come\u00e7a depois do valor 2 e para no prox yield \n*/\n\nfor (let valor of g1){ // ele sabe o tamanho da fun\u00e7\u00e3o ent\u00e3o ele retorna at\u00e9 o final\n console.log(valor, 'no for')\n}\n\nconsole.log('################')\n\nfunction* geradora2() { // fun\u00e7\u00e3o infinita\n let i = 0;\n while(true){\n yield i;\n i++\n }\n}\n\nconst g2 = geradora2();\n// printa um n\u00famero de cada vez.\nconsole.log(g2.next().value)\nconsole.log(g2.next().value)\nconsole.log(g2.next().value)\nconsole.log(g2.next().value)\nconsole.log(g2.next().value)\n\nconsole.log('#############')\n\nfunction* geradora3(){\n yield 0\n yield 1\n yield 2\n}\n\nfunction* geradora4(){ // continua a fun\u00e7\u00e3o da outra geradora \n yield* geradora3()\n yield 3\n yield 4\n yield 5\n\n}\n\nconst g4 = geradora4()\n\nfor(let valor of g4) {\n console.log(valor)\n}\n\nconsole.log('###############')\n\nfunction* geradora5() {\n yield function() { // passando uma fun\u00e7\u00e3o no yield\n console.log('Vim do y1')\n }\n\n yield function() {\n console.log('Vim do y2')\n }\n\n return function() {\n console.log('Vim do return')\n }\n // daqui pra baixo o c\u00f3digo fica in\u00fatil por que o return encerra a fun\u00e7\u00e3o\n yield function() {\n console.log('Vim do y3')\n }\n}\n\nconst g5 = geradora5()\nconst func1 = g5.next().value\nconst func2 = g5.next().value\nconst func3 = g5.next().value\nfunc1()\nfunc2()\nfunc3()"} {"doc_id": "400142c335153cc1aaaca0f7e65a42db", "text": "/**\n * Created by\uff1aCaMnter\n */\n\n/******************\n * Generator next *\n ******************/\n\nrequire(\"babel-polyfill\");\n\n/**\n * yield \u8bed\u53e5\u672c\u8eab\u6ca1\u6709 \u5177\u4f53\u8fd4\u56de\u503c\uff0c\u4e00\u76f4\u8fd4\u56de undefined\n * next \u65b9\u6cd5\u53ef\u4ee5\u52a0\u4e00\u4e2a\u53c2\u6570\uff0c\u4f5c\u4e3a\u4e0a\u4e00\u6b21 yield \u7684\u8fd4\u56de\u503c\n */\n\n/**\n * \u5b9e\u4f8b\uff1a\u521d\u59cb\u5316\u904d\u5386\n */\n(() => {\n function* resetTraverse() {\n for (var i = 1; true; i++) {\n let reset = yield i;\n if (reset) {\n i = 0;\n }\n }\n }\n\n let generator = resetTraverse();\n for (let i = 0; i < 2; i++) {\n console.log(\"[generator] [test-\" + 1 + \"] [generator.next()] = \", generator.next());\n }\n console.log(\"[generator] [test-\" + 1 + \"] [generator.next(true)] = \", generator.next(true));\n for (let i = 0; i < 2; i++) {\n console.log(\"[generator] [test-\" + 1 + \"] [generator.next()] = \", generator.next());\n }\n console.log('');\n})();\n\n/**\n * \u590d\u6742\u4f8b\u5b50\n */\n(() => {\n function* func(v) {\n let x = 2 * (yield (v + 1));\n let y = yield (x / 3);\n return (v + x + y);\n }\n\n let generatorA = func(2);\n // \u6682\u505c\u5230 yield (v + 1)\uff0c\u8c03\u7528\u540e \u8fd4\u56de v + 1\n // \u5f97\u5230 3\n console.log(\"[generator] [test-\" + 2 + \"] [generatorA.next()] = \", generatorA.next());\n // \u6682\u505c\u5230 yield (x / 3)\uff0c\u8c03\u7528\u540e \u8fd4\u56de x / 3\n // x = 2 * (yield (v + 1))\uff0cyield (v + 1) = undefined\n // x = 2 * undefined = NaN\n // x / 3 = NaN\n console.log(\"[generator] [test-\" + 2 + \"] [generatorA.next()] = \", generatorA.next());\n // \u6682\u505c\u5230 return\uff0c\u8c03\u7528\u540e \u8fd4\u56de v + x + y\uff0creturn \u8c03\u7528\u540e\u7ed3\u675f\n // x = 2 * (yield (v + 1))\uff0cyield (v + 1) = undefined\n // x = 2 * undefined = NaN\n // y = yield (x / 3)\uff0cyield (x / 3) = undefined\n // y = undefined\n // v + x + y = 2 + NaN + undefined = NaN\n console.log(\"[generator] [test-\" + 2 + \"] [generatorA.next()] = \", generatorA.next());\n\n let generatorB = func(2);\n // \u6682\u505c\u5230 yield (v + 1)\uff0c\u8c03\u7528\u540e \u8fd4\u56de v + 1\n // \u5f97\u5230 3\n console.log(\"[generator] [test-\" + 3 + \"] [generatorB.next()] = \", generatorB.next());\n // \u6682\u505c\u5230 yield (x / 3)\uff0c\u8c03\u7528\u540e \u8fd4\u56de x / 3\n // x = 2 * (yield (v + 1))\uff0cyield (v + 1) = 3\n // x = 2 * 3 = 6\n // x / 3 = 2\n console.log(\"[generator] [test-\" + 3 + \"] [generatorB.next()] = \", generatorB.next(3));\n // \u6682\u505c\u5230 return\uff0c\u8c03\u7528\u540e \u8fd4\u56de v + x + y\uff0creturn \u8c03\u7528\u540e\u7ed3\u675f\n // x = 2 * (yield (v + 1))\uff0cyield (v + 1) = 3\n // x = 2 * 3 = 6\n // y = yield (x / 3)\uff0cyield (x / 3) = 3\n // y = 3\n // v + x + y = 2 + 6 + 3 = 11\n console.log(\"[generator] [test-\" + 3 + \"] [generatorB.next()] = \", generatorB.next(3), '\\n');\n})();\n\n/**\n * \u7b2c\u4e00\u6b21 next \u7684\u53c2\u6570\u503c\u662f\u5931\u6548\u7684\n *\n * \u4ee5\u4e0a\u9762\u7684\u4e3a\u4f8b\uff1ayield (v + 1)\uff0c\u8c03\u7528\u540e \u8fd4\u56de v + 1\uff0c\u5b8c\u5168\u4e0d\u6d89\u53ca\u5230 yield (v + 1) \u7684\u503c\uff0c\u53ea\u5173\u5fc3\u4e86 yield\n * \u540e\u9762\u7684 v + 1 \u7684\u503c\n *\n * \u5982\u679c\u60f3\u8981\u7b2c\u4e00\u8c03\u7528 next \u65b9\u6cd5\u65f6\uff0c\u53c2\u6570\u503c\u751f\u6548\n * \u9700\u8981\u5728 Generator \u5305\u4e00\u5c42\n *\n * \u5b9e\u8d28\u4e0a\u5c31\u662f\u5b8c\u6210\u4e86\uff1a\n * \u521b\u5efa Generator \u65b9\u6cd5 + \u624b\u52a8\u8c03\u7528\u4e00\u6b21 next\n * \u7136\u540e\u8fd9\u4e2a\u53c2\u6570\u4f5c\u4e3a \u521b\u5efa Generator \u65b9\u6cd5 \u65f6\u7684\u521d\u59cb\u503c\n */\n(() => {\n function wrapperGenerator(generatorFunction) {\n return function (...args) {\n let generator = generatorFunction(...args);\n generator.next();\n return generator;\n };\n }\n\n const wrapped = wrapperGenerator(function*() {\n console.log(\"[generator] [test-\" + 4 + \"] [yield] = \", yield);\n return \"done\";\n });\n\n let generator = wrapped();\n generator.next('Save');\n console.log(\"[generator] [test-\" + 4 + \"] [generator.next()] = \", generator.next(), '\\n');\n})();\n\n/**\n * \u5411 Generator \u8f93\u5165\u503c\u7684\u4f8b\u5b50\n */\n(() => {\n function * generatorFunction() {\n console.log(\"[generator] [test-\" + 5 + \"] [start]\");\n console.log(\"[generator] [test-\" + 5 + \"] [ 1. yield ] = \", yield);\n console.log(\"[generator] [test-\" + 5 + \"] [ 2. yield ] = \", yield);\n console.log(\"[generator] [test-\" + 5 + \"] [ 3. yield ] = \", yield);\n console.log(\"[generator] [test-\" + 5 + \"] [ 4. yield ] = \", yield);\n }\n\n let generator = generatorFunction();\n generator.next();\n let save = 'Save';\n for (let char of save) {\n generator.next(char);\n }\n})();"} {"doc_id": "404a4d6d2a390a2b565bbd8823046bcd", "text": "\"use strict\";\n\n// Funciones\nfunction add(a, b) {\n return a + b;\n}\n/*\n function add( a: number, b: number ): tipo que regresa{\n return a + b;\n }\n*/\n\n\nvar sum = add(5, 2); // Funciones que regresan otras funciones\n\nfunction createAdder(a) {\n return function (b) {\n return b + a;\n };\n}\n\nvar addFour = createAdder(4);\nvar fourPlus6 = addFour(6);\nconsole.log(fourPlus6); // Argumentos / Parametros que no son obligatorios\n\nfunction fullName(firstName, lastName) {\n return \"\".concat(firstName, \" \").concat(lastName);\n}\n/*\n El signo de interrogaci\u00f3n antes de los dos puntos indica que ese argumento puede ser undefined o string\n*/\n\n\nvar richard = fullName('Richard');\nconsole.log(richard);"} {"doc_id": "41160bf36b3cdc67f458603c49704a67", "text": "const CACHE = {\n 1: 0,\n 2: 1\n};\n\nfunction getNthFib(n) {\t\n// n is not stored in cache\nif (!CACHE.hasOwnProperty(n)) {\n // find the value, and store it on the cache\n CACHE[n] = getNthFib(n - 1) + getNthFib(n - 2);\n} \n// Don't use and Else, becaue we store all values found \n// in CACHE,as it is our data store\n console.log(\"cache:\", CACHE);\n return CACHE[n];\n}\n\n// Do not edit the line below.\nconst position = 5;\nconsole.log(`Fibonacci position: ${position}; value: ${getNthFib(position)}`);"} {"doc_id": "41335c9162c1584d85aac3844469ceb6", "text": "/*\n You are given a program that logs pairings between mentors and students\n It fails because the array `pairsById` can contain different values that break the program\n It is decided that array items which are not pairs should be filtered out\n - Finish the statement on line 11 to produce an array with valid content\n - Do not edit any of the existing code\n*/\n\nvar pairsByIndexRaw = [[0, 3], [1, 2], [2, 1], null, [1], false, \"whoops\"];\n\nfunction notArray (arr){\n return (typeof arr !== \"string\" && arr !== null && arr.length === 2);\n}\n\nvar pairsByIndex = pairsByIndexRaw.filter(notArray); // Complete this statement\n\nvar students = [\"Islam\", \"Lesley\", \"Harun\", \"Rukmini\"];\nvar mentors = [\"Daniel\", \"Irina\", \"Mozafar\", \"Luke\"];\n\nvar pairs = pairsByIndex.map(function(indexes) {\n var student = students[indexes[0]];\n var mentor = mentors[indexes[1]];\n return [student, mentor];\n});\n\nconsole.log(pairs);\n"} {"doc_id": "4200cd06cac86817c74c38fa14348874", "text": "var input = 'cqjxjndz';\n\n// add a method to the String prototype to \"replace\" a character in a string\n// at a given index. Strings are immutable, so actually return a new string.\nString.prototype.replaceAt = function(index, character) {\n return this.substr(0, index) + character + this.substr(index+character.length);\n};\n\n// test if the string contains two different pairs of matching characters\nvar contains2Pairs = function(string) {\n var pairs = string.match(/(.)\\1+/g);\n if (pairs) {\n return pairs.length > 1;\n } else {\n return false;\n }\n}\n\n// test if the string contains the characters 'i', 'o', or 'l'\nvar doesNotContainIOL = function(string) {\n return !(/[iol]/).test(string);\n}\n\n// test if the string contains a sequence of 3+ characters in alphabetic order\nvar containsAlphaSequence = function(string) {\n for (var i = 0; i < string.length - 2; i++) {\n var char1 = parseInt(string.charCodeAt(i));\n var char2 = parseInt(string.charCodeAt(i+1));\n var char3 = parseInt(string.charCodeAt(i+2));\n\n if ((char1 + 2) === (char2 + 1) && (char2 + 1) === char3) {\n return true;\n }\n }\n\n return false;\n}\n\n// test if a string meets all 3 required conditions\nvar isValid = function(string) {\n return (doesNotContainIOL(string) &&\n contains2Pairs(string) &&\n containsAlphaSequence(string));\n}\n\n// alphabetically increment the character at a given index\n// if no index supplied, assume the end of the string.\n// wraps a 'z' back to an 'a' which then increments index-1, etc.\nvar incrementCharacter = function(string, index) {\n if (!index) { index = string.length -1; }\n var charCode = parseInt(string.charCodeAt(index));\n\n if (charCode < 122) {\n charCode++;\n string = string.replaceAt(index, String.fromCharCode(charCode));\n } else {\n string = string.replaceAt(index, 'a');\n string = incrementCharacter(string, index-1);\n }\n\n return string;\n}\n\n// given an initial password, iterate until we find the next valid password\nvar findNextValidPassword = function(input) {\n var password = incrementCharacter(input);\n\n while (!isValid(password)) {\n password = incrementCharacter(password);\n }\n\n return password;\n};\n\nvar part1 = findNextValidPassword(input);\nvar part2 = findNextValidPassword(part1);\n\nconsole.log('Part 1 password: ' + part1);\nconsole.log('Part 2 password: ' + part2);\n"} {"doc_id": "424f2d687eb4465d1366567a3c760bec", "text": "//this is the main Tic-Tac-Toe game function that holds the whole game\n// //we call it to start the game fresh\nfunction ticTacToe() {\n function randomAI(thisBoard, currPlay) {\n let aiMove = [];\n let checkValid=false\n let aiXcoord = Math.floor(Math.random() * 3); // returns a random integer from 0 to 2\n aiMove.push(aiXcoord);\n let aiYcoord = Math.floor(Math.random() * 3); // returns a random integer from 0 to 2\n aiMove.push(aiYcoord);\n while (checkValid===false){ \n if (thisBoard[aiMove[0]][aiMove[1]] == `X` || thisBoard[aiMove[0]][aiMove[1]] == `O`) {\n aiMove=randomAI(newBoard, currentPlayer);; \n } else {\n checkValid=true\n }\n }\n return aiMove;\n }\nlet playerOne;\nlet playerTwo;\nlet currentPlayer;\nlet player = playerOne;\nfunction vsHuman () {\nplayerOne=prompt('Player One, enter your name: ');//ask playerOne their name\nplayerOne+=\" is X:\";//add this info to name\nplayerTwo = prompt('Player Two, enter your name: ');//same as with playerOne\nplayerTwo += \" is O:\";\nplayer= playerOne//must initialize a value for the first turn\n}\n//this makes a fresh board \nconst makeBoard = () => {\n return [[` `, ` `, ` `], [` `, ` `, ` `], [` `, ` `, ` `]];\n }\nlet newBoard = makeBoard(); \nlet gameType = confirm(`Do you want to play against the CPU?`)\nif (gameType === true) {\nplayerOne=prompt('Player One, enter your name: ');//ask playerOne their name\nplayerOne+=\" is X:\";//add this info to name\nplayerTwo = \"CPU is O:\";\nplayer= playerOne//must initialize a value for the first turn\n} else {\n vsHuman();\n}\n//this is our board renderer it receives the output of makeBoard\n const coolBoard = (board, coord) => {\n let tempArray = board;\n tempArray[coord[0]][coord[1]] = currentPlayer;\n console.log(` 0 1 2 `);\n console.log(` _______`);\n console.log(`0| ${tempArray[0]} |`);\n console.log(`1| ${tempArray[1]} |`);\n console.log(`2| ${tempArray[2]} |`);\n console.log(` _______`);\n return tempArray;\n }\n// getMove gets the turn the player wants to make\n function getMove() {\n //get the move in two parts: x and y coordinates\n let playerMove = [];\n let playerXcoord = null;\n let playerYcoord = null;\n alert(`${player}, it's your turn now.`);\n //this sanitizes player input at the Y coordinate level I'm sorry I named things this way\n function xMove() {\n playerXcoord = prompt(`${player}, enter your Y coordinate of 0, 1, or 2`);\n while (playerXcoord != 0 || playerXcoord != 1 || playerXcoord != 2 || playerXcoord == null){\n switch (playerXcoord) {\n case '0':\n case '1':\n case '2':\n case 0:\n case 1:\n case 2:\n return playerXcoord;\n default:\n console.log(playerXcoord, `playerXcoord`)\n console.log(`Invalid move. Please enter 0, 1, or 2`);\n playerXcoord = null;\n playerXcoord = prompt(\n `${player}, enter your Y coordinate of 0, 1, or 2`);\n }\n } \n }\n//this sanitizes player input at the X coordinate I'm sorry I named things this way\n function yMove() {\n playerYcoord = prompt(`${player}, enter your X coordinate of 0, 1, or 2`);\n while (playerYcoord != 0 || playerYcoord != 1 || playerYcoord != 2 || playerYcoord == null){\n switch (playerYcoord) {\n case '0':\n case '1':\n case '2':\n case 0:\n case 1:\n case 2:\n return playerYcoord;\n default:\n console.log(playerYcoord, `playerYcoord`)\n console.log(`Invalid move. Please enter 0, 1, or 2`);\n playerYcoord = null;\n playerYcoord = prompt(\n `${player}, enter your X coordinate of 0, 1, or 2`);\n }\n } \n }\n xMove(); //returns playerXcoord\n playerMove.push(Number(playerXcoord));\n console.log(playerMove, `your X-coordinate`);\n yMove(); //returns playerYcoord\n playerMove.push(Number(playerYcoord));\n console.log(playerMove, `your move`);\n //pass playerMove to isValidMove\n return playerMove;\n}\nfunction isValidMove(currBoard, currMove) {\n //takes in attemptedMove and lets it thru if its OK\n //takes in current state of Board\n //restarts getMove() if not OK\n //if the attempted move in the array is NOT empty space\n //then it's invalid\n let checkValid=false\n//this while loops ensures that no matter how many times the player enters an invalid move it will always ask for a valid entry until it gets a legal move \n//when it does get a valid entry, checkValid is true and exits loop\n while (checkValid===false){ \n if (currBoard[currMove[0]][currMove[1]] == `X` || currBoard[currMove[0]][currMove[1]] == `O`) {\n console.log(`Invalid move, please enter a new move`);\n currMove=getMove(); \n } else {\n checkValid=true\n }\n }\n return currMove;\n}\n//this checks for winners and prints win statement\nfunction checkResult (result, playerName) {\n let userPlay;\n if (result === true) {\n console.log(`${playerName} won the game!`)\n console.log(`Thanks for playing our game! \\n This game is brought to you by \\n Tjolanda Sullivan, Sung Y Kim, Miguel Manalo \\n\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2584\u2584\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\n\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\u2591\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\n\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\u2591\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\n\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\u2591\u2591\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\n\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\u2591\u2591\u2591\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\n\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2591\u2591\n\u2593\u2593\u2593\u2593\u2593\u2593\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\n\u2593\u2593\u2593\u2593\u2593\u2593\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\n\u2593\u2593\u2593\u2593\u2593\u2593\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\n\u2593\u2593\u2593\u2593\u2593\u2593\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\n\u2593\u2593\u2593\u2593\u2593\u2593\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\n\u2593\u2593\u2593\u2593\u2593\u2593\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2588\u2591\u2591\n\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2591\u2591\u2591\u2591\u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2591\u2591\u2591\u2591\\n\nidea: https://robertheaton.com/2018/10/09/programming-projects-for-advanced-beginners-3-a/`)\n userPlay = confirm(`Do you want to play again?`);\n return userPlay;\n }\n else if (result === `Draw`) {\n console.log(`It's a tie`)\n userPlay = confirm(`Do you want to play again?`);\n return userPlay;\n } \n}\n const check_winner = (board) => {\n let resultList = {\n var1: 'OOO',\n var2: 'XXX'\n }\n //horizontal result\n for(let i = 0; i < board.length; i++) {\n let tempString = board[i][0] + board[i][1] + board[i][2];\n if(tempString === resultList.var1 && board[i][0] === currentPlayer) {\n return true;\n } else if(tempString === resultList.var2 && board[i][0] === currentPlayer) {\n return true;\n } else {}\n }\n //vertical result\n for(let j = 0; j < board.length; j++) {\n let tempString = board[0][j] + board[1][j] + board[2][j];\n if(tempString === resultList.var1 && board[0][j] === currentPlayer) {\n return true;\n } else if(tempString === resultList.var2 && board[0][j] === currentPlayer) {\n return true;\n } else {}\n }\n //diagonal result\n let diaResult1 = board[0][0] + board[1][1] + board[2][2];\n let diaResult2 = board[2][0] + board[1][1] + board[0][2];\n if(diaResult1 === resultList.var1 && board[1][1] === currentPlayer) {\n return true;\n } else if(diaResult1 === resultList.var2 && board[1][1] === currentPlayer){\n return true;\n } else {}\n if(diaResult2 === resultList.var1 && board[1][1] === currentPlayer) {\n return true;\n } else if(diaResult2 === resultList.var2 && board[1][1] === currentPlayer){\n return true;\n } else {}\n //check if all the slots are full in the tic-tac-toe board\n let valueCounter = 0;\n for(let k = 0; k < board.length; k++) {\n for(let l = 0; l < board.length; l++) {\n if(board[k][l] !== ` `) {\n valueCounter++;\n }\n }\n }\n if(valueCounter === 9) {\n return 'Draw';\n }\n //if none is returned, the makeBoard keeps going\n return false;\n}\n//initialize these so they're global\nlet checkMove;\nlet nowMove;\n//this is the bulk of the game\nconst makeMove = (prevBoard, playMove)=> {\n let playerInput = coolBoard(prevBoard, playMove);\n return playerInput;\n}\n for (let i = 1; i < 10; i += 1) {\n let result; \n if (i % 2 === 0) {\n currentPlayer = 'O';\n if (gameType === true) {\n checkMove = randomAI(newBoard, currentPlayer);\n } else {\n checkMove = getMove();\n }\n nowMove = isValidMove(newBoard, checkMove);\n newBoard = makeMove(newBoard, nowMove);\n result = check_winner(newBoard);\n let decision = checkResult(result, player);\n player = playerOne;\n if (decision == true) {\n ticTacToe();\n break;\n } else if (decision == false) {\n break;\n }\n } else {\n currentPlayer = 'X';\n checkMove = getMove();\n nowMove = isValidMove(newBoard, checkMove);\n newBoard = makeMove(newBoard, nowMove);\n result = check_winner(newBoard);\n let decision = checkResult(result, player);\n player = playerTwo;\n if (decision == true) {\n ticTacToe();\n break;\n } else if (decision == false) {\n break;\n }\n }\n }\n}\nticTacToe();\n//for refactoring\n//206: recursion instead of for loop\n//in check_winner do functional programming instead of for loops\n//big O notation\n//for loops : n^2(O)\n//n(O)\n//stuff we'd add\n//play against the CPU\n //Left to do\n //validating moves - overwriting a taken space\n //validating player input - someone writes 'fart', 9\n //checking for winners - play again?\n //checking for ties\n //make player 1 and player 2\n //credits with our names, URL for game idea\n //fancy stuff\n //let players choose X/O\n //play again prompt\n //give up?\n //winner art\n //refining it\n //computer AI\n //this constatnly checks for winners every turn\n function randomAI(thisBoard, currPlay) {\n let aiMove = [];\n let aiXcoord = push.aiMove(Math.floor(Math.random() * 2)); // returns a random integer from 0 to 2\n let aiYcoord = push.aiMove(Math.floor(Math.random() * 2)); // returns a random integer from 0 to 2\n aiMove = isValidMove(newBoard, checkMove);\n }\n \n"} {"doc_id": "426d7c777ccce73ebe126704e5362a31", "text": "\"use strict\";\n// Abstract Classes\n/*\nYou can extend classes with Abstract classes.\nConsider an abstract class as a base class.\nIt is a class that may have methods and properties that are common,\nbut another class can be created which extends from this base class and overrides\nany existing methods or can add additional methods and properties specific for itself.\n\nIt is different than an interface in the way that is not indicating rules that the class must follow,\nbut the class that is extending will already have its own copies of the base classes properties and\nmethods once any new object is instantiated using it.\n\n*/\n/* class Animal {\n name: string\n age: number\n\n constructor(name: string, age: number) {\n this.name = name\n this.age = age\n }\n\n feed(food: string, amount: number): void {\n console.log(\n 'Feeding ' +\n this.name +\n ' the ' +\n this.constructor.name +\n ' ' +\n amount +\n ' kg of ' +\n food\n )\n }\n}\n\nclass Cat extends Animal {}\n\nclass Dog extends Animal {}\n\nconst cat = new Cat('Cosmo', 8)\nconst dog = new Dog('Rusty', 12)\ncat.feed('Fish', 0.1)\ndog.feed('Beef', 0.25) */\nclass Animal {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n feed(food, amount) {\n console.log('Feeding ' +\n this.name +\n ' the ' +\n this.constructor.name +\n ' ' +\n amount +\n ' kg of ' +\n food);\n }\n}\nclass Cat extends Animal {\n constructor(name, age, isHungry) {\n super(name, age);\n this.isHungry = isHungry;\n }\n feed(food, amount) {\n if (this.isHungry) {\n super.feed(food, amount);\n }\n else {\n console.log(this.name +\n ' the ' +\n this.constructor.name +\n ' is not hungry');\n }\n }\n}\nclass Dog extends Animal {\n}\nconst cat = new Cat('Cosmo', 8, false);\nconst dog = new Dog('Rusty', 12);\ncat.feed('Fish', 0.1);\ndog.feed('Beef', 0.25);\n"} {"doc_id": "427c7d4fc2ead492439f18fb0ec7928c", "text": "\n// Business (or back-end) logic:\nvar add = function(number1, number2) {\n return number1 + number2;\n};\nvar substract = function(number1, number2) {\n return number1 - number2;\n};\n\nvar multiply = function(number1, number2) {\n return number1 * number2;\n};\nvar divide = function(number1, number2) {\n return number1 / number2;\n};\n\n// User interface (or front-end) logic\n$(document).ready(function () {\n $(\"form#add\").submit(function(event) {\n event.preventDefault();\n var number1 = parseInt($(\"#add1\").val());\n var number2 = parseInt($(\"#add2\").val());\n var result = add(number1, number2);\n $(\"#outputAdd\").text(\"Your result is: \" + result);\n });\n $(\"form#substract\").submit(function(event) {\n event.preventDefault();\n var number1 = parseInt($(\"#substract1\").val());\n var number2 = parseInt($(\"#substract2\").val());\n var result = substract(number1, number2);\n $(\"#outputSubstract\").text(\"Your result is: \" + result);\n });\n $(\"form#multiply\").submit(function(event) {\n event.preventDefault();\n var number1 = parseInt($(\"#multiply1\").val());\n var number2 = parseInt($(\"#multiply2\").val());\n var result = multiply(number1, number2);\n $(\"#outputMultiply\").text(\"Your result is: \" + result);\n });\n $(\"form#divide\").submit(function(event) {\n event.preventDefault();\n var number1 = parseInt($(\"#divide1\").val());\n var number2 = parseInt($(\"#divide2\").val());\n var result = divide(number1, number2);\n $(\"#outputDivide\").text(\"Your result is: \" + result.toFixed(2));\n });\n});\n"} {"doc_id": "427da83c324ae2302a569a13939b5191", "text": "//LETS CREATE A REACT COMPONENT SO THAT WE HAVE A REUSEABLE CUSTOM HTML ELEMENT instead of repeating the HTML code\n// a react component is just a function\n\n\n//So here what I'll do is I'll actually add an argument to this person function which I'll name props,React automatically gives me an argument in that function I turned into a component with this syntax down here with person JSX code and prop simply contains all the attributes I add to my own component so I could add name and age\n\nfunction Person(props) {\n return (\n //looks strange\n //html in js\n React.createElement(\"div\", { className: \"person\" },\n React.createElement(\"h1\", null, props.name),\n React.createElement(\"p\", null, \"The age: \", props.age)));\n\n\n\n\n}\n\nvar app =\nReact.createElement(\"div\", null,\nReact.createElement(Person, { name: \"Mani\", age: \"34\" }),\nReact.createElement(Person, { name: \"Ashu\", age: \"36\" }));\n\n\n//has a render method,this method allows us to render a Javascript function as a component to the real DOM and that treat it as a component part is exactly what React takes care about.\n\n//We can then render this function but not by referencing it like this but by actually turning it into a HTML element, again behind the scenes using this JSX syntax which is understood by React.\n\n//So I write this as my custom self-closing HTML element and render then takes another argument where I specify where to render this and there I reach out to the document and I can use the query selector,so normal Javascript code to select any element with the ID P1 and that again is normal Javascript code,the normal query selector. With that, I'm telling React that I want to render this function, the person component in this place here on the left and it does. Now the styling is lost because class actually is a keyword in Javascript, so React turns this into class name and that's the best proof that this looks like HTML but isn't.\n\n//reuse again n again\n\n//I got the two elements now next to each other because now they're rendered in the same hook, in the same element so to say, in the same div and this method of only having one hook, one React DOM render call and then creating app there with nested components is the far more popular way of creating React apps.\nReactDOM.render(app, document.querySelector('#app'));"} {"doc_id": "42c73e5174f291b1cf1728d89c5fc8c1", "text": "export default ` In the previous page we looked at JSX syntax where we displayed a string \\`Hello World\\` inside the \\`div\\` element. What's the big deal! What else can it do for us?\n\nSince JSX is technically Javascript it is pretty powerful in many sense. It can do everything that Javascript can do.\n\nIf you want to execute any Javascript code within JSX then you surround your Javascript code with curly braces \\`{ //javascript code }\\` and put it inside anywhere in JSX. It will evaluate your code everytime it renders the component to find out what it should render on the browser.\n\nFor example lets imagine we want to display a company profile information and a Company ticker. And imagine the Company ticker is stored on some variable somewhere and the company profile information is stored in another variable as an object. In that case we might write:\n\n\\`\\`\\`jsx\nfunction CompanyProfile(props) {\n //ticker and companyProfileInfo stored in a variable\n const ticker = 'APPL';\n const companyProfileInfo = {\n 'Company Name': 'Apple Inc.',\n 'Exchange': 'Nasdaq',\n 'Sector': 'Technology',\n 'Industry': 'Computer Hardware',\n 'CEO': 'Timothy D. Cook'\n };\n return (\n
      \n
      Profile of: {ticker}
      \n
      \n {\n {/*This is javascript code inside the curly braces*/}\n Object.keys(companyProfileInfo)\n .map((key, index) => {\n return
      {key}: {companyProfileInfo[key]}
      \n })\n }\n
      \n
      \n )\n}\n\\`\\`\\`\n\nThe HTML output of the above Component when it's rendered will be:\n\n\\`\\`\\`html\n
      \n
      Profile of: APPL
      \n
      \n
      Company Name: Apple Inc.
      \n
      Exchange: Nasdaq
      \n
      Sector: Technology
      \n
      Industry: Computer Hardware
      \n
      CEO: Timothy D. Cook
      \n
      \n
      \n\\`\\`\\`\n\nWell that's a handful, so let's review what's happening here. We have a \\`ticker\\` variable assigned to a value \\`APPL\\` and an object \\`companyProfileInfo\\` that has company profile. Inside the JSX (inside the \\`return\\` statement) we have a \\`div\\` enclosing everything. In JSX, **a component must return one and only one enclosing tag**. That tag can have as many children as it wants.\n\\`\\`\\`jsx\n// \u274c This is illegal in React since the return has more than one tag.\nreturn ( \n
      \n
      \n)\n\n// \u2705 This is perfectly legal because there is just one enclosing tag and\n// it can have as many children as it likes\nreturn (\n
      \n
      \n
      \n
      \n
      \n
      \n)\n\n// \u2705 If you don't want to wrap your component with some enclosing tag like \\`div\\`\n// you can wrap everything with \\`React.Fragment\\` which is a empty tag provided by React\nreturn (\n \n
      \n
      \n
      \n)\n\\`\\`\\`\n\nGoing back to the company profile example, the first child of the enclosing \\`div\\` is another \\`div\\`. Inside that \\`div\\` we used curly braces to display the \\`ticker\\` alongside \\`Profile of:\\`. Remember curly braces is how we inject Javascript code inside JSX. So here the \\`ticker\\` variable would be evaluated and rendered inside that \\`div\\` tag. Then we have another \\`div\\` as a second children of the enclosing parent. Inside this \\`div\\` we again have curly braces and we executed some Javascript code. In this case we mapped each key of the \\`companyProfileInfo\\` object to a \\`div\\` element. The content of this \\`div\\` is again evaluated using another curly braces like: \\`{key} : {companyProfileInfo[key]}\\`. What we did here is told React that for each key of the \\`companyProfileInfo\\` object we want to render a \\`div\\` whose content would be the \\`key\\` followed by a colon \\`:\\` followed by corresponding value for the key on the object (\\`companyProfileInfo[key]\\`).\n\nLet's write some code here to hit the nail on the head. Please open the exercise file and follow the instructions.\n\n\n\nKey takeaways:\n- Components must return only one tag. This tag can have as many children as it likes. Instead of a tag, it can however return a string or null.\n- You can run any Javascript code inside the \\`return\\` using curly braces \\`{//run any Javascript}\\`.\n- Outside of the \\`return\\` it's exactly like any other Javascript class or function. You can do whatever you desire to do.\n\n### Differences with HTML\n\nThere are some commonly used things that are slightly different in JSX than in HTML.\n\n- Styles\n\nIn HTML, styles are passed as string. The css properties are kebab-cased.\n\n\\`\\`\\`html\n
      \n\\`\\`\\`\n\nIn JSX, styles are passed as an object. The css properties are camelCased.\n\n\\`\\`\\`jsx \n
      \n\\`\\`\\`\n\n- Class\n\nIn HTML class attribute is passed as string.\n\n\\`\\`\\`html\n
      \n\\`\\`\\`\n\nIn JSX also class attribute is passed as string but instead of calling it \\`class\\` we call it \\`className\\`. That's because JSX is extension of Javascript and \"class\" is a reserved keyword in Javascript.\n\n\\`\\`\\`jsx \n
      \n\\`\\`\\`\n- Event Handler\n\nIn HTML event handler attribute is all lower cased and the handlers are passed as string.\n\n\\`\\`\\`html\n
      \n\\`\\`\\`\n\nIn JSX, event handler are camelCased and instead of string we pass the actual function.\n\n\\`\\`\\`jsx\n
      \n\\`\\`\\`\n\nWe will look more into [event handler](/tutorial/handling-events) later in the tutorial.\n `"} {"doc_id": "438bb91d74fd83f60cf1d4f728b8b353", "text": "//find the shortest distance for any two words in large text file\n\nlet shortest = ( book, word1, word2 ) => {\n\n let min = Number.MAX_VALUE;\n let lastPosWord1 = -1;\n let lastPosWord2 = -1;\n\n let n = book.length;\n\n for ( let i=0; i {\n\n book = book.replace(/\\./g, \" \").replace(/,/g, \" \").replace(/-/g, ' ');\n\n return book.split(\" \");\n}\nlet book = \"As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days were long. The fig tree was in full leaf, but not yet bearing fruit. \"\n + \"Soon Lara spotted other landmarks\ufffdan outcropping of limestone beside the path that had a silhouette like a face, a marshy spot beside the river where the waterfowl were easily startled, a tall tree that looked like a man with his arms upraised. They were drawing near to the place where there was an island in the river. The island was a good spot to make camp. They would sleep on the island tonight.\"\n + \"Lara had been back and forth along the river path many times in her short life. Her people had not created the path it had always been there, like the river\ufffdbut their deerskin-shod feet and the wooden wheels of their handcarts kept the path well worn. Lara\ufffds people were salt traders, and their livelihood took them on a continual journey. \";\n\nbook = getText(book);\n\nconsole.log(shortest( book, \"Lara\", \"the\"));\nconsole.log(shortest( book, \"life\", 'a'));"} {"doc_id": "44d020e60731567239748761bac6bed1", "text": "//Accessing Array Elements\nvar alphas;\nalphas = [\"1\", \"2\", \"3\", \"4\"];\nconsole.log(alphas[0]);\nconsole.log(alphas[1]);\n//Single statement declaration and initialization\nvar nums = [1, 2, 3, 3];\nconsole.log(nums[0]);\nconsole.log(nums[1]);\nconsole.log(nums[2]);\nconsole.log(nums[3]);\n//Array Object\nvar arr_names = new Array(4);\nfor (var i = 0; i < arr_names.length; i++) {\n arr_names[i] = i * 2;\n console.log(arr_names[i]);\n}\n// Array Constructor accepts comma separated values\nvar names = new Array(\"Mary\", \"Tom\", \"Jack\", \"Jill\");\nfor (var i = 0; i < names.length; i++) {\n console.log(names[i]);\n}\n//Array Methods\n//Join\nvar arr = new Array(\"First\", \"Second\", \"Third\");\nvar str = arr.join();\nconsole.log(\"str : \" + str);\nvar str = arr.join(\", \");\nconsole.log(\"str : \" + str);\nvar str = arr.join(\" + \");\nconsole.log(\"str : \" + str);\n//every\nfunction isBigEnough(element, index, array) {\n return (element >= 4);\n}\nvar passed = [12, 5, 8, 130, 44].every(isBigEnough);\nconsole.log(\"Test Value : \" + passed);\n//filter\nfunction isBigEnough2(element, index, array) {\n return (element >= 10);\n}\nvar passed2 = [12, 5, 8, 130, 44].filter(isBigEnough2);\nconsole.log(\"Test Value : \" + passed2);\n//Array forEach\nvar num = [7, 8, 9];\nnum.forEach(function (value) {\n console.log(value);\n});\n//Array indexOf()\nvar index = [12, 5, 8, 130, 44].indexOf(8);\nconsole.log(\"index is : \" + index);\n//Array lastIndexOf()\nvar index = [12, 5, 103, 8, 102, 101, 130, 44].lastIndexOf(8);\nconsole.log(\"index is : \" + index);\n//Array map()\nvar numbers = [1, 4, 9, 17];\nvar roots = numbers.map(Math.sqrt);\nconsole.log(\"roots is : \" + roots);\n//Array pop()\nvar numbers = [1, 4, 9];\nvar element = numbers.pop();\nconsole.log(\"element is : \" + element);\nvar element = numbers.pop();\nconsole.log(\"element is : \" + element);\n//Array push()\nvar numbers = new Array(1, 4, 9);\nvar length = numbers.push(10);\nconsole.log(\"new numbers is : \" + numbers);\nlength = numbers.push(20);\nconsole.log(\"new numbers is : \" + numbers);\n// Array reduce()\nvar total = [0, 1, 2, 3].reduce(function (a, b) { return a + b; });\nconsole.log(\"total is : \" + total);\n//Array reduceRight()\nvar total = [0, 1, 2, 3].reduceRight(function (a, b) { return a + b; });\nconsole.log(\"total is : \" + total);\n//Array reverse()\nvar arrReverse = [0, 1, 2, 3].reverse();\nconsole.log(\"Reversed array is : \" + arrReverse);\n//Array shift\nvar arrShift = [10, 1, 2, 3].shift();\nconsole.log(\"Shifted value is : \" + arrShift);\n//Array slice\nvar arr = [\"orange\", \"mango\", \"banana\", \"sugar\", \"tea\"];\nconsole.log(\"arr.slice( 1, 2) : \" + arr.slice(1, 2));\nconsole.log(\"arr.slice( 1, 3) : \" + arr.slice(0, 3));\n//Array some\nfunction isBigEnough3(element, index, array) {\n return (element >= 10);\n}\nvar retval = [2, 5, 8, 1, 4].some(isBigEnough3);\nconsole.log(\"Returned value is : \" + retval);\nvar retval = [12, 5, 8, 1, 4].some(isBigEnough3);\nconsole.log(\"Returned value is : \" + retval);\n//Array sort\nvar arr = new Array(\"orange\", \"mango\", \"banana\", \"sugar\");\nvar sorted = arr.sort();\nconsole.log(\"Returned string is : \" + sorted);\n//Array splice\nvar arr = [\"orange\", \"mango\", \"banana\", \"sugar\", \"tea\"];\nvar removed = arr.splice(2, 0, \"water\");\nconsole.log(\"After adding 1: \" + arr);\nconsole.log(\"removed is: \" + removed);\nremoved = arr.splice(3, 1);\nconsole.log(\"After removing 1: \" + arr);\nconsole.log(\"removed is: \" + removed);\n//Array toString\nvar arr = new Array(\"orange\", \"mango\", \"banana\", \"sugar\");\nvar str = arr.toString();\nconsole.log(\"Returned string is : \" + str);\n//Array unshift\nvar arr = new Array(\"orange\", \"mango\", \"banana\", \"sugar\");\nvar length = arr.unshift(\"water\");\nconsole.log(\"Returned array is : \" + arr);\nconsole.log(\"Length of the array is : \" + length);\n"} {"doc_id": "4590f7c125f6628d8e341f097e1f8d6a", "text": "\"use strict\";\n// Access Modifiers\n// TypeScript supports access modifiers for your class properties and methods.\n// Public\n// In JavaScript, all class properties are public by default so there is no need to write the public keyword in your TypeScript files.\n// class Cat {\n// public name: string\n// constructor(name: string) {\n// this.name = name\n// }\n// }\n// const cat = new Cat('Tom')\n// console.log(cat.name)\n/* //Private\nclass Bird {\n private name: string\n\n constructor(name: string) {\n this.name = name\n }\n private customMerhod(): void{\n\n }\n}\n\nconst bird = new Bird('Cosmo')\nconsole.log(bird.name) // \u26d4\u274c */\n// Protected\n// A protected property is accessible only internally within the class or any class that extends it but not externally.\n/*\nclass Animal {\n protected name: string\n protected age: number\n\n constructor(name: string, age: number) {\n this.name = name\n this.age = age\n }\n}\n\nclass Cat extends Animal {\n constructor(name: string, age: number) {\n super(name, age)\n console.log(this.name)\n }\n}\n\nconst cat = new Cat('Cosmo', 8)\nconsole.log(cat.name) // \u274c\n */ \n"} {"doc_id": "4607bbd8d99c436f497157e8cf198fb0", "text": "/*\n

      Koko loves to eat bananas.  There are N piles of bananas, the i-th pile has piles[i] bananas.  The guards have gone and will come back in H hours.

      \n\n

      Koko can decide her bananas-per-hour eating speed of K.  Each hour, she chooses some pile of bananas, and eats K bananas from that pile.  If the pile has less than K bananas, she eats all of them instead, and won't eat any more bananas during this hour.

      \n\n

      Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.

      \n\n

      Return the minimum integer K such that she can eat all the bananas within H hours.

      \n\n

       

      \n\n
        \n
      \n\n
      \n

      Example 1:

      \n\n
      \nInput: piles = [3,6,7,11], H = 8\nOutput: 4\n
      \n\n
      \n

      Example 2:

      \n\n
      \nInput: piles = [30,11,23,4,20], H = 5\nOutput: 30\n
      \n\n
      \n

      Example 3:

      \n\n
      \nInput: piles = [30,11,23,4,20], H = 6\nOutput: 23\n
      \n\n

       

      \n\n

      Note:

      \n\n
        \n\t
      • 1 <= piles.length <= 10^4
      • \n\t
      • piles.length <= H <= 10^9
      • \n\t
      • 1 <= piles[i] <= 10^9
      • \n
      \n
      \n
      \n
      \n

      \u73c2\u73c2\u559c\u6b22\u5403\u9999\u8549\u3002\u8fd9\u91cc\u6709 N \u5806\u9999\u8549\uff0c\u7b2c i \u5806\u4e2d\u6709 piles[i] \u6839\u9999\u8549\u3002\u8b66\u536b\u5df2\u7ecf\u79bb\u5f00\u4e86\uff0c\u5c06\u5728 H \u5c0f\u65f6\u540e\u56de\u6765\u3002

      \n\n

      \u73c2\u73c2\u53ef\u4ee5\u51b3\u5b9a\u5979\u5403\u9999\u8549\u7684\u901f\u5ea6 K \uff08\u5355\u4f4d\uff1a\u6839/\u5c0f\u65f6\uff09\u3002\u6bcf\u4e2a\u5c0f\u65f6\uff0c\u5979\u5c06\u4f1a\u9009\u62e9\u4e00\u5806\u9999\u8549\uff0c\u4ece\u4e2d\u5403\u6389 K \u6839\u3002\u5982\u679c\u8fd9\u5806\u9999\u8549\u5c11\u4e8e K \u6839\uff0c\u5979\u5c06\u5403\u6389\u8fd9\u5806\u7684\u6240\u6709\u9999\u8549\uff0c\u7136\u540e\u8fd9\u4e00\u5c0f\u65f6\u5185\u4e0d\u4f1a\u518d\u5403\u66f4\u591a\u7684\u9999\u8549\u3002  

      \n\n

      \u73c2\u73c2\u559c\u6b22\u6162\u6162\u5403\uff0c\u4f46\u4ecd\u7136\u60f3\u5728\u8b66\u536b\u56de\u6765\u524d\u5403\u6389\u6240\u6709\u7684\u9999\u8549\u3002

      \n\n

      \u8fd4\u56de\u5979\u53ef\u4ee5\u5728 H \u5c0f\u65f6\u5185\u5403\u6389\u6240\u6709\u9999\u8549\u7684\u6700\u5c0f\u901f\u5ea6 K\uff08K \u4e3a\u6574\u6570\uff09\u3002

      \n\n

       

      \n\n
        \n
      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \u8f93\u5165: piles = [3,6,7,11], H = 8\n\u8f93\u51fa: 4\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \u8f93\u5165: piles = [30,11,23,4,20], H = 5\n\u8f93\u51fa: 30\n
      \n\n

      \u793a\u4f8b 3\uff1a

      \n\n
      \u8f93\u5165: piles = [30,11,23,4,20], H = 6\n\u8f93\u51fa: 23\n
      \n\n

       

      \n\n

      \u63d0\u793a\uff1a

      \n\n
        \n\t
      • 1 <= piles.length <= 10^4
      • \n\t
      • piles.length <= H <= 10^9
      • \n\t
      • 1 <= piles[i] <= 10^9
      • \n
      \n

      \u73c2\u73c2\u559c\u6b22\u5403\u9999\u8549\u3002\u8fd9\u91cc\u6709 N \u5806\u9999\u8549\uff0c\u7b2c i \u5806\u4e2d\u6709 piles[i] \u6839\u9999\u8549\u3002\u8b66\u536b\u5df2\u7ecf\u79bb\u5f00\u4e86\uff0c\u5c06\u5728 H \u5c0f\u65f6\u540e\u56de\u6765\u3002

      \n\n

      \u73c2\u73c2\u53ef\u4ee5\u51b3\u5b9a\u5979\u5403\u9999\u8549\u7684\u901f\u5ea6 K \uff08\u5355\u4f4d\uff1a\u6839/\u5c0f\u65f6\uff09\u3002\u6bcf\u4e2a\u5c0f\u65f6\uff0c\u5979\u5c06\u4f1a\u9009\u62e9\u4e00\u5806\u9999\u8549\uff0c\u4ece\u4e2d\u5403\u6389 K \u6839\u3002\u5982\u679c\u8fd9\u5806\u9999\u8549\u5c11\u4e8e K \u6839\uff0c\u5979\u5c06\u5403\u6389\u8fd9\u5806\u7684\u6240\u6709\u9999\u8549\uff0c\u7136\u540e\u8fd9\u4e00\u5c0f\u65f6\u5185\u4e0d\u4f1a\u518d\u5403\u66f4\u591a\u7684\u9999\u8549\u3002  

      \n\n

      \u73c2\u73c2\u559c\u6b22\u6162\u6162\u5403\uff0c\u4f46\u4ecd\u7136\u60f3\u5728\u8b66\u536b\u56de\u6765\u524d\u5403\u6389\u6240\u6709\u7684\u9999\u8549\u3002

      \n\n

      \u8fd4\u56de\u5979\u53ef\u4ee5\u5728 H \u5c0f\u65f6\u5185\u5403\u6389\u6240\u6709\u9999\u8549\u7684\u6700\u5c0f\u901f\u5ea6 K\uff08K \u4e3a\u6574\u6570\uff09\u3002

      \n\n

       

      \n\n
        \n
      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \u8f93\u5165: piles = [3,6,7,11], H = 8\n\u8f93\u51fa: 4\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \u8f93\u5165: piles = [30,11,23,4,20], H = 5\n\u8f93\u51fa: 30\n
      \n\n

      \u793a\u4f8b 3\uff1a

      \n\n
      \u8f93\u5165: piles = [30,11,23,4,20], H = 6\n\u8f93\u51fa: 23\n
      \n\n

       

      \n\n

      \u63d0\u793a\uff1a

      \n\n
        \n\t
      • 1 <= piles.length <= 10^4
      • \n\t
      • piles.length <= H <= 10^9
      • \n\t
      • 1 <= piles[i] <= 10^9
      • \n
      \n*/\n\n\n/**\n * @param {number[]} piles\n * @param {number} H\n * @return {number}\n */\nvar minEatingSpeed = function(piles, H) {\n \n};"} {"doc_id": "46ce51065f8ec210f32deace5fb85d17", "text": "// ================================= CONDITIONALS BONUSES\n//\n// Bonus 1.\n//\n// Write a function (or multiple functions) that will return\n// a boolean depending on if the string value passed to it\n// as an argument is the name of a day of the week that starts with a T.\n// Otherwise, it should return false.\n//\n// Example: dayOfTheWeekStartsWithT(\"Monday\") => returns false\n// Example: dayOfTheWeekStartsWithT(\"Tuesday\") => returns true\n// Example: dayOfTheWeekStartsWithT(\"Tommy\") => returns false\n//\n//\n// Bonus 2.\n//\n// Write a function, isValidPassword, that takes in a string argument and returns true or false\n// depending on whether or not all the following conditions are true:\n//\n// 1) Must be 6 characters long (only for the sake of this exercise, NOT a best practice)\n// 2) Contains at least one letter and one number\n// 3) Contains at least one upper and one lower case letter\n// 4) Only comprised of letters and numbers\n// 5) EXTRA BONUS: is not the same forwards and backwards\n\n\"use strict\";\n\nfunction dayOfTheWeekStartsWithT(dayToCheck) {\n dayToCheck.ignoreCase();\n if (dayToCheck.toLowerCase() === 'tuesday' || dayToCheck.toLowerCase() === 'thursday') {\n return true;\n } else return false;\n}\n\nfunction checkPwd(str) {\n var backwards = ((str.split('').reverse().join()));\n if (str.length < 6) {\n return(\"too_short\");\n } else if (str.search(/\\d/) === -1) {\n return(\"no_num\");\n } else if (str.search(/[a-z]/) === -1) {\n return(\"no_lowercase_letter\");\n } else if (str.search(/[A-Z]/) === -1) {\n return(\"no_capital_letter\");\n } else if (str.search(/[^a-zA-Z0-9\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+]/) !== -1) {\n return(\"bad_char\");\n } else if (str === backwards) {\n return(\"password_rev_match\");\n }\n return('ok');\n}"} {"doc_id": "471a55d63c4abb49fd691c72c4777660", "text": "var numeroSecreto = parseInt(Math.random() * 11);\n\nvar numeroTentativas = 3;\n\nfunction Chutar() {\n var elementoResultado = document.getElementById(\"resultado\");\n var chute = parseInt(document.getElementById(\"valor\").value);\n console.log(chute);\n\n if (chute == numeroSecreto) {\n elementoResultado.innerHTML = \"Voc\u00ea acertou!\";\n } else if (chute < 0 || chute > 10) {\n elementoResultado.innerHTML = \"Digite um n\u00famero somente entre 0 e 10\";\n } else if (numeroTentativas > 0) {\n numeroTentativas--;\n }\n\n if (chute > numeroSecreto) {\n elementoResultado.innerHTML =\n \"O n\u00famero \u00e9 menor.\" + numeroTentativas + \" tentativas restante.\";\n } else if (chute < numeroSecreto) {\n elementoResultado.innerHTML =\n \"O n\u00famero \u00e9 maior. \" + numeroTentativas + \" tentativas restante.\";\n }\n\n if (numeroTentativas == 0) {\n elementoResultado.innerHTML =\n \"Game over! O n\u00famero secreto era \" + numeroSecreto;\n }\n}"} {"doc_id": "47343cb28c886d7e3c37db97bc8f1249", "text": "/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n * 79. Word Search\n *\n * Medium\n *\n * Given an m x n grid of characters board and a string word, return true if word exists in the grid.\n * The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are\n * horizontally or vertically neighboring. The same letter cell may not be used more than once.\n *\n * Example 1:\n * Input: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\n * Output: true\n *\n * Example 2:\n * Input: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\n * Output: true\n *\n * Example 3:\n * Input: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\n * Output: false\n *\n * Constraints:\n * m == board.length\n * n = board[i].length\n * 1 <= m, n <= 6\n * 1 <= word.length <= 15\n * board and word consists of only lowercase and uppercase English letters.\n *** =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/\n\n\n// Given a 2D board and a word, find if the word exists in the grid.\n\n// The word can be constructed from letters of sequentially adjacent cell, where \"adjacent\" cells \n//are those horizontally or vertically neighboring. The same letter cell may not be used more than once.\n\n// For example,\n// Given board =\n\n// [\n// ['A','B','C','E'],\n// ['S','F','C','S'],\n// ['A','D','E','E']\n// ]\n// word = \"ABCCED\", -> returns true,\n// word = \"SEE\", -> returns true,\n// word = \"ABCB\", -> returns false.\n// Hide Company Tags Microsoft Bloomberg Facebook\n// Hide Tags Array Backtracking\n// Hide Similar Problems (H) Word Search II\n\nvar exist = function (board, word) {\n var hash = {};\n\n for (var i = 0; i < board.length; i++) {\n for (var j = 0; j < board[0].length; j++) {\n if (dfs(board, word, 0, i, j)) {\n return true;\n }\n }\n }\n\n function dfs(board, word, w, i, j) {\n var key = i + \",\" + j;\n if (hash[key]) {\n return false;\n }\n\n if (w === word.length) {\n return true;\n }\n\n if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {\n return false;\n }\n\n var result = false;\n\n if (word[w] === board[i][j]) {\n hash[key] = true;\n\n result =\n dfs(board, word, w + 1, i + 1, j) ||\n dfs(board, word, w + 1, i - 1, j) ||\n dfs(board, word, w + 1, i, j + 1) ||\n dfs(board, word, w + 1, i, j - 1);\n\n hash[key] = false;\n }\n\n return result;\n }\n\n return false;\n};"} {"doc_id": "476ad7b6b7397d5c0ccc54b097c43973", "text": "/*\n

      Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

      \n\n

      Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.

      \n\n

      Example 1:
      \n

      \nInput: [1,1,2,2,2]\nOutput: true\n\nExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.\n
      \n

      \n\n

      Example 2:
      \n

      \nInput: [3,3,3,3,4]\nOutput: false\n\nExplanation: You cannot find a way to form a square with all the matchsticks.\n
      \n

      \n\n

      Note:
      \n

        \n
      1. The length sum of the given matchsticks is in the range of 0 to 10^9.\n
      2. The length of the given matchstick array will not exceed 15.
      3. \n
      \n

      \u8fd8\u8bb0\u5f97\u7ae5\u8bdd\u300a\u5356\u706b\u67f4\u7684\u5c0f\u5973\u5b69\u300b\u5417\uff1f\u73b0\u5728\uff0c\u4f60\u77e5\u9053\u5c0f\u5973\u5b69\u6709\u591a\u5c11\u6839\u706b\u67f4\uff0c\u8bf7\u627e\u51fa\u4e00\u79cd\u80fd\u4f7f\u7528\u6240\u6709\u706b\u67f4\u62fc\u6210\u4e00\u4e2a\u6b63\u65b9\u5f62\u7684\u65b9\u6cd5\u3002\u4e0d\u80fd\u6298\u65ad\u706b\u67f4\uff0c\u53ef\u4ee5\u628a\u706b\u67f4\u8fde\u63a5\u8d77\u6765\uff0c\u5e76\u4e14\u6bcf\u6839\u706b\u67f4\u90fd\u8981\u7528\u5230\u3002

      \n\n

      \u8f93\u5165\u4e3a\u5c0f\u5973\u5b69\u62e5\u6709\u706b\u67f4\u7684\u6570\u76ee\uff0c\u6bcf\u6839\u706b\u67f4\u7528\u5176\u957f\u5ea6\u8868\u793a\u3002\u8f93\u51fa\u5373\u4e3a\u662f\u5426\u80fd\u7528\u6240\u6709\u7684\u706b\u67f4\u62fc\u6210\u6b63\u65b9\u5f62\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: [1,1,2,2,2]\n\u8f93\u51fa: true\n\n\u89e3\u91ca: \u80fd\u62fc\u6210\u4e00\u4e2a\u8fb9\u957f\u4e3a2\u7684\u6b63\u65b9\u5f62\uff0c\u6bcf\u8fb9\u4e24\u6839\u706b\u67f4\u3002\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165: [3,3,3,3,4]\n\u8f93\u51fa: false\n\n\u89e3\u91ca: \u4e0d\u80fd\u7528\u6240\u6709\u706b\u67f4\u62fc\u6210\u4e00\u4e2a\u6b63\u65b9\u5f62\u3002\n
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      1. \u7ed9\u5b9a\u7684\u706b\u67f4\u957f\u5ea6\u548c\u5728 0 \u5230 10^9\u4e4b\u95f4\u3002
      2. \n\t
      3. \u706b\u67f4\u6570\u7ec4\u7684\u957f\u5ea6\u4e0d\u8d85\u8fc715\u3002
      4. \n
      \n

      \u8fd8\u8bb0\u5f97\u7ae5\u8bdd\u300a\u5356\u706b\u67f4\u7684\u5c0f\u5973\u5b69\u300b\u5417\uff1f\u73b0\u5728\uff0c\u4f60\u77e5\u9053\u5c0f\u5973\u5b69\u6709\u591a\u5c11\u6839\u706b\u67f4\uff0c\u8bf7\u627e\u51fa\u4e00\u79cd\u80fd\u4f7f\u7528\u6240\u6709\u706b\u67f4\u62fc\u6210\u4e00\u4e2a\u6b63\u65b9\u5f62\u7684\u65b9\u6cd5\u3002\u4e0d\u80fd\u6298\u65ad\u706b\u67f4\uff0c\u53ef\u4ee5\u628a\u706b\u67f4\u8fde\u63a5\u8d77\u6765\uff0c\u5e76\u4e14\u6bcf\u6839\u706b\u67f4\u90fd\u8981\u7528\u5230\u3002

      \n\n

      \u8f93\u5165\u4e3a\u5c0f\u5973\u5b69\u62e5\u6709\u706b\u67f4\u7684\u6570\u76ee\uff0c\u6bcf\u6839\u706b\u67f4\u7528\u5176\u957f\u5ea6\u8868\u793a\u3002\u8f93\u51fa\u5373\u4e3a\u662f\u5426\u80fd\u7528\u6240\u6709\u7684\u706b\u67f4\u62fc\u6210\u6b63\u65b9\u5f62\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: [1,1,2,2,2]\n\u8f93\u51fa: true\n\n\u89e3\u91ca: \u80fd\u62fc\u6210\u4e00\u4e2a\u8fb9\u957f\u4e3a2\u7684\u6b63\u65b9\u5f62\uff0c\u6bcf\u8fb9\u4e24\u6839\u706b\u67f4\u3002\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165: [3,3,3,3,4]\n\u8f93\u51fa: false\n\n\u89e3\u91ca: \u4e0d\u80fd\u7528\u6240\u6709\u706b\u67f4\u62fc\u6210\u4e00\u4e2a\u6b63\u65b9\u5f62\u3002\n
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      1. \u7ed9\u5b9a\u7684\u706b\u67f4\u957f\u5ea6\u548c\u5728 0 \u5230 10^9\u4e4b\u95f4\u3002
      2. \n\t
      3. \u706b\u67f4\u6570\u7ec4\u7684\u957f\u5ea6\u4e0d\u8d85\u8fc715\u3002
      4. \n
      \n*/\n\n\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nvar makesquare = function(nums) {\n \n};"} {"doc_id": "484c45af384ef4beded789b0f5d7de5b", "text": "/*\n==========\nGET PRIMES\n==========\n\nBilangan prima adalah sebuah bilangan dimana hanya bisa habis dibagi oleh angka 1 dan angka itu sendiri.\nContoh:\n7 adalah bilangan prima, karena hanya habis dibagi angka 1 dan 7.\n22 bukan bilangan prima, karena habis dibagi 1, 2, 11, dan 22.\n\nDeret bilangan prima\n2, 3, 5, 7, 11, 13, 17, 19, 23, dst\n\nBuatlah sebuah function getPrime dimana menerima sebuah parameter bertipe Number.\nFunction tersebut mengembalikan/me-return array kumpulan deret bilangan prima sampai parameter tersebut.\n\nContoh 1:\n\ninput: 10\noutput: [ 2, 3, 5, 7 ]\nkarena di-range angka 10 hanya bilangan 2, 3, 5 dan 7 saja yang merupakan bilangan prima\n\nContoh 2:\n\ninput: 44\noutput: [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 ]\nkarena di-range angka 44 hanya bilangan di atas saja yang merupakan bilangan prima\n\n\nRULES:\n- WAJIB membuat algoritma/pseudocode untuk program getPrime\n\nREMINDER ABOUT PSEUDOCODE\n=========================\nContoh Pseudocode yang Kurang Tepat (tidak ada hubungan dengan soal):\nvar num\nfor i = 0 , i < 8, i++\n if i = 5\n num++\n\nContoh Pseudocode yang Benar (tidak ada hubungan dengan soal):\nSTORE num with any value\nWHILE i < 8\n IF i equals to 5\n ADD num by 1\n*/\n\nfunction getPrime(num) {\n // your code here\n if (num <= 2) return [];\n if (num == 3) return [2];\n let result = [2, 3];\n let i = 4;\n while (i <= num) {\n if (isPrime(i)) {\n result.push(i);\n }\n\n i++;\n }\n\n\n\n return result;\n}\n\nfunction isPrime(n) {\n for (let i = 2; i < n; i++) {\n if (n % i == 0) return false;\n }\n return true\n}\n\n\n\nconsole.log(getPrime(5));\nconsole.log(getPrime(10)); // [ 2, 3, 5, 7 ]\nconsole.log(getPrime(23)); // [ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]\nconsole.log(getPrime(44)); // [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 ]\nconsole.log(getPrime(1)); // []\nconsole.log(getPrime(0)); // []"} {"doc_id": "4913b1d79bfa13a5331edbd8147db4e7", "text": "/*\n

      Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

      \n\n

      Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

      \n\n

      For example, 

      \n\n
      \nGiven the tree:\n        4\n       / \\\n      2   7\n     / \\\n    1   3\nAnd the value to insert: 5\n
      \n\n

      You can return this binary search tree:

      \n\n
      \n         4\n       /   \\\n      2     7\n     / \\   /\n    1   3 5\n
      \n\n

      This tree is also valid:

      \n\n
      \n         5\n       /   \\\n      2     7\n     / \\   \n    1   3\n         \\\n          4\n

      \u7ed9\u5b9a\u4e8c\u53c9\u641c\u7d22\u6811\uff08BST\uff09\u7684\u6839\u8282\u70b9\u548c\u8981\u63d2\u5165\u6811\u4e2d\u7684\u503c\uff0c\u5c06\u503c\u63d2\u5165\u4e8c\u53c9\u641c\u7d22\u6811\u3002 \u8fd4\u56de\u63d2\u5165\u540e\u4e8c\u53c9\u641c\u7d22\u6811\u7684\u6839\u8282\u70b9\u3002 \u4fdd\u8bc1\u539f\u59cb\u4e8c\u53c9\u641c\u7d22\u6811\u4e2d\u4e0d\u5b58\u5728\u65b0\u503c\u3002

      \n\n

      \u6ce8\u610f\uff0c\u53ef\u80fd\u5b58\u5728\u591a\u79cd\u6709\u6548\u7684\u63d2\u5165\u65b9\u5f0f\uff0c\u53ea\u8981\u6811\u5728\u63d2\u5165\u540e\u4ecd\u4fdd\u6301\u4e3a\u4e8c\u53c9\u641c\u7d22\u6811\u5373\u53ef\u3002 \u4f60\u53ef\u4ee5\u8fd4\u56de\u4efb\u610f\u6709\u6548\u7684\u7ed3\u679c\u3002

      \n\n

      \u4f8b\u5982, 

      \n\n
      \n\u7ed9\u5b9a\u4e8c\u53c9\u641c\u7d22\u6811:\n\n        4\n       / \\\n      2   7\n     / \\\n    1   3\n\n\u548c \u63d2\u5165\u7684\u503c: 5\n
      \n\n

      \u4f60\u53ef\u4ee5\u8fd4\u56de\u8fd9\u4e2a\u4e8c\u53c9\u641c\u7d22\u6811:

      \n\n
      \n         4\n       /   \\\n      2     7\n     / \\   /\n    1   3 5\n
      \n\n

      \u6216\u8005\u8fd9\u4e2a\u6811\u4e5f\u662f\u6709\u6548\u7684:

      \n\n
      \n         5\n       /   \\\n      2     7\n     / \\   \n    1   3\n         \\\n          4\n
      \n

      \u7ed9\u5b9a\u4e8c\u53c9\u641c\u7d22\u6811\uff08BST\uff09\u7684\u6839\u8282\u70b9\u548c\u8981\u63d2\u5165\u6811\u4e2d\u7684\u503c\uff0c\u5c06\u503c\u63d2\u5165\u4e8c\u53c9\u641c\u7d22\u6811\u3002 \u8fd4\u56de\u63d2\u5165\u540e\u4e8c\u53c9\u641c\u7d22\u6811\u7684\u6839\u8282\u70b9\u3002 \u4fdd\u8bc1\u539f\u59cb\u4e8c\u53c9\u641c\u7d22\u6811\u4e2d\u4e0d\u5b58\u5728\u65b0\u503c\u3002

      \n\n

      \u6ce8\u610f\uff0c\u53ef\u80fd\u5b58\u5728\u591a\u79cd\u6709\u6548\u7684\u63d2\u5165\u65b9\u5f0f\uff0c\u53ea\u8981\u6811\u5728\u63d2\u5165\u540e\u4ecd\u4fdd\u6301\u4e3a\u4e8c\u53c9\u641c\u7d22\u6811\u5373\u53ef\u3002 \u4f60\u53ef\u4ee5\u8fd4\u56de\u4efb\u610f\u6709\u6548\u7684\u7ed3\u679c\u3002

      \n\n

      \u4f8b\u5982, 

      \n\n
      \n\u7ed9\u5b9a\u4e8c\u53c9\u641c\u7d22\u6811:\n\n        4\n       / \\\n      2   7\n     / \\\n    1   3\n\n\u548c \u63d2\u5165\u7684\u503c: 5\n
      \n\n

      \u4f60\u53ef\u4ee5\u8fd4\u56de\u8fd9\u4e2a\u4e8c\u53c9\u641c\u7d22\u6811:

      \n\n
      \n         4\n       /   \\\n      2     7\n     / \\   /\n    1   3 5\n
      \n\n

      \u6216\u8005\u8fd9\u4e2a\u6811\u4e5f\u662f\u6709\u6548\u7684:

      \n\n
      \n         5\n       /   \\\n      2     7\n     / \\   \n    1   3\n         \\\n          4\n
      \n*/\n\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {number} val\n * @return {TreeNode}\n */\nvar insertIntoBST = function(root, val) {\n \n};"} {"doc_id": "492b12bd8b84adb57129557de9d3b9f1", "text": "export default ` Let's continue with the earlier example where we displayed company profile of \\`APPL\\`. Let's say I want to display the Company Profile for \\`FB\\` at some other place in the application. Since we have two variables \\`ticker\\` and \\`companyProfileInfo\\` hard-coded inside this component should I copy and paste the entire component to some other place and replace the \\`ticker\\` and \\`companyProfileInfo\\` to be that of \\`FB\\`?\n\n Well, no. Remember React is about building reusable Components. So we want to build a component called \\`CompanyProfile\\` that can be reused for any company ticker.\n\n Let's look at the \\`CompanyProfile\\` component again. Here we have two variables \\`ticker\\` and \\`companyProfileInfo\\`. So what if instead of hard coding the values of these two variables here inside the component, we could pass those values to this component instead?\n\nIf we were to pass these values to this component from outside, then this Component will not be tied to one Company ticker. We can pass in \\`XYZ\\` and it's profile info to this component and it should be able to render the profile for \\`XYZ\\` or any other company for that matter. This component becomes truly reusable. Wonderful, that's what we want. \n\n\\`\\`\\`jsx\nfunction CompanyProfile(props) {\n //Instead of storing these variables we want to pass\n //these values to this component from outside.\n const ticker = //pass the value for this variable from outside\n const companyProfileInfo = //pass the value for this variable from outside\n return (\n
      \n
      Profile of: {ticker}
      \n
      \n {\n Object.keys(companyProfileInfo)\n .map((key, index) => {\n return
      {key}: {companyProfileInfo[key]}
      \n })\n }\n
      \n
      \n )\n}\n\\`\\`\\`\n\nWell then how do we pass these values to a component from outside? That's where \\`props\\` comes in. In React lingo, \\`props\\` are something that the component is passed by the user of that component (parent component passes \\`props\\` to child component). \nYou can pass anything as a props - \\`function\\`, \\`object\\`, \\`boolean\\`, \\`string\\`, \\`number\\` etc. Here's an example of a Component passing the \\`props\\` to its children.\n\n\\`\\`\\`jsx\nfunction Children(props) {\n return (\n
      {props.textToDisplay}
      \n )\n}\n\nfunction Parent(props) {\n return (\n \n )\n}\n\\`\\`\\`\nThere are couple things going on here. First - remember on the [first page of this tutorial](/tutorial/react-introduction) we said that we can compose components (we can use one component inside the other)? Well that's what we are doing here. \\`Parent\\` component uses \\`Children\\` component inside it's return.\n\nSecond - if you inspect the above code snippet carefully, we see that when the \\`Parent\\` uses the \\`Children\\` (inside \\`return\\`) it's also passing something called \\`textToDisplay\\` with some value \\`Hello\\`. We call this \"passing the props\". So \\`Parent\\` is passing a \\`props\\` called \\`textToDisplay\\` to the \\`Children\\`. How, then, does the \\`Children\\` use the value that the \\`Parent\\` passes down to it?\n\n1. Component created with function\n\n If you created your component as a \\`function\\` like we did here, all the \\`props\\` its \\`Parent\\` passed down will be accessible through the argument. If you look at the \\`Children\\` above it's using \\`props.textToDisplay\\` inside the \\`div\\`. All the \\`props\\` passed to the \\`Children\\` are passed as this single \\`props\\` argument. For example, if the \\`Parent\\` had passed a props called \\`defaultValue\\`, the \\`Children\\` would access it as \\`props.defaultValue\\`.\n\n2. Component created as React.Component\n\n If you created your Component by extending \\`React.Component\\` then all the \\`props\\` would be available as \\`this.props\\`. The equivalent of above \\`Children\\` function using \\`React.Component\\` would look like this:\n\n\\`\\`\\`jsx\nclass Children extends React.Component {\n render(){\n return (\n
      {this.props.textToDisplay}
      \n )\n }\n}\n\\`\\`\\`\n\nNow that we know what \\`props\\` are, lets do some exercise and see how we can make \\`CompanyProfile\\` component reusable.\n\n\n\n\nOne thing you must remember regarding \\`props\\` is that you should **never** mutate \\`props\\` - React will complain if you do. This is something given to the component by it's parent - accept with love and don't try to mess around with things to make your parent angry!\n\n\\`\\`\\`jsx\nfunction Children(props) {\n //\u274c NEVER DO THIS\n props.textToDisplay = 'I want to mutate props'\n return (\n
      {props.textToDisplay}
      \n )\n}\n\\`\\`\\`\n\n### PropTypes\nIn many cases it's better for a component to clearly define a contract regarding the \\`props\\` it can accept - data type, data structure, if the props is required etc. \nThere are couple obvious benefits of this:\n- React can enforce type checking to avoid many bugs arising from parents passing props with a type that's different from what the children expects (ex. parent passing \\`string\\` when children expects an \\`object\\`).\n- If you are writing components that will be used by different people at different parts of the application, it's always useful for those users to know what are the props they can pass, what is the expected structure of the props etc.\n\nTo define this contract - first you need to add \\`prop-types\\` as a [project dependency (provided by React team)](https://www.npmjs.com/package/prop-types) and you need to define a special property called \\`propTypes\\` in your component.\n\n\\`\\`\\`jsx\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\nclass SoftwareEngineer extends React.Component {\n render(){\n return (...)\n }\n}\n\n//defines \"propTypes\" property in this component\nSoftwareEngineer.propTypes = {\n name: PropTypes.string.isRequired, //expects string and is required\n hobbies: PropTypes.arrayOf(PropTypes.string), //expects array of string\n address: PropTypes.shape({\n street: PropTypes.string,\n city: PropTypes.string\n }) //must be an object with 'street' and 'city' fields\n}\n\\`\\`\\`\nHere we have defined the \\`propTypes\\` property and assigned an object. Each key in this object represents the name of the \\`props\\` the user of this component can pass. The value defines the \"type\" of the \\`props\\` - you know \\`string\\`, \\`number\\`, \\`array\\` etc. All \\`props\\` are optional (user of the component doesn't have to pass them) except the one that has \\`.isRequired\\`. Here's a quick explanation on three \\`props\\` defined above:\n- \\`name\\` - It expects the value of this \\`props\\` to be a \\`string\\` and it's required because, well, it has \\`.isRequired\\`.\n- \\`hobbies\\` - It's optional but if passed it must be an array of strings.\n- \\`address\\` - It's also optional but if passed it must be an object with two fields - \\`street\\` and \\`city\\` and both must be string.\n\nThese are just some examples of what you can do to enable type checking. There are plenty more types you can define - please check out [the documentation](https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes) for more.\n\n### Default Props\nIn some cases you might want to define a default value for a \\`props\\` in case it is not passed to you.\nYou can use \\`defaultProps\\` property to define your defaults. With this you're basically saying - \"if someone doesn't pass me a value for a \\`props\\` that I'm expecting, then I want the value of that \\`props\\` to be what I have defined in the \\`defaultProps\\`\". For example - for above component we can define \\`defaultProps\\` as follows:\n\n\\`\\`\\`jsx\nimport React from 'react';\nimport PropTypes from 'prop-types';\n\nclass SoftwareEngineer extends React.Component {\n render(){\n //if this props is not passed, it will print default value as defined by \\`defaultProps\\`\n console.log(this.props.hobbies);\n\n //if this props is not passed, it will print \\`undefined\\` because we haven't defined any default value for this props\n console.log(this.props.address); \n return (...)\n }\n}\n\n//defines \"defaultProps\" property in this component\nSoftwareEngineer.defaultProps = {\n hobbies: ['Writing React code']\n}\n\\`\\`\\`\n\nLet's say if the user of this component doesn't pass any value for \\`hobbies\\`, then it will be defaulted to \\`['Writing React code']\\`.\nAnd if the user of the component doesn't pass any value for \\`address\\` then it will resolve to \\`undefined\\` because we haven't defined the default value for it.\n `"} {"doc_id": "499a5fd4970dad893d008126198bfcad", "text": "// Chapter 2: Linked Lists\n// Solutions originally solved on repl.it, please see: https://repl.it/@khd25/\n//==============================================================================\n\n/*\n\nQuestion 2.6b - Is a Singly Linked List a Palindrome:\n\nR(ephrase): in a SLL where each node's value is a letter in a word, check whether the word is a palindrome or not\n\nE(xamples):\n Input:\n |t|->|a|->|c|->|o|->|c|->|a|->|t|->|NULL| \n \n Check each item against the reverse:\n |NULL|<-|t|<-|a|<-|c|<-|o|<-|c|<-|a|<-|t|\n\n Output: true\n\nA(pproach):\n-> set a var reverseCopy to a new, empty SLL\n-> in a while loop make a copy of original list into reverseCopy, but copy it in reverse using \"append\" method instead of \"prepend\" method\n-> make sure current goes back to original list's head, and copy current is reverse copy's head\n-> while loop again and check that current vals are matching set\n -if not, return false immediately\n -if loop completes, return true\n\nC(ode): (NOTE: the following code is case sensitive)\n\n*/\nclass SinglyLinkedList {\n constructor() {\n this.head = this.tail = null;\n }\n // adds node to end\n append(value) {\n // if list is empty\n if (!this.tail) {\n this.head = this.tail = new Node(value);\n } else {\n let oldTail = this.tail;\n this.tail = new Node(value);\n oldTail.next = this.tail;\n }\n }\n // adds node to beginning\n prepend(value) {\n // if list is empty\n if (!this.head) {\n this.head = this.tail = new Node(value);\n } else {\n let oldHead = this.head;\n this.head = new Node(value);\n this.head.next = oldHead;\n }\n }\n}\n\nclass Node {\n constructor(value, next = null) {\n this.value = value;\n this.next = next;\n }\n}\n\nfunction isPalindrome(list) {\n // Optimize:\n if (!list.head) {\n throw new Error('input is an empty list');\n }\n if (!list.head.next) {\n return true;\n }\n let reverseCopy = new SinglyLinkedList();\n let current = list.head;\n let counter = 1;\n\n while (current) {\n reverseCopy.prepend(current.value);\n current = current.next;\n ++counter;\n }\n\n let halfway = Math.floor(counter / 2);\n let newCounter = 1;\n current = list.head;\n copyCurrent = reverseCopy.head;\n\n while (newCounter <= halfway) {\n if (current.value !== copyCurrent.value) {\n return false;\n }\n ++newCounter;\n current = current.next;\n copyCurrent = copyCurrent.next;\n }\n\n return true;\n}\n\n// T(est):\n\nlet myList = new SinglyLinkedList();\n\nmyList.append('t');\nmyList.append('a');\nmyList.append('c');\nmyList.append('o');\nmyList.append('c');\nmyList.append('a');\nmyList.append('t');\n\nlet myList2 = new SinglyLinkedList();\n\nmyList2.append('h');\nmyList2.append('a');\nmyList2.append('n');\nmyList2.append('n');\nmyList2.append('a');\nmyList2.append('h');\n\nlet myList3 = new SinglyLinkedList();\n\nmyList3.append('h');\nmyList3.append('a');\nmyList3.append('n');\nmyList3.append('n');\nmyList3.append('a');\nmyList3.append('h');\nmyList3.append('h');\n\nlet myList4 = new SinglyLinkedList();\n\nmyList4.append('K');\n\nlet myList5 = new SinglyLinkedList();\n\nconsole.log('myList1: ', isPalindrome(myList)); // expect true\nconsole.log('myList2: ', isPalindrome(myList2)); // expect true\nconsole.log('myList3: ', isPalindrome(myList3)); // expect false\nconsole.log('myList4: ', isPalindrome(myList4)); // expect true\nconsole.log('myList5: ', isPalindrome(myList5)); // expect error\n\n// O(ptimize):\n// see lines 67 - 73, 84, 85, 89\n// O(N) time, O(N) space, where N is the total number of nodes\n"} {"doc_id": "4b748f199725204318d0074cac315b73", "text": "/*\n

      This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.

      \n\n
      \n\n

      Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk.  After concatenating them, the result equals the sorted array.

      \n\n

      What is the most number of chunks we could have made?

      \n\n

      Example 1:

      \n\n
      \nInput: arr = [5,4,3,2,1]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n
      \n\n

      Example 2:

      \n\n
      \nInput: arr = [2,1,3,4,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n
      \n\n

      Note:

      \n\n
        \n\t
      • arr will have length in range [1, 2000].
      • \n\t
      • arr[i] will be an integer in range [0, 10**8].
      • \n
      \n\n

       

      \u8fd9\u4e2a\u95ee\u9898\u548c“\u6700\u591a\u80fd\u5b8c\u6210\u6392\u5e8f\u7684\u5757”\u76f8\u4f3c\uff0c\u4f46\u7ed9\u5b9a\u6570\u7ec4\u4e2d\u7684\u5143\u7d20\u53ef\u4ee5\u91cd\u590d\uff0c\u8f93\u5165\u6570\u7ec4\u6700\u5927\u957f\u5ea6\u4e3a2000\uff0c\u5176\u4e2d\u7684\u5143\u7d20\u6700\u5927\u4e3a10**8\u3002

      \n\n

      arr\u662f\u4e00\u4e2a\u53ef\u80fd\u5305\u542b\u91cd\u590d\u5143\u7d20\u7684\u6574\u6570\u6570\u7ec4\uff0c\u6211\u4eec\u5c06\u8fd9\u4e2a\u6570\u7ec4\u5206\u5272\u6210\u51e0\u4e2a“\u5757”\uff0c\u5e76\u5c06\u8fd9\u4e9b\u5757\u5206\u522b\u8fdb\u884c\u6392\u5e8f\u3002\u4e4b\u540e\u518d\u8fde\u63a5\u8d77\u6765\uff0c\u4f7f\u5f97\u8fde\u63a5\u7684\u7ed3\u679c\u548c\u6309\u5347\u5e8f\u6392\u5e8f\u540e\u7684\u539f\u6570\u7ec4\u76f8\u540c\u3002

      \n\n

      \u6211\u4eec\u6700\u591a\u80fd\u5c06\u6570\u7ec4\u5206\u6210\u591a\u5c11\u5757\uff1f

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: arr = [5,4,3,2,1]\n\u8f93\u51fa: 1\n\u89e3\u91ca:\n\u5c06\u6570\u7ec4\u5206\u62102\u5757\u6216\u8005\u66f4\u591a\u5757\uff0c\u90fd\u65e0\u6cd5\u5f97\u5230\u6240\u9700\u7684\u7ed3\u679c\u3002\n\u4f8b\u5982\uff0c\u5206\u6210 [5, 4], [3, 2, 1] \u7684\u7ed3\u679c\u662f [4, 5, 1, 2, 3]\uff0c\u8fd9\u4e0d\u662f\u6709\u5e8f\u7684\u6570\u7ec4\u3002 \n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165: arr = [2,1,3,4,4]\n\u8f93\u51fa: 4\n\u89e3\u91ca:\n\u6211\u4eec\u53ef\u4ee5\u628a\u5b83\u5206\u6210\u4e24\u5757\uff0c\u4f8b\u5982 [2, 1], [3, 4, 4]\u3002\n\u7136\u800c\uff0c\u5206\u6210 [2, 1], [3], [4], [4] \u53ef\u4ee5\u5f97\u5230\u6700\u591a\u7684\u5757\u6570\u3002 \n
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • arr\u7684\u957f\u5ea6\u5728[1, 2000]\u4e4b\u95f4\u3002
      • \n\t
      • arr[i]\u7684\u5927\u5c0f\u5728[0, 10**8]\u4e4b\u95f4\u3002
      • \n
      \n

      \u8fd9\u4e2a\u95ee\u9898\u548c“\u6700\u591a\u80fd\u5b8c\u6210\u6392\u5e8f\u7684\u5757”\u76f8\u4f3c\uff0c\u4f46\u7ed9\u5b9a\u6570\u7ec4\u4e2d\u7684\u5143\u7d20\u53ef\u4ee5\u91cd\u590d\uff0c\u8f93\u5165\u6570\u7ec4\u6700\u5927\u957f\u5ea6\u4e3a2000\uff0c\u5176\u4e2d\u7684\u5143\u7d20\u6700\u5927\u4e3a10**8\u3002

      \n\n

      arr\u662f\u4e00\u4e2a\u53ef\u80fd\u5305\u542b\u91cd\u590d\u5143\u7d20\u7684\u6574\u6570\u6570\u7ec4\uff0c\u6211\u4eec\u5c06\u8fd9\u4e2a\u6570\u7ec4\u5206\u5272\u6210\u51e0\u4e2a“\u5757”\uff0c\u5e76\u5c06\u8fd9\u4e9b\u5757\u5206\u522b\u8fdb\u884c\u6392\u5e8f\u3002\u4e4b\u540e\u518d\u8fde\u63a5\u8d77\u6765\uff0c\u4f7f\u5f97\u8fde\u63a5\u7684\u7ed3\u679c\u548c\u6309\u5347\u5e8f\u6392\u5e8f\u540e\u7684\u539f\u6570\u7ec4\u76f8\u540c\u3002

      \n\n

      \u6211\u4eec\u6700\u591a\u80fd\u5c06\u6570\u7ec4\u5206\u6210\u591a\u5c11\u5757\uff1f

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: arr = [5,4,3,2,1]\n\u8f93\u51fa: 1\n\u89e3\u91ca:\n\u5c06\u6570\u7ec4\u5206\u62102\u5757\u6216\u8005\u66f4\u591a\u5757\uff0c\u90fd\u65e0\u6cd5\u5f97\u5230\u6240\u9700\u7684\u7ed3\u679c\u3002\n\u4f8b\u5982\uff0c\u5206\u6210 [5, 4], [3, 2, 1] \u7684\u7ed3\u679c\u662f [4, 5, 1, 2, 3]\uff0c\u8fd9\u4e0d\u662f\u6709\u5e8f\u7684\u6570\u7ec4\u3002 \n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165: arr = [2,1,3,4,4]\n\u8f93\u51fa: 4\n\u89e3\u91ca:\n\u6211\u4eec\u53ef\u4ee5\u628a\u5b83\u5206\u6210\u4e24\u5757\uff0c\u4f8b\u5982 [2, 1], [3, 4, 4]\u3002\n\u7136\u800c\uff0c\u5206\u6210 [2, 1], [3], [4], [4] \u53ef\u4ee5\u5f97\u5230\u6700\u591a\u7684\u5757\u6570\u3002 \n
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • arr\u7684\u957f\u5ea6\u5728[1, 2000]\u4e4b\u95f4\u3002
      • \n\t
      • arr[i]\u7684\u5927\u5c0f\u5728[0, 10**8]\u4e4b\u95f4\u3002
      • \n
      \n*/\n\n\n/**\n * @param {number[]} arr\n * @return {number}\n */\nvar maxChunksToSorted = function(arr) {\n \n};"} {"doc_id": "4b7feb9c2bed251643f939838b39fbc3", "text": "// I paired [by myself] on this challenge.\n\n\n\n\n// Pseudocode\n// Opened commandline and ran this file using node.js\n// Got \"ERROR: The value of secretNumber should be a number.\"\n// made a new variable, secretNumber, equal to 10\n// Got \"ERROR: The value of secretNumber should be 7\"\n// changed the value of the secretNumber variable to 7\n// code accepted, moving on to next part\n// \n// Got \"ERROR: The value of password should be a string.\"\n// made a new variable, password, equal to string \"whats the pass?\"\n// Got \"ERROR: The value of password should be 'just open the door'\"\n// changed the password variable to be equal to the string \"just open the door\"\n// code accepted, moving on to next part\n// \n// Got \"ERROR: The value of allowedIn should be a boolean\"\n// made a new variable, allowedIn, with a value equal to the boolean false.\n// code accepted, moving onto next part\n// \n// Got \"members instanceof Array\", and \"ReferenceError: members is not defined\"\n// made a new variable, members, and set it equal to an array containing \"sam\" and \"annatina\"\n// Got \"ERROR: the first element in the value of members should be 'John'\"\n// changing members variable to equal array with 'John' inside.\n// Got \"ERROR: the fourth elements in the value of members should be 'Mary'\"\n// changing members variable to equal array with 'john', 'sam','annatina', and 'mary' inside \n// code accepted, challenge over\n\n// __________________________________________\n// Write your code below.\nvar secretNumber= 7;\nvar password = \"just open the door\";\nvar allowedIn= false;\nvar members = [\"John\", \"sam\", \"annatina\", \"Mary\"];\n\n\n// __________________________________________\n// Refactored Code: Include a refactored version (or justification of your original code) here. \n\n// I feel as though my variable names are descriptive and as short as possible. It also is not DRY.\n// In terms of refactoring, I believe my code could be changed so that it takes up less lines\n// however I feel like this would reduce the readability of the code for the sake of short code.\n// That being said I will keep my code how it is.\n\n\n// __________________________________________\n// Reflection: Use the reflection guidelines to write a reflection here. \n// \n// In this challenge I revised how to define local variables in javascript, \n// and how to create objects of different types. One tricky concept was Test-Driven Development\n// and using my text editor and command line together in order to quickly and effectively test my code.\n// Although once I tried this a few times it became much easier and it seems like a very useful skill to have.\n// Looking at the pros and cons of refactoring my code was interesting and the readability vs. short code debate is\n// clearly important to any code. \n// \n// \n// \n// \n// __________________________________________\n// Driver Code: Do not alter code below this line.\n\nfunction assert(test, message, test_number) {\n if (!test) {\n console.log(test_number + \"false\");\n throw \"ERROR: \" + message;\n }\n console.log(test_number + \"true\");\n return true;\n}\n\nassert(\n (typeof secretNumber === 'number'),\n \"The value of secretNumber should be a number.\",\n \"1. \"\n)\n\nassert(\n secretNumber === 7,\n \"The value of secretNumber should be 7.\",\n \"2. \"\n)\n\nassert(\n typeof password === 'string',\n \"The value of password should be a string.\",\n \"3. \"\n)\n\nassert(\n password === \"just open the door\",\n \"The value of password should be 'just open the door'.\",\n \"4. \"\n)\n\nassert(\n typeof allowedIn === 'boolean',\n \"The value of allowedIn should be a boolean.\",\n \"5. \"\n)\n\nassert(\n allowedIn === false,\n \"The value of allowedIn should be false.\",\n \"6. \"\n)\n\nassert(\n members instanceof Array,\n \"The value of members should be an array\",\n \"7. \"\n)\n\nassert(\n members[0] === \"John\",\n \"The first element in the value of members should be 'John'.\",\n \"8. \"\n)\n\nassert(\n members[3] === \"Mary\",\n \"The fourth element in the value of members should be 'Mary'.\",\n \"9. \"\n)\n\n\n"} {"doc_id": "4c011485ac15a186d83135cba85fb1b6", "text": "/**\n * A JavaScript **Promise** is created with the new Promise constructor function - new Promise(). A promise will let you start some work that will be done asynchronously and let you get back to your regular work. When you create the promise, you must give it the code that will be run asynchronously. You provide this code as the argument of the constructor function:\n */\n\nlet myPromise = new Promise(function (resolve, reject) {\n setTimeout(function createSundae (flavor = 'chocolate') {\n if (flavor) {\n const sundae = { flavor }\n // request ice cream\n // get cone\n // warm up ice cream scoop\n // scoop generous portion into cone!\n console.log(sundae)\n resolve(sundae)\n } else {\n reject(new Error('We need a flavor!'))\n }\n }, Math.random() * 2000)\n})\nmyPromise.then((sundae) => console.log('The promise ends successfully.', sundae))\nmyPromise.catch((error) => console.log('The promise fails.', error))\nmyPromise.finally(() => console.log('This is the finally of the promise.'))\nconsole.log('-------------------------')\nconsole.log(myPromise)\nconsole.log('waiting')\n\nmyPromise = new Promise(function (resolve, reject) {\n setTimeout(function createSundae (flavor) {\n if (flavor) {\n const sundae = { flavor }\n // request ice cream\n // get cone\n // warm up ice cream scoop\n // scoop generous portion into cone!\n console.log(sundae)\n resolve(sundae)\n } else {\n reject(new Error('We need a flavor!'))\n }\n }, Math.random() * 5000)\n})\nmyPromise.then((sundae) => console.log('The promise ends successfully.', sundae))\nmyPromise.catch((error) => console.log('The promise fails.', error))\nmyPromise.finally(() => console.log('This is the finally of the promise.'))\nconsole.log('-------------------------')\nconsole.log(myPromise)\nconsole.log('waiting')\n"} {"doc_id": "4c5866cc956404997cedcf43474b663f", "text": "// Enumerating Properties of an Object/Vy\u010d\u00edslenie vlastnost\u00ed objektu\n\nconst circle = {\n radius: 1,\n draw() {\n console.log('draw');\n }\n};\n\nfor (let key in circle) {\n console.log('-------------');\n console.log(key);\n console.log(circle[key]);\n console.log('-------------');\n}\n\nfor (let key of Object.keys(circle)) {\n console.log(key);\n}\n\nfor (let entry of Object.entries(circle)) // Object je definovan\u00fd parameter kt. obs. objekt v kt. su metod\u00fd ako je napr. entries\n console.log(entry);\n\nif ('radius' in circle) { \n console.log('yes');\n}\n"} {"doc_id": "4c72fe0195d89fda2c1c62f762075a31", "text": "//function should output the inputted array with \"My name is\" added in front of each name\n\nvar people = [ \n { name: \"John\", age: 55 }, \n { name: \"Roger\", age: 44 },\n { Name: \"Betty\", age: 37 }\n ]\n\nfunction returnNames(names){\n let output = [];\n for ( var i = 0; i < names.length; i++) {\n output.push(\"My name is \" + names[i].name)\n }\n return output\n}\nreturnNames(people)\n// ctrl c to stop terminal\n\n//do not edit\nmodule.exports = returnNames; \nmodule.exports.people = people;\n\n"} {"doc_id": "4d2fc3574eadeddcfe675cbb1a6246c7", "text": "// var primeiroValor = prompt(\"Digite o primeiro valor:\")\n// var primeiroValorInt = parseInt(primeiroValor)\nvar primeiroValor = parseInt(prompt(\"Digite o primeiro n\u00famero inteiro:\"))\nvar segundoValor = parseInt(prompt(\"Digite o segundo n\u00famero inteiro:\"))\n\nvar operacao = prompt(\"Digite:\\n 1 para fazer uma divis\u00e3o\\n 2 para multiplica\u00e7\u00e3o\\n 3 para subtra\u00e7\u00e3o\\n 4 para adi\u00e7\u00e3o\")\n\n//var resultado = primeiroValor * segundoValor\n\n//document.write(\"

      \" + resultado + \"

      \")\n//document.write(\"

      \" + primeiroValor + \" x \" + segundoValor + \" = \" + resultado + \"

      \")\n\nvar sinal;\n\nif (operacao == 1) {\n sinal = \" / \"\n var resultado = primeiroValor / segundoValor\n document.write(\"

      \" + primeiroValor + sinal + segundoValor + \" = \" + resultado + \"

      \")\n} else if (operacao == 2) {\n sinal = \" x \"\n var resultado = primeiroValor * segundoValor\n document.write(\"

      \" + primeiroValor + sinal + segundoValor + \" = \" + resultado + \"

      \")\n} else if (operacao == 3) {\n sinal = \" - \"\n var resultado = primeiroValor - segundoValor\n document.write(\"

      \" + primeiroValor + sinal + segundoValor + \" = \" + resultado + \"

      \")\n} else if (operacao == 4) {\n sinal = \" + \"\n var resultado = primeiroValor + segundoValor\n document.write(\"

      \" + primeiroValor + sinal + segundoValor + \" = \" + resultado + \"

      \")\n} else {\n document.write(\"

      Op\u00e7\u00e3o Inv\u00e1lida

      \")\n}\n\n// if = se\n// else = sen\u00e3o\n// else if = sen\u00e3o se\n\n// escrevendo na tela: document.write()\n// concatena\u00e7\u00e3o: (juntar palavras e vari\u00e1veis com + e \"\") ex: (\"palavra\" + vari\u00e1vel)\n// compara\u00e7\u00e3o: ==\n// atribui\u00e7\u00e3o: =\n// opera\u00e7\u00f5es: + - * /"} {"doc_id": "4d4631f05336e51d79c4dc89b29c9822", "text": "let name = ' Jack Sparrow '\n\n// length property\nconsole.log(name.length)\n\n// convert to uppercase (method)\nconsole.log(name.toUpperCase())\n\n// convert to lowercase (method)\nconsole.log(name.toLowerCase())\n\n// includes method\nlet password = 'abc123password098'\nconsole.log(password.includes('password'))\n\n// trim method\nconsole.log(name.trim())\n\n\n\n// Challenge area\n\n// isValidPassword (t/f)\nlet isValidPassword = function (password) {\n if (password.length > 8 && !password.includes('password')) {\n return true\n } else {\n return false\n }\n // can also be written as:\n // return password.length > 8 && !password.includes('password')\n}\n// true if length is more than 8, and doesn't contain the word \"password\"\n\nconsole.log(isValidPassword('asdf'))\nconsole.log(isValidPassword('abcdefghijklmnop'))\nconsole.log(isValidPassword('asdfpassword1234'))"} {"doc_id": "4d941ab2c01326c4facad4f073e8a7b4", "text": "// What will be printed if we run the previous code snippet?\nlet a = 7;\nif (a < 5) {\n console.log(a / 2);\n} else {\n console.log(a * 2);\n}\n// What should be changed to get 1 printed to the console?\nlet b = 7;\nif (b) {\n console.log(1);\n} else {\n console.log('Please, define b.')\n}\n//:-)\n\n// Create a loop which prints the numbers from 0-9.\n\nfor (let i = 0; i < 10; i++){\n console.log(i);\n}\n// Change the previous loop to print the numbers from 1 to 10.\nfor (let j = 1; j < 11; j++){\n console.log(j);\n}\n// Print the even numbers between 0 and 20.\nfor (let k = 0; k < 20; k++){\n if (k % 2 === 0) {\n console.log(k);\n }\n}\n\n// Use your previous for loops and create a function which print the first N numbers.\n\nconst firstNumbers = (finalNumber) => {\n for (let num = 1; num <= finalNumber; num++){\n console.log(num);\n }\n}\n\nfirstNumbers(3);\n\n// Create a function which gets a name as parameter and then returns a greeting to the specified person.\n\nconst greeting = (name) => {\n return `Hello ${name}!`\n}\n\nconsole.log(greeting('Pepa'));\n\n// Create a function which gets an array as parameter and prints each value from it. (using loop)\n\n\nconst printArrayElement = (array) => {\n for (let element = 0; element < array.length; element++) {\n console.log(array[element]);\n }\n}\n\nprintArrayElement([0,3,6,7,9]);\n\n// Change your previous printValues function to use forEach loop.\n\nconst printArrayElement2 = (array2) => {\n array2.forEach(element2 => console.log(element2))\n}\n\nprintArrayElement2([10,20,30,50,12]);"} {"doc_id": "4dff1b30f88fea6bbeaff86ea35e3f16", "text": "// Assignment Code\nvar generateBtn = document.querySelector(\"#generate\");\nvar availableCharacters = \"\";\nvar newPassword = \"\";\n\n// Character generation variables \nvar lowerCase = \"abcdefghijklmnopqrstuvwxyz\";\nvar upperCase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nvar numeric = \"123456789\";\nvar specialCharacters = \"!#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\";\n\n// Write password to the #password input\nfunction writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}\n\n// Add event listener to generate button\n//call writePassword function \ngenerateBtn.addEventListener(\"click\", writePassword);\n\nfunction generatePassword() {\n //Prompts and confirms\n passwordLength = prompt(\"Pick a character count between 8 and 128 for your password:\")\n var lCCharacter = confirm(\"Do you want to include a lowercase character?\");\n var uCCharacter = confirm(\"Do you want to include an uppercase character?\");\n var num = confirm(\"Do you want to include an numeric character?\");\n var specChar = confirm(\"Do you want to include a special characters?\");\n\n\n //Conditional statement \n\n if (passwordLength < 8 || passwordLength > 128) {\n prompt(\"Please enter a number between 8 and 128 characters:\")\n }; \n if(lCCharacter){\n availableCharacters = availableCharacters + lowerCase;\n };\n if(uCCharacter){\n availableCharacters = availableCharacters + upperCase;\n };\n if (num){\n availableCharacters = availableCharacters + numeric;\n };\n if (specChar) {\n availableCharacters = availableCharacters + specChar;\n };\n\n //validate the inputs at least one character type should be selected might put outside to call over again\n var confirmPassword = confirm(\n \"Created a password with the following characters: Lowercase \" + lCCharacter\n + \" Uppercase \" + uCCharacter\n + \" Numeric \" + num \n + \"Special Characters \" + specChar)\n if (!confirmPassword){\n generatePassword();\n }\n //number generation \n for (i = 1; i < passwordLength; i++ ){\n\n var randomNumber = Math.floor(Math.random() * availableCharacters.length);\n console.log(randomNumber)\n var randomCharacter = availableCharacters[randomNumber];\n console.log(randomCharacter);\n \n \n newPassword += randomCharacter;\n console.log(newPassword);\n \n } \n\n //return password \n \n return newPassword \n // length between 8-128\n \n \n\n \n\n}\n\n//functions \n//generate password with x many characters for loop i<=x then pick each characrter option \n//generate a password with lowercase character pick a i = randomnumber between 1-28 then do lowercase[i]\n// generate a password with uppercase characters pick a i = random number between 1-28 then do uppercase[i]\n//generate a password with speical characters pick a random number between the specialCharacter.length to insert into the password array \n\n\n// genpassword = {\n// // 97-122 charset\n// //65-90 charset\n\n\n// };\n\n\n//for loop that is going through the \n\n// // prompts for password \n\n// \n\n\n// conditional statement for all prompts to be anwnsered with at least one character selected \n// password that matches criteria created \n// password \n// // WHEN the password is generated\n// // THEN the password is either displayed in an alert or written to the page\n\n\n// when they pick characters add that array into the password array after each character question. at the end you will do a for loop over it to randomly \n//remeber to empty the mega array at the end \n\n\n\n\n\n// variables \n\n\n// function dfintions \n// function calls \n// event listeners \n// console.log(\"Password Character length: \", passwordLength)\n//conditional if true generate a password with this many characters \n // character types \n // lowercase\n\n// console.log(\"Lowercase Characters included: \", lCCharacter);\n // console.log(\"Password Characters available: \",passArray);\n //conditional if true generate a password with lowercase character\n //else do not generate a password with a lowercase character \n //create a function for a password with a lowercase character \n //uppercase\n \n\n// console.log(\"Uppercase Characters included: \", uCCharacter);\n // console.log(\"Password Characters available: \",passArray);\n //conditional if true generate a password with uppercase character \n //elsef do not generate a password with a lowercase character\n //create a function for a password with a uppercase character \n // numeric\n \n// console.log(\"Numeric Characters included: \", num);\n // console.log(\"Password Characters available: \", passArray);\n //conditional if true generate a password with a numeric character \n //else do not genrate a password with a numeric character \n //create a function for a password with a\n // special characters \n\n// console.log(\"Special Characters included: \", specChar);\n // console.log(\"Password Characters available: \", passArray);\n\n\n\n\n//create a function for a password with a a special character\n\n \n\n //generate password "} {"doc_id": "4e047e815302dda2a54aa8eeab753c20", "text": "/*\n

      Compare two version numbers version1 and version2.
      \nIf version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.

      \n\n

      You may assume that the version strings are non-empty and contain only digits and the . character.
      \nThe . character does not represent a decimal point and is used to separate number sequences.
      \nFor instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.

      \n\n

      Here is an example of version numbers ordering:

      \n\n
      \n0.1 < 1.1 < 1.2 < 13.37
      \n\n

      Credits:
      \nSpecial thanks to @ts for adding this problem and creating all test cases.

      \n

      \u6bd4\u8f83\u4e24\u4e2a\u7248\u672c\u53f7 version1 \u548c version2\u3002
      \n\u5982\u679c version1 > version2 \u8fd4\u56de 1\uff0c\u5982\u679c version1 < version2 \u8fd4\u56de -1\uff0c \u9664\u6b64\u4e4b\u5916\u8fd4\u56de 0\u3002

      \n\n

      \u4f60\u53ef\u4ee5\u5047\u8bbe\u7248\u672c\u5b57\u7b26\u4e32\u975e\u7a7a\uff0c\u5e76\u4e14\u53ea\u5305\u542b\u6570\u5b57\u548c . \u5b57\u7b26\u3002

      \n\n

       . \u5b57\u7b26\u4e0d\u4ee3\u8868\u5c0f\u6570\u70b9\uff0c\u800c\u662f\u7528\u4e8e\u5206\u9694\u6570\u5b57\u5e8f\u5217\u3002

      \n\n

      \u4f8b\u5982\uff0c2.5 \u4e0d\u662f“\u4e24\u4e2a\u534a”\uff0c\u4e5f\u4e0d\u662f“\u5dee\u4e00\u534a\u5230\u4e09”\uff0c\u800c\u662f\u7b2c\u4e8c\u7248\u4e2d\u7684\u7b2c\u4e94\u4e2a\u5c0f\u7248\u672c\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: version1 = "0.1", version2 = "1.1"\n\u8f93\u51fa: -1
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: version1 = "1.0.1", version2 = "1"\n\u8f93\u51fa: 1
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \u8f93\u5165: version1 = "7.5.2.4", version2 = "7.5.3"\n\u8f93\u51fa: -1
      \n

      \u6bd4\u8f83\u4e24\u4e2a\u7248\u672c\u53f7 version1 \u548c version2\u3002
      \n\u5982\u679c version1 > version2 \u8fd4\u56de 1\uff0c\u5982\u679c version1 < version2 \u8fd4\u56de -1\uff0c \u9664\u6b64\u4e4b\u5916\u8fd4\u56de 0\u3002

      \n\n

      \u4f60\u53ef\u4ee5\u5047\u8bbe\u7248\u672c\u5b57\u7b26\u4e32\u975e\u7a7a\uff0c\u5e76\u4e14\u53ea\u5305\u542b\u6570\u5b57\u548c . \u5b57\u7b26\u3002

      \n\n

       . \u5b57\u7b26\u4e0d\u4ee3\u8868\u5c0f\u6570\u70b9\uff0c\u800c\u662f\u7528\u4e8e\u5206\u9694\u6570\u5b57\u5e8f\u5217\u3002

      \n\n

      \u4f8b\u5982\uff0c2.5 \u4e0d\u662f“\u4e24\u4e2a\u534a”\uff0c\u4e5f\u4e0d\u662f“\u5dee\u4e00\u534a\u5230\u4e09”\uff0c\u800c\u662f\u7b2c\u4e8c\u7248\u4e2d\u7684\u7b2c\u4e94\u4e2a\u5c0f\u7248\u672c\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: version1 = "0.1", version2 = "1.1"\n\u8f93\u51fa: -1
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: version1 = "1.0.1", version2 = "1"\n\u8f93\u51fa: 1
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \u8f93\u5165: version1 = "7.5.2.4", version2 = "7.5.3"\n\u8f93\u51fa: -1
      \n*/\n\n\n/**\n * @param {string} version1\n * @param {string} version2\n * @return {number}\n */\nvar compareVersion = function(version1, version2) {\n \n};"} {"doc_id": "4e09975fcbfdcae5759e4ede78889962", "text": "/*\n# Word Count\n\nWrite a program that given a phrase can count the occurrences of each word in that phrase.\n\nFor example for the input `\"olly olly in come free\"`\n\n```plain\nolly: 2\nin: 1\ncome: 1\nfree: 1\n```\n\n### Instructions\n1. Review the description, and create a count method that returns an object.\n2. Once you have a passing test suite, add your code to your daily-challenges repo\n3. Link us to your word-count.js file on Slack.\n\n*/\n\n// will return an object with format: {word : wordcount}\nfunction count(string) {\n const output = {};\n\t// var ray = string.split(/\\s+|\\n+/); // split based on whitespace (tabs, space, etc.)\n const ray = string.trim().split(/[\\s\\n\\t]+/); // split based on whitespace (tabs, space, etc.)\n\n\t// init every word as a key for the output\n for (let word of ray) {\n if (ray.length !== 0) {\n // get current word\n // word = ray[i];\n // lowercase just to keep the count case-insensitive\n word = word.toLowerCase();\n output[word] = 0; // init to 0 at first\n }\n }\n\n\t// increase count for each word\n for (let word of ray) {\n // word = ray[i]; // get current word;\n word = word.toLowerCase(); // lowercase just to keep the count case-insensitive\n\n console.log(`${output[word]}`);\n output[word]++; // otherwise just add one to the count\n console.log(word);\n }\n\n console.log('');\n console.log('Results: ');\n\n\t// output for sanity check and debugging\n for (const word of Object.keys(output)) {\n console.log(`${word}`);\n }\n\n console.log('--------: ');\n\t// console.log(`--------: `);\n return output;\n}\n\ncount('word');\n\n// / -- do not edit below ---\n\nxdescribe('count()', () => {\n it('counts one word', () => {\n const expectedCounts = { word: 1 };\n expect(count('word')).toEqual(expectedCounts);\n });\n\n it('counts one of each', () => {\n const expectedCounts = { one: 1, of: 1, each: 1 };\n expect(count('one of each')).toEqual(expectedCounts);\n });\n\n it('counts multiple occurrences', () => {\n const expectedCounts = { one: 1, fish: 4, two: 1, red: 1, blue: 1 };\n expect(count('one fish two fish red fish blue fish')).toEqual(expectedCounts);\n });\n\n it('includes punctuation', () => {\n const expectedCounts = { car: 1, ':': 2, carpet: 1, as: 1, java: 1, 'javascript!!&@$%^&': 1 };\n expect(count('car : carpet as java : javascript!!&@$%^&')).toEqual(expectedCounts);\n });\n\n it('includes numbers', () => {\n const expectedCounts = { testing: 2, 1: 1, 2: 1 };\n expect(count('testing 1 2 testing')).toEqual(expectedCounts);\n });\n\n it('normalizes to lowercase', () => {\n const expectedCounts = { go: 3 };\n expect(count('go Go GO')).toEqual(expectedCounts);\n });\n\n it('counts properly international characters', () => {\n const expectedCounts = { '\u00a1hola!': 1, '\u00bfqu\u00e9': 1, 'tal?': 1, '\u043f\u0440\u0438\u0432\u0435\u0442!': 1 };\n expect(count('\u00a1Hola! \u00bfQu\u00e9 tal? \u041f\u0440\u0438\u0432\u0435\u0442!')).toEqual(expectedCounts);\n });\n\n it('counts multiline', () => {\n const expectedCounts = { hello: 1, world: 1 };\n expect(count('hello\\nworld')).toEqual(expectedCounts);\n });\n\n it('counts tabs', () => {\n const expectedCounts = { hello: 1, world: 1 };\n expect(count('hello\\tworld')).toEqual(expectedCounts);\n });\n\n it('counts multiple spaces as one', () => {\n const expectedCounts = { hello: 1, world: 1 };\n expect(count('hello world')).toEqual(expectedCounts);\n });\n\n it('does not count leading or trailing whitespace', () => {\n const expectedCounts = { introductory: 1, course: 1 };\n expect(count('\\t\\tIntroductory Course ')).toEqual(expectedCounts);\n });\n\n it('handles properties that exist on Object\u2019s prototype', () => {\n const expectedCounts = {\n reserved: 1, words: 1, like: 1, constructor: 1, and: 1, tostring: 1, 'ok?': 1 };\n expect(count('reserved words like constructor and toString ok?')).toEqual(expectedCounts);\n });\n});\n"} {"doc_id": "4e6d7105a9c4b39940371f4764e16b86", "text": "/*\n

      Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

      \n\n

      Example :

      \n\n
      \nInput: root = [4,2,6,1,3,null,null]\nOutput: 1\nExplanation:\nNote that root is a TreeNode object, not an array.\n\nThe given tree [4,2,6,1,3,null,null] is represented by the following diagram:\n\n          4\n        /   \\\n      2      6\n     / \\    \n    1   3  \n\nwhile the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.\n
      \n\n

      Note:

      \n\n
        \n\t
      1. The size of the BST will be between 2 and 100.
      2. \n\t
      3. The BST is always valid, each node's value is an integer, and each node's value is different.
      4. \n

      \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u641c\u7d22\u6811\u7684\u6839\u7ed3\u70b9 root, \u8fd4\u56de\u6811\u4e2d\u4efb\u610f\u4e24\u8282\u70b9\u7684\u5dee\u7684\u6700\u5c0f\u503c\u3002

      \n\n

      \u793a\u4f8b\uff1a

      \n\n
      \n\u8f93\u5165: root = [4,2,6,1,3,null,null]\n\u8f93\u51fa: 1\n\u89e3\u91ca:\n\u6ce8\u610f\uff0croot\u662f\u6811\u7ed3\u70b9\u5bf9\u8c61(TreeNode object)\uff0c\u800c\u4e0d\u662f\u6570\u7ec4\u3002\n\n\u7ed9\u5b9a\u7684\u6811 [4,2,6,1,3,null,null] \u53ef\u8868\u793a\u4e3a\u4e0b\u56fe:\n\n          4\n        /   \\\n      2      6\n     / \\    \n    1   3  \n\n\u6700\u5c0f\u7684\u5dee\u503c\u662f 1, \u5b83\u662f\u8282\u70b91\u548c\u8282\u70b92\u7684\u5dee\u503c, \u4e5f\u662f\u8282\u70b93\u548c\u8282\u70b92\u7684\u5dee\u503c\u3002
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      1. \u4e8c\u53c9\u6811\u7684\u5927\u5c0f\u8303\u56f4\u5728 2 \u5230 100\u3002
      2. \n\t
      3. \u4e8c\u53c9\u6811\u603b\u662f\u6709\u6548\u7684\uff0c\u6bcf\u4e2a\u8282\u70b9\u7684\u503c\u90fd\u662f\u6574\u6570\uff0c\u4e14\u4e0d\u91cd\u590d\u3002
      4. \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u641c\u7d22\u6811\u7684\u6839\u7ed3\u70b9 root, \u8fd4\u56de\u6811\u4e2d\u4efb\u610f\u4e24\u8282\u70b9\u7684\u5dee\u7684\u6700\u5c0f\u503c\u3002

      \n\n

      \u793a\u4f8b\uff1a

      \n\n
      \n\u8f93\u5165: root = [4,2,6,1,3,null,null]\n\u8f93\u51fa: 1\n\u89e3\u91ca:\n\u6ce8\u610f\uff0croot\u662f\u6811\u7ed3\u70b9\u5bf9\u8c61(TreeNode object)\uff0c\u800c\u4e0d\u662f\u6570\u7ec4\u3002\n\n\u7ed9\u5b9a\u7684\u6811 [4,2,6,1,3,null,null] \u53ef\u8868\u793a\u4e3a\u4e0b\u56fe:\n\n          4\n        /   \\\n      2      6\n     / \\    \n    1   3  \n\n\u6700\u5c0f\u7684\u5dee\u503c\u662f 1, \u5b83\u662f\u8282\u70b91\u548c\u8282\u70b92\u7684\u5dee\u503c, \u4e5f\u662f\u8282\u70b93\u548c\u8282\u70b92\u7684\u5dee\u503c\u3002
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      1. \u4e8c\u53c9\u6811\u7684\u5927\u5c0f\u8303\u56f4\u5728 2 \u5230 100\u3002
      2. \n\t
      3. \u4e8c\u53c9\u6811\u603b\u662f\u6709\u6548\u7684\uff0c\u6bcf\u4e2a\u8282\u70b9\u7684\u503c\u90fd\u662f\u6574\u6570\uff0c\u4e14\u4e0d\u91cd\u590d\u3002
      4. \n
      \n*/\n\n\n/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number}\n */\nvar minDiffInBST = function(root) {\n \n};"} {"doc_id": "4f2d05f65e4805491b45a7d36115e248", "text": "/**\n * Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). For each character they type except '#', you need to return the top 3 historical hot sentences that have prefix the same as the part of sentence already typed. Here are the specific rules:\n\nThe hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.\nThe returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same degree of hot, you need to use ASCII-code order (smaller one appears first).\nIf less than 3 hot sentences exist, then just return as many as you can.\nWhen the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.\nYour job is to implement the following functions:\n\nThe constructor function:\n\nAutocompleteSystem(String[] sentences, int[] times): This is the constructor. The input is historical data. Sentences is a string array consists of previously typed sentences. Times is the corresponding times a sentence has been typed. Your system should record these historical data.\n\nNow, the user wants to input a new sentence. The following function will provide the next character the user types:\n\nList input(char c): The input c is the next character typed by the user. The character will only be lower-case letters ('a' to 'z'), blank space (' ') or a special character ('#'). Also, the previously typed sentence should be recorded in your system. The output will be the top 3 historical hot sentences that have prefix the same as the part of sentence already typed.\n\n\nExample:\nOperation: AutocompleteSystem([\"i love you\", \"island\",\"ironman\", \"i love leetcode\"], [5,3,2,2])\nThe system have already tracked down the following sentences and their corresponding times:\n\"i love you\" : 5 times\n\"island\" : 3 times\n\"ironman\" : 2 times\n\"i love leetcode\" : 2 times\nNow, the user begins another search:\n\nOperation: input('i')\nOutput: [\"i love you\", \"island\",\"i love leetcode\"]\nExplanation:\nThere are four sentences that have prefix \"i\". Among them, \"ironman\" and \"i love leetcode\" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, \"i love leetcode\" should be in front of \"ironman\". Also we only need to output top 3 hot sentences, so \"ironman\" will be ignored.\n\nOperation: input(' ')\nOutput: [\"i love you\",\"i love leetcode\"]\nExplanation:\nThere are only two sentences that have prefix \"i \".\n\nOperation: input('a')\nOutput: []\nExplanation:\nThere are no sentences that have prefix \"i a\".\n\nOperation: input('#')\nOutput: []\nExplanation:\nThe user finished the input, the sentence \"i a\" should be saved as a historical sentence in system. And the following input will be counted as a new search.\n\nNote:\nThe input sentence will always start with a letter and end with '#', and only one blank space will exist between two words.\nThe number of complete sentences that to be searched won't exceed 100. The length of each sentence including those in the historical data won't exceed 100.\nPlease use double-quote instead of single-quote when you write test cases even for a character input.\nPlease remember to RESET your class variables declared in class AutocompleteSystem, as static/class variables are persisted across multiple test cases.\n */"} {"doc_id": "50007468fa5de02ba14c4e4581645138", "text": "/**\nYou have an array of negative and positive numbers. Please move all negative numbers to the left and all positive numbers to the right without disrupting the original order.\nexample input: [-6, 2, 1, 2, -10, -4, 8]\nexample output: [-6, -10, -4, 2, 1, 2, 8]\n**/\n\n/*============talk through problem============\n\nDesccribe how you would go about creating a function to select k random items out of an input array of size n. The input array contains only unique items, and the result set should be only unique items.\n k <= n\n\nint[] input = {-6, 2, 1, -10, -4, 8};\nint k = 3;\npossible output: {2, -10, 8} NOT {2, -10, 2}\n\n*/\n"} {"doc_id": "511372dfa01fbe6f73462b876c363768", "text": "/*\n

      Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

      \n\n

      \n\"Range
      \nThe above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.\n

      \n\n

      Example:
      \n

      \nGiven matrix = [\n  [3, 0, 1, 4, 2],\n  [5, 6, 3, 2, 1],\n  [1, 2, 0, 1, 5],\n  [4, 1, 0, 1, 7],\n  [1, 0, 3, 0, 5]\n]\n\nsumRegion(2, 1, 4, 3) -> 8\nsumRegion(1, 1, 2, 2) -> 11\nsumRegion(1, 2, 2, 4) -> 12\n
      \n

      \n\n

      Note:
      \n

        \n
      1. You may assume that the matrix does not change.
      2. \n
      3. There are many calls to sumRegion function.
      4. \n
      5. You may assume that row1 ≤ row2 and col1 ≤ col2.
      6. \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u7ef4\u77e9\u9635\uff0c\u8ba1\u7b97\u5176\u5b50\u77e9\u5f62\u8303\u56f4\u5185\u5143\u7d20\u7684\u603b\u548c\uff0c\u8be5\u5b50\u77e9\u9635\u7684\u5de6\u4e0a\u89d2\u4e3a (row1, col1) \uff0c\u53f3\u4e0b\u89d2\u4e3a (row2, col2)\u3002

      \n\n

      \"Range
      \n\u4e0a\u56fe\u5b50\u77e9\u9635\u5de6\u4e0a\u89d2 (row1, col1) = (2, 1) \uff0c\u53f3\u4e0b\u89d2(row2, col2) = (4, 3)\uff0c\u8be5\u5b50\u77e9\u5f62\u5185\u5143\u7d20\u7684\u603b\u548c\u4e3a 8\u3002

      \n\n

      \u793a\u4f8b:

      \n\n
      \u7ed9\u5b9a matrix = [\n  [3, 0, 1, 4, 2],\n  [5, 6, 3, 2, 1],\n  [1, 2, 0, 1, 5],\n  [4, 1, 0, 1, 7],\n  [1, 0, 3, 0, 5]\n]\n\nsumRegion(2, 1, 4, 3) -> 8\nsumRegion(1, 1, 2, 2) -> 11\nsumRegion(1, 2, 2, 4) -> 12\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      1. \u4f60\u53ef\u4ee5\u5047\u8bbe\u77e9\u9635\u4e0d\u53ef\u53d8\u3002
      2. \n\t
      3. \u4f1a\u591a\u6b21\u8c03\u7528 sumRegion \u65b9\u6cd5\u3002
      4. \n\t
      5. \u4f60\u53ef\u4ee5\u5047\u8bbe row1 ≤ row2 \u4e14 col1 ≤ col2\u3002
      6. \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u7ef4\u77e9\u9635\uff0c\u8ba1\u7b97\u5176\u5b50\u77e9\u5f62\u8303\u56f4\u5185\u5143\u7d20\u7684\u603b\u548c\uff0c\u8be5\u5b50\u77e9\u9635\u7684\u5de6\u4e0a\u89d2\u4e3a (row1, col1) \uff0c\u53f3\u4e0b\u89d2\u4e3a (row2, col2)\u3002

      \n\n

      \"Range
      \n\u4e0a\u56fe\u5b50\u77e9\u9635\u5de6\u4e0a\u89d2 (row1, col1) = (2, 1) \uff0c\u53f3\u4e0b\u89d2(row2, col2) = (4, 3)\uff0c\u8be5\u5b50\u77e9\u5f62\u5185\u5143\u7d20\u7684\u603b\u548c\u4e3a 8\u3002

      \n\n

      \u793a\u4f8b:

      \n\n
      \u7ed9\u5b9a matrix = [\n  [3, 0, 1, 4, 2],\n  [5, 6, 3, 2, 1],\n  [1, 2, 0, 1, 5],\n  [4, 1, 0, 1, 7],\n  [1, 0, 3, 0, 5]\n]\n\nsumRegion(2, 1, 4, 3) -> 8\nsumRegion(1, 1, 2, 2) -> 11\nsumRegion(1, 2, 2, 4) -> 12\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      1. \u4f60\u53ef\u4ee5\u5047\u8bbe\u77e9\u9635\u4e0d\u53ef\u53d8\u3002
      2. \n\t
      3. \u4f1a\u591a\u6b21\u8c03\u7528 sumRegion \u65b9\u6cd5\u3002
      4. \n\t
      5. \u4f60\u53ef\u4ee5\u5047\u8bbe row1 ≤ row2 \u4e14 col1 ≤ col2\u3002
      6. \n
      \n*/\n\n\n/**\n * @param {number[][]} matrix\n */\nvar NumMatrix = function(matrix) {\n \n};\n\n/** \n * @param {number} row1 \n * @param {number} col1 \n * @param {number} row2 \n * @param {number} col2\n * @return {number}\n */\nNumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {\n \n};\n\n/** \n * Your NumMatrix object will be instantiated and called as such:\n * var obj = Object.create(NumMatrix).createNew(matrix)\n * var param_1 = obj.sumRegion(row1,col1,row2,col2)\n */"} {"doc_id": "515fa990ceb1422dcedab7a2a3df021d", "text": "document.getElementById(\"container\").innerHTML = \"JavaScript sandbox Test DIV\";\nconsole.log(\"JavaScript sandbox Test Console\");\n\n/*\n// ***ForEach Loop***\nconst colors = [\"red\", \"green\", \"blue\"];\n\n// Regular old For Loop\nfor (let i = 0; i < colors.length; i++) {\n const colorsElement = colors[i];\n console.log(colorsElement);\n}\n\n// ForEach Loop\ncolors.forEach(function(color) {\n console.log(color);\n});\n// ForEach Loop with a Fat Arrow\ncolors.forEach(color => {\n console.log(color);\n});\n\n// ForEach Loop - adding numbers\nconst numbers = [1, 2, 3, 4, 5];\nlet sum = 0;\n\nnumbers.forEach(function(number) {\n sum += number;\n});\nconsole.log(sum);\n\n// ForEach Loop - adding numbers (Reference to External Function)\nfunction adder(number) {\n sum += number;\n}\nnumbers.forEach(adder);\nconsole.log(sum);\n\n\n// ***Map Loop***\nconst numbers = [1, 2, 3];\nlet doubleNumbers = [];\n//the way it was done in the past\nfor (let i = 0; i < numbers.length; i++) {\n doubleNumbers.push(numbers[i] * 2);\n}\nconsole.log(doubleNumbers);\n//Map Loop\nconst doubled = numbers.map(function(number) {\n return number * 2;\n});\nconsole.log(doubled);\n\nconst cars = [\n { model: \"buick\", price: \"Cheap\" },\n { model: \"Camero\", price: \"Expensive\" }\n];\n\nconst prices = cars.map(function(car) {\n return car.price;\n});\n\nconsole.log(prices);\n\n// ***Filter Loop***\nconst products = [\n { name: \"cucumber\", type: \"vegetable\" },\n { name: \"banana\", type: \"fruite\" },\n { name: \"celery\", type: \"vegetable\" },\n { name: \"orange\", type: \"fruite\" }\n];\n// Regular old For Loop\nconst filterdProducts = [];\nfor (let i = 0; i < products.length; i++) {\n if (products[i].type === \"fruite\") {\n filterdProducts.push(products[i]);\n }\n}\nconsole.log(filterdProducts);\n\nconst newfilterdProducts = products.filter(function(product) {\n return product.type === \"fruite\";\n});\nconsole.log(newfilterdProducts);\n\nconst complexproducts = [\n { name: \"cucumber\", type: \"vegetable\", quantity: 0, price: 1 },\n { name: \"banana\", type: \"fruite\", quantity: 10, price: 15 },\n { name: \"celery\", type: \"vegetable\", quantity: 30, price: 9 },\n { name: \"orange\", type: \"fruite\", quantity: 3, price: 5 }\n];\n//type is 'vegetable', quantity is greater than 0, price is less than 10\nconst complexfilterdProducts = complexproducts.filter(function(product) {\n return (\n product.type === \"vegetable\" && product.quantity > 0 && product.price < 10\n );\n});\nconsole.log(complexfilterdProducts);\n\nconst post = { id: 4, title: \"New Post\" };\nconst comments = [\n { postId: 4, content: \"awesome post\" },\n { postId: 3, content: \"it was OK\" },\n { postId: 4, content: \"neat\" }\n];\n\nfunction commentsForPost(post, comments) {\n return comments.filter(function(comment) {\n return comment.postId === post.id;\n });\n}\n\nconsole.log(commentsForPost(post, comments));\n\n\n// ***Find Loop***\nconst users = [{ name: \"Jill\" }, { name: \"Alex\" }, { name: \"Bill\" }];\n\n// Regular old For Loop\nlet user;\nconst filterdProducts = [];\nfor (let i = 0; i < users.length; i++) {\n if (users[i].name === \"Alex\") {\n user = users[i];\n break;\n }\n}\nconsole.log(user);\n\nconst findUser = users.find(function(user) {\n return user.name === \"Alex\";\n});\nconsole.log(findUser);\n\n// ***Complex Find Loop***\nfunction Car(model) {\n this.model = model;\n}\n\nconst cars = [new Car(\"Buick\"), new Car(\"Camaro\"), new Car(\"Focus\")];\n\nconst findCar = cars.find(function(car) {\n return car.model === \"Focus\";\n});\nconsole.log(findCar);\n\nconst posts = [{ id: 1, title: \"New Post\" }, { id: 2, title: \"Old Post\" }];\nconst comment = { postId: 1, content: \"awesome post\" };\n\nfunction postForComment(posts, comment) {\n return posts.find(function(post) {\n return post.id === comment.postId;\n });\n}\n\nconsole.log(postForComment(posts, comment));\n\n\n// ***Every and Some Helpers***\nconst computers = [\n { name: \"Apple\", ram: 24 },\n { name: \"Compaq\", ram: 4 },\n { name: \"Acer\", ram: 32 }\n];\n\nlet allComputersCanRunProgram = true;\nlet onlySomeComputersCanRunProgram = false;\n\n// Regular old For Loop\nfor (let i = 0; i < computers.length; i++) {\n let computer = computers[i];\n if (computer.ram < 16) {\n allComputersCanRunProgram = false;\n } else {\n onlySomeComputersCanRunProgram = true;\n }\n}\nconsole.log(allComputersCanRunProgram);\nconsole.log(onlySomeComputersCanRunProgram);\n\nconst everyComputer = computers.every(function(computer) {\n return computer.ram > 16;\n});\nconsole.log(`Every Helper: ${everyComputer}`);\n\nconst someComputer = computers.some(function(computer) {\n return computer.ram > 16;\n});\nconsole.log(`Some Helper: ${someComputer}`);\n\nconst names = [\"Alexandria\", \"Matthew\", \"Joe\"];\n\nconst everyName = names.every(function(name) {\n return name.length > 4;\n});\nconsole.log(`EVERY name has more than 4 characters: ${everyName}`);\n\nconst someName = names.some(function(name) {\n return name.length > 4;\n});\nconsole.log(`SOME name has more than 4 characters: ${someName}`);\n\n// ***Every Helper - Practical Example***\n\nfunction Field(value) {\n this.value = value;\n}\n\nField.prototype.validate = function() {\n return this.value.length > 0;\n};\n\nconst username = new Field(\"username\");\nconst password = new Field(\"password\");\nconst birthDate = new Field(\"01/03/1984\");\n\nconst fields = [username, password, birthDate];\n\nconst formIsValid = fields.every(function(field) {\n return field.validate();\n});\nconsole.log(`EVERY field is Validated: ${formIsValid}`);\n\nif (formIsValid) {\n console.log(`Form Is Valid: ${formIsValid} - you can go in`);\n} else {\n console.log(`Form Is Valid: ${formIsValid} - you can't go in`);\n}\n\n// ***Reduce Helper***\n// Regular old For Loop\nconst numbers = [10, 20, 30];\nlet sum = 0;\nfor (let i = 0; i < numbers.length; i++) {\n sum += numbers[i];\n}\nconsole.log(`the Sum is: ${sum} - Regular old For Loop`);\n\n//Simple Reduce Helper\nconst numbersReduce = numbers.reduce(function(sum, number) {\n return sum + number;\n}, 0);\nconsole.log(`the Sum is: ${numbersReduce} - Using the Reduce Helper`);\n\n//Reduce Helper - List of Strings\nconst primaryColors = [{ color: \"red\" }, { color: \"green\" }, { color: \"blue\" }];\nconst primaryColorsReduce = primaryColors.reduce(function(\n previous,\n primaryColor\n) {\n previous.push(primaryColor.color);\n return previous;\n},\n[]);\nconsole.log(\n `list of Strings: ${primaryColorsReduce} - Using the Reduce Helper`\n);\n\n//Reduce Helper - Check For Balanced Parenthesis\nfunction balancedParens(string) {\n return !string.split(\"\").reduce(function(previous, char) {\n if (previous < 0) {\n return previous;\n }\n if (char === \"(\") {\n return ++previous;\n }\n if (char === \")\") {\n return --previous;\n }\n return previous;\n }, 0);\n}\nconsole.log(\n `Balanced Parenthesis Check: ${balancedParens(\n \"()\"\n )} - Using the Reduce Helper`\n);\n\n// ***Arrow functions***\n//regular old function\nconst regularAdd = function(a, b) {\n return a + b;\n};\nconsole.log(`Adding ${regularAdd(1, 3)} - regular old function`);\n\n//arrow function\nconst arrowAdd = (a, b) => {\n return a + b;\n};\nconsole.log(`Adding ${arrowAdd(2, 3)} - arrow function`);\n\n//arrow function - single expression (implicit return)\nconst arrowAddImp = (a, b) => a + b;\nconsole.log(`Adding ${arrowAddImp(6, 6)} - arrow function Single line`);\n\n//arrow function - single argument\nconst double = number => number * 2;\nconsole.log(`double ${double(15)} - arrow function Single argument`);\n\n//arrow function doubling array - BEFORE\nnumbers = [1, 2, 3];\nconst numbersMapBefore = numbers.map(function(number) {\n return 2 * number;\n});\nconsole.log(`double array ${numbersMapBefore} - arrow function BEFORE`);\n\n//arrow function doubling array - AFTER\nconst numbersMapAfter = numbers.map(number => 2 * number);\nconsole.log(`double array ${numbersMapAfter} - arrow function AFTER`);\n\n//arrow function with NO lexical this\nconst noTeamArrow = {\n members: [\"jane\", \"Bill\"],\n teamName: \"Super Squad\",\n teamSummary: function() {\n return this.members.map(\n function(member) {\n return `${member} is on team ${this.teamName}`;\n }.bind(this) //bind(this) used to bind the function to the parent(noTeamArrow)\n );\n }\n};\nconst noTeamLog = noTeamArrow.teamSummary();\nconsole.log(noTeamLog);\n\n//arrow function lexical this\nconst teamArrow = {\n members: [\"jane\", \"Bill\"],\n teamName: \"Super Squad\",\n teamSummary: function() {\n return this.members.map(member => {\n return `${member} is on team ${this.teamName}`;\n });\n }\n};\nconst teamLog = teamArrow.teamSummary();\nconsole.log(teamLog);\n\n// ***JavaScript object literals***\n// the old way\n// function createBookShop(inventory) {\n// return {\n// inventory: inventory,\n// inventoryValue: function() {\n// return this.inventory.reduce((total, book) => total + book.price, 0);\n// },\n// priceForTitle: function(title) {\n// return this.inventory.find(book => book.title === title).price;\n// }\n// };\n// }\n\n// const inventory = [\n// { title: \"Harry Potter\", price: 10 },\n// { title: \"Eloquent Javascript\", price: 15 }\n// ];\n\n// const bookShop = createBookShop(inventory);\n// console.log(bookShop.inventoryValue());\n// console.log(bookShop.priceForTitle(\"Harry Potter\"));\n\n// enhanced object literals\nfunction createBookShop(inventory) {\n return {\n inventory,\n inventoryValue() {\n return this.inventory.reduce((total, book) => total + book.price, 0);\n },\n priceForTitle(title) {\n return this.inventory.find(book => book.title === title).price;\n }\n };\n}\n\nconst inventory = [\n { title: \"Harry Potter\", price: 10 },\n { title: \"Eloquent Javascript\", price: 15 }\n];\n\nconst bookShop = createBookShop(inventory);\nconsole.log(bookShop.inventoryValue());\nconsole.log(bookShop.priceForTitle(\"Harry Potter\"));\n\n// L33\n\n\n// ***Default function arguments***\n\n// the old way\nfunction makeAjaxRequest(url, method) {\n if (!method) {\n method = \"GET\";\n }\n return `http://${url}/${method}/`;\n //some logic\n}\nconsole.log(makeAjaxRequest(\"google.co.il\"));\nconsole.log(makeAjaxRequest(\"google.co.il\", \"GET\"));\n\n// the New way\nfunction NewMakeAjaxRequest(url, method = \"GET\") {\n return `http://${url}/${method}/`;\n //some logic\n}\nconsole.log(NewMakeAjaxRequest(\"google.co.il\"));\nconsole.log(NewMakeAjaxRequest(\"google.co.il\", \"POST\"));\n\n// L35 ***Rest and Spread operators***\n//without Rest operator - you need an array\nfunction addNumbers(numbers) {\n return numbers.reduce((sum, number) => {\n return sum + number;\n }, 0);\n}\nconsole.log(addNumbers([1, 2, 3, 4, 5]));\n\n//with Rest operator - you don't need an array\nfunction restAddNumbers(...numbers) {\n return numbers.reduce((sum, number) => {\n return sum + number;\n }, 0);\n}\nconsole.log(restAddNumbers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));\n\nconst defaultColors = [\"red\", \"green\"];\nconst userFavoriteColors = [\"orange\", \"yellow\"];\n\n//without Spread operators - you use concat\nconst combinedColors = defaultColors.concat(userFavoriteColors);\nconsole.log(combinedColors);\n\n//with Spread operators - you dump all the values to a new array\nconst spreadCombinedColors = [...defaultColors, ...userFavoriteColors];\nconsole.log(spreadCombinedColors);\n//with Spread operators - another example\nconst blueSpreadCombinedColors = [\n \"blue\",\n ...defaultColors,\n ...userFavoriteColors\n];\nconsole.log(blueSpreadCombinedColors);\n\n//complex example - if milk not in list add it\nfunction validateShoppingList(...items) {\n if (items.indexOf(\"milk\") < 0) {\n return [\"milk\", ...items];\n }\n return items;\n}\nconst shoppingList = validateShoppingList(\"Oranges\", \"Eggs\", \"milk\");\nconsole.log(shoppingList);\n\n// L38 ***Destructuring***\n//without Destructuring\nvar expense = {\n type: \"Business\",\n amount: \"$45 USD\"\n};\nvar noDestructuringType = expense.type;\nvar noDestructuringAmount = expense.amount;\nconsole.log(\n `some ${noDestructuringType} item - cost: ${noDestructuringAmount} without Destructuring`\n);\n\n//with Destructuring\nconst { type, amount } = expense;\nconsole.log(`some ${type} item - cost: ${amount} without Destructuring`);\n\nvar savedFiled = {\n extension: \"jpeg\",\n name: \"picture\",\n size: \"14040\"\n};\n//without Destructuring\nfunction fileSummary(file) {\n return `the file ${file.name}.${file.extension} is of size ${file.size}`;\n}\nconsole.log(fileSummary(savedFiled));\n\n//with Destructuring\nfunction fileSummary({ name, extension, size }) {\n return `the file ${name}.${extension} is of size ${size}`;\n}\nconsole.log(fileSummary(savedFiled));\n\n//with Destructuring with color red\n// function fileSummary({ name, extension, size }, { color }) {\n// return `${color} - the file ${name}.${extension} is of size ${size}`;\n// }\n// console.log(fileSummary(savedFiled, { color: \"red\" }));\n\n//** Destructuring from array**\nconst companies = [\"Google\", \"Facebook\", \"Uber\", \"Tweeter\"];\n\n//without Destructuring\nconst firstCompany = companies[0];\nconsole.log(firstCompany);\n\n//with Destructuring - square brackets to pull items\nconst [name, name2, ...rest] = companies;\nconsole.log(name, name2); //first two names\nconsole.log(...rest); //rest of the names\n\n//with Destructuring - curly brackets to pull properties\nconst { length } = companies;\nconsole.log(length);\n\n// L41 ***Destructuring Objects and Arrays***\nconst ArrayObjectCompanies = [\n { name: \"Google\", Location: \"Mountain View\" },\n { name: \"Facebook\", Location: \"Menlo Park\" },\n { name: \"Uber\", Location: \"San Francisco\" }\n];\n//without Destructuring\nconst ES5Location = ArrayObjectCompanies[0].Location;\nconsole.log(`${ES5Location} - ES5 Style`);\n\n//with Destructuring - square brackets to pull item(s) and curly brackets to pull Location properties\nconst [{ Location: Location }] = ArrayObjectCompanies;\nconsole.log(`${Location} - with Destructuring`);\n\nconst Google = {\n locations: [\"Mountain View\", \"New York\", \"London\"]\n};\n\nconst { locations } = Google;\nconsole.log(`${locations} - Extracting locations Array from an Object`);\nconsole.log(\n `${locations[2]} - Extracting individual locations from an Object`\n);\n\n// L42 ***Destructuring Practical Example***\n//without Destructuring\n// function SignUp(username, password, email, dateOfBirth, city) {\n// //code\n// }\n\n// SignUp(\n// \"myusername\",\n// \"mypassword\",\n// \"myemail@gmail.com\",\n// \"01.03.1984\",\n// \"Tel-Aviv\"\n// );\n\n//with Destructuring - extract individual object elements (the order doesn't matter)\nfunction SignUp({ username, password, email, dateOfBirth, city }) {\n console.log(`\nUsername: ${username}\nPassword: ${password}\nEmail: ${email}\nDate Of Birth: ${dateOfBirth}\nCity: ${city}`);\n}\nconst user = {\n username: \"myusername\",\n password: \"mypassword\",\n email: \"myemail@gmail.com\",\n dateOfBirth: \"01.03.1984\",\n city: \"Tel-Aviv\"\n};\n//provide a single object\nSignUp(user);\n\n// L43 ***Destructuring Practical Example - Arrays***\n// change the structure of 'array of arrays' to 'array of objects'\nconst points = [[4, 5], [10, 1], [0, 40]];\n\nconst convertedPoints = points.map(([x, y]) => {\n return { x, y };\n});\nconsole.log(convertedPoints);\n\n// L44 ***inheritance and ES6 Classes***\n// basic object creation in javascript\n// function Car(options) {\n// this.title = options.title;\n// }\n// //adding new properties via the prototype constructor\n// Car.prototype.drive = function() {\n// return \"vroom\";\n// };\n// const car = new Car({ title: \"Focus\" });\n// console.log(car.title);\n// console.log(car.drive());\n\n// //Toyota inheriting Car Properties\n// function Toyota(options) {\n// Car.call(this, options);\n// this.color = options.color;\n// }\n// //Toyota inheriting Car prototype\n// Toyota.prototype = Object.create(Car.prototype);\n// Toyota.prototype.constructor = Toyota;\n// //Toyota add new prototype\n// Toyota.prototype.honk = function() {\n// return \"Beep\";\n// };\n\n// const toyota = new Toyota({ color: \"Red\", title: \"Daily Driver\" });\n// console.log(`My ${toyota.color} Toyota is my ${toyota.title}`);\n// console.log(\n// `${toyota.drive()} ${toyota.drive()} ${toyota.honk()} ${toyota.honk()}`\n// );\n\n//L46 ES6 Classes\nclass Car {\n constructor({ title }) {\n this.title = title;\n }\n drive() {\n return \"vroom\";\n }\n}\n\nconst car = new Car({ title: \"Ford\" });\nconsole.log(`${car.title} goes ${car.drive()}`);\n\nclass Toyota extends Car {\n constructor(options) {\n super(options);\n this.color = options.color;\n }\n honk() {\n return \"beep\";\n }\n}\n\nconst toyota = new Toyota({ color: \"Red\", title: \"Corolla\" });\n\nconsole.log(\n `My ${toyota.color} ${\n toyota.title\n } goes ${toyota.drive()} and ${toyota.honk()}`\n);\n\n// ***Generators***\n//L49 - for of loop\nconst colors = [\"red\", \"green\", \"blue\"];\nfor (const color of colors) {\n console.log(color);\n}\n\nconst numbers = [1, 2, 3, 4];\nlet total = 0;\nfor (const number of numbers) {\n total += number;\n}\nconsole.log(total);\n\n//L50/51/52 Generators - a function that can be entered and exited multiple times\nfunction* shopping() {\n //yield - stop at this point and come back to this exact point on the second gen.next(\"with the value provided\")\n const stuffFromStore = yield \"cash\";\n //yield - stop at this point and come back to this exact point on the third gen.next(\"with the value provided\")\n const stuffFromLaundry = yield \"Laundry\";\n return [stuffFromStore, stuffFromLaundry];\n}\nconst gen = shopping();\nconsole.log(gen.next()); // leaving our house\nconsole.log(gen.next(\"groceries\")); // leaving the sore with groceries\nconsole.log(gen.next(\"Laundry\")); // leaving the Laundry with clean clothes\n\nconsole.log(\"************************************\");\n//L53 Generators with for of loops - can loop trough any type on data structure\nfunction* GeneratorColors() {\n yield \"Red\";\n yield \"Green\";\n yield \"Blue\";\n}\n\nconst myColors = [];\nfor (const color of GeneratorColors()) {\n myColors.push(color);\n}\nconsole.log(myColors);\n\n//L57/58 Generators with for of loops - practical example 2 - Generator Delegator (Refactored with Symbol.iterator)\nconst testingTeam = {\n lead: \"Amanda\",\n tester: \"Bill\",\n [Symbol.iterator]: function*() {\n yield this.lead;\n yield this.tester;\n }\n};\n\nconst engineeringTeam = {\n testingTeam,\n size: 3,\n department: \"Engineering\",\n lead: \"Jill\",\n manager: \"Alex\",\n engineer: \"Dave\",\n [Symbol.iterator]: function*() {\n yield this.lead;\n yield this.manager;\n yield this.engineer;\n yield* this.testingTeam;\n }\n};\n\nconst names = [];\n//push those values into the names array\nfor (const name of engineeringTeam) {\n names.push(name);\n}\nconsole.log(names);\n\n//L59/60 Iterating a tree with for of loop\nclass Comment {\n constructor(content, children) {\n this.content = content;\n this.children = children;\n }\n *[Symbol.iterator]() {\n yield this.content;\n for (const child of this.children) {\n yield* child;\n }\n }\n}\n\nconst children = [\n new Comment(\"Good Comment\", []),\n new Comment(\"Bad Comment\", []),\n new Comment(\"meh\", [])\n];\n\nconst tree = new Comment(\"Great post!\", children);\n\nconst values = [];\nfor (const value of tree) {\n values.push(value);\n}\n\nconsole.log(tree);\nconsole.log(values);\n*/\n\n//L61-67 promises and fetch - better to use axios\nconst url = \"https://jsonplaceholder.typicode.com/posts/\";\n// fetch(url).then(data => console.log(data)); //not getting the data right away\nfetch(url)\n .then(response => response.json())\n .then(data => console.log(data))\n .catch(error => console.log(\"BAD\", error));\n"} {"doc_id": "51759ec04300e029213e9da006250d19", "text": "let firstValue = parseInt(prompt(\"Digite o primeiro valor:\"));\nlet operation = prompt(\"Qual a opera\u00e7\u00e3o voce deseja fazer?\");\nlet secondValue = parseInt(prompt(\"Digite o segundo valor:\"));\nlet result = '';\n\nif (operation == \"+\"){\n result = firstValue + secondValue;\n document.write(\"

      \" + firstValue + \"+\" + secondValue + \" = \" + result + \"

      \");\n}else if(operation == \"-\"){\n result = firstValue - secondValue;\n document.write(\"

      \" + firstValue + \"-\" + secondValue + \" = \" + result + \"

      \");\n}else if(operation == \"x\"){\n result = firstValue * secondValue;\n document.write(\"

      \" + firstValue + \"*\" + secondValue + \" = \" + result + \"

      \");\n}else if(operation == \"/\"){\n result = firstValue / secondValue;\n document.write(\"

      \" + firstValue + \"/\" + secondValue + \" = \" + result + \"

      \");\n}else {\n document.write(\"

      Op\u00e7\u00e3o inv\u00e1lida

      \");\n}"} {"doc_id": "5352a36b72340a649eb38ef83040eb81", "text": "var add = function(number1, number2) {\n return number1 + number2;\n};\n\nvar multiply = function(number1, number2) {\n return number1 * number2;\n};\n\nvar sub = function(number1, number2) {\n return number1 - number2;\n};\n\nvar divide = function(number1, number2) {\n return number1 / number2;\n};\n\n// var height = parseInt(prompt(\"Enter your height in inches\"));\n// var weight = parseInt(prompt(\"Enter your weight in pounds\"));\n// weight=weight*.45;\n// height = Math.pow((height*.025), 2);\n// var bmi = weight/height;\n// alert(bmi);\n//\n// var Celcius= parseInt(prompt(\"Enter a temperature in Celcius\"));\n// Farenheit= Celcius*9/5 + 32;\n// alert(Farenheit)\n//\n// var Farenheit= parseInt(prompt(\"Enter a temperature in Farenheit\"));\n// Celcius= (Farenheit - 32) * 5/9\n// alert(Celcius)\n\n$(function(){\n $(\"form#add\").submit(function(event){\n event.preventDefault();\n var number1 = parseInt($(\"#add1\").val());\n var number2 = parseInt($(\"#add2\").val());\n var result = add(number1, number2);\n $(\"#output\").text(result);\n });\n\n $(\"form#subtract\").submit(function(event){\n event.preventDefault();\n var number1 = parseInt($(\"#sub1\").val());\n var number2 = parseInt($(\"#sub2\").val());\n var result = sub(number1, number2);\n $(\"#output\").text(result);\n });\n\n $(\"form#multiply\").submit(function(event){\n event.preventDefault();\n var number1 = parseInt($(\"#multiply1\").val());\n var number2 = parseInt($(\"#multiply2\").val());\n var result = multiply(number1, number2);\n $(\"#output\").text(result);\n });\n\n $(\"form#divide\").submit(function(event){\n event.preventDefault();\n var number1 = parseInt($(\"#divide1\").val());\n var number2 = parseInt($(\"#divide2\").val());\n var result = divide(number1, number2);\n $(\"#output\").text(result);\n });\n});\n"} {"doc_id": "536ffe3f63740b77d01b8ef6425773c7", "text": "/*\nIt's Christmas time! To share his Christmas spirit with all his friends, the young Christmas Elf decided to send each of them a Christmas e-mail with a nice Christmas tree. Unfortunately, Internet traffic is very expensive in the North Pole, so instead of sending an actual image he got creative and drew the tree using nothing but asterisks ('*' symbols). He has given you the specs (see below) and your task is to write a program that will generate trees following the spec and some initial parameters.\n\nHere is a formal definition of how the tree should be built, but before you read it the Elf HIGHLY recommends first looking at the examples that follow:\n\nEach tree has a crown as follows:\n\n *\n *\n***\nDefine a line as a horizontal group of asterisks and a level as a collection of levelHeight lines stacked one on top of the other.\n\nBelow the crown there are levelNum levels.\n\nThe tree is perfectly symmetrical so all the middle asterisks of the lines lie on the center of the tree.\n\nEach line of the same level (excluding the first one) has two more asterisks than the previous one (one added to each end);\n\nThe number of asterisks in the first line of each level is chosen as follows:\n\nthe first line of the first level has 5 asterisks;\nthe first line of each consecutive level contains two more asterisks than the first line of the previous level.\nAnd finally there is the tree foot which has a height of levelNum and a width of:\n\nlevelHeight asterisks if levelHeight is odd;\nlevelHeight + 1 asterisks if levelHeight is even.\nGiven levelNum and levelHeight, return the Christmas tree of the young elf.\n\nExample\n\nFor levelNum = 1 and levelHeight = 3, the output should be\n\nchristmasTree(levelNum, levelHeight) =\n [\" *\",\n \" *\",\n \" ***\",\n \" *****\",\n \" *******\",\n \"*********\",\n \" ***\"]\n, which represents the following tree:\n\n ___\n * |\n * |-- the crown \n *** ___| \n ***** |\n ******* |-- level 1\n ********* ___|\n *** ___|-- the foot\nFor levelNum = 2 and levelHeight = 4, the output should be\n\nchristmasTree(levelNum, levelHeight) = \n [\" *\", \n \" *\", \n \" ***\", \n \" *****\", \n \" *******\", \n \" *********\", \n \" ***********\", \n \" *******\", \n \" *********\", \n \" ***********\", \n \"*************\", \n \" *****\", \n \" *****\"]\n */\n\nfunction plot(line) {\n const width = line.reduce((a, v) => Math.max(v, a), 0); \n\n return line.map((v) => ' '.repeat((width - v) >> 1) + '*'.repeat(v));\n}\n\nfunction christmasTree(levelNum, levelHeight) {\n var line = [];\n var firstLevel;\n var width;\n \n line.push(1, 1, 3);\n \n firstLevel = 5;\n for (var i = 0; i < levelNum; i++) {\n var thisLevel = firstLevel;\n for (var j = 0; j < levelHeight; j++) {\n line.push(thisLevel);\n thisLevel += 2;\n }\n firstLevel += 2;\n }\n \n width = levelHeight + ((levelHeight + 1) & 1);\n for (var i = 0; i < levelNum; i++) {\n line.push(width);\n }\n \n return plot(line);\n}\n\n\n\n\nlet levelNum = 2\nlet levelHeight = 10\nchristmasTree(levelNum, levelHeight)\n"} {"doc_id": "538a07e882e8fa8054a72f3ca009c429", "text": "// \u7edf\u8ba1\u6240\u6709\u5c0f\u4e8e\u975e\u8d1f\u6574\u6570 n \u7684\u8d28\u6570\u7684\u6570\u91cf\u3002\r\n\r\n// \u793a\u4f8b:\r\n// \u8f93\u5165: 10\r\n// \u8f93\u51fa: 4\r\n// \u89e3\u91ca: \u5c0f\u4e8e 10 \u7684\u8d28\u6570\u4e00\u5171\u6709 4 \u4e2a, \u5b83\u4eec\u662f 2, 3, 5, 7 \u3002\r\n\r\n//\u57c3\u62c9\u6258\u8272\u5c3c\u7b5b\u9009\u6cd5!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n// var countPrimes = function(n) {\r\n// let arr = [], count = 0\r\n// for (let i = 0; i < n + 1; i++) {\r\n// arr[i] = true;\r\n// }\r\n// for (let i = 2;i < n; i++) {\r\n// if (arr[i]) { // \u5982\u679ci\u662f\u8d28\u6570\r\n// for (let j = i + i; j < n; j = j + i) {\r\n// arr[j] = false // i\u7684n\u500d\u6570\u80af\u5b9a\u4e0d\u662f\u8d28\u6570\r\n// }\r\n// count++;\r\n// }\r\n// }\r\n// return count;\r\n// };\r\nvar countPrimes = function(n) { \r\n\tconst primes = Array(n).fill(true) \r\n\tlet count = 0 \r\n\tfor (let i = 2; i < n; i++) { \r\n\t\tif (primes[i]) { \r\n\t\t\tcount++ \r\n\t\t\tfor (let j = 2; i * j < n; j++) { \r\n\t\t\t\tprimes[i * j] = false \r\n\t\t\t} \r\n\t\t} \r\n\t} \r\n\treturn count \r\n};\r\n\r\nconsole.log(countPrimes(10));\r\n"} {"doc_id": "53e24ed3f27464fb2a18a86d73ad43ef", "text": "/*----------UNDERSTANDING THE PROBLEM----------\n- Objective \n - Find the 'product sum' of the given \"special\" array.\n\n- Definitions\n - Characteristics of a \"special array\":\n - The array will always be non-empty.\n - It can only contain either integers or OTHER special arrays.\n\n - \"Product Sum\": the value that results when all the items in the array are\n added together and then multiplied by the levels of their respective depths. \n - For example, an outer array containing only integers will have its sum\n multiplied by 1 because it doesn't contain any nested OTHER special arrays\n within it.\n - However, if an array contains integers AND other nested special arrays,\n the 'multiplier' for those nested special arrays will differ from the\n multiplier used with the integers of the outermost special array.\n\n- Expected Input(s)\n - Number of Expected Parameters: 2\n - Names/Data Types of Expected Parameters\n - \"specialAray\" (an array; must only contain Number or Array data types)\n - \"multiplier\" (an integer with a default value of 1)\n\n- Expected Output(s)\n - Number of Expected Outputs: 1\n - Names/Data Types of Expected Output\n - \"productSum\" (a number)\n\n- Constraints\n - Will the following make the algorithm fail?\n - Negative numbers?\n - No.\n - Number data types?\n - No.\n - Floating point numbers?\n - Yes.\n - Must be integers only.\n - Non-alphanumeric characters in the inputs?\n - Yes.\n - Must be integers (negative or positive) only.\n\n- Example #1\n - Example #1 Input(s): [1, 2, 3, 4, 5]\n - Example #1 Output(s): 15 (=> 1 * (1 + 2 + 3 + 4 + 5))\n\n- Example #2\n - Example #2 Input(s): [1, [2, 3], 4, 5]\n - Example #2 Output(s): 20 (=> 1 * (1 + (2 * (2 + 3)) + 4 + 5))\n\n- Example #3\n - Example #3 Input(s): [1, [2, [3, 4], 5]]\n - Example #3 Output(s): 57 (=> 1 * (1 + (2 * (2 + (3 * (3 + 4)) + 5)))\n*/\n\n/*---------------DEVISING A PLAN---------------\n- BRUTE FORCE SOLUTION (Pseudocoded Steps) \n (1) Create a recursive function (\"findProductSum()\") that will take in a\n special array (that may or may not contain others special arrays and/or\n integers) and return its product sum.\n (2) Create a variable (\"multiplier\") that will hold the value of the number\n to be multiplied to the sum at each depth.\n (3) Create another variable (\"sum\") that will hold the running \n total of all the product sums (at a given level) added together.\n (4) Iterate through the given special array and any special arrays that are\n nested inside of it.\n (5) If the element is an integer, add it to the \"sum\" variable.\n (6) If the element is a nested special array, recursively call the\n 'findProductSum()' function for that element by passing in the nested\n special array, as well as the 'multiplier' that will be increased by 1\n from the previous depth.\n (7) Return the \"totalSum\" variable.\n*/\n\n/*------------IMPLEMENTING THE PLAN------------*/\n\nconst assert = require('assert');\n\n('use strict');\n\n// helper function - produces product sum of each individual item in the given\n// special array\n// function findItemProductSum(item) {\n// \t// console.log(`item = ${item}`);\n// \tlet itemProductSum = 0;\n// \tlet itemLen = item.length;\n// \tlet levelsOfDepth = 1;\n\n// \t// checks for proper input (number, integer)\n// \tif (typeof item === 'number' && Number.isInteger(item)) {\n// \t\titemProductSum += item;\n// \t\t// console.log(`itemProductSum (mutated) = ${itemProductSum}\\n`);\n// \t} else if (typeof item === 'object' && itemLen !== 0) {\n// \t\t// console.log(\"Input is an 'object' data type (array)\");\n// \t\tconsole.log(`levelsOfDepth = ${levelsOfDepth}`);\n// \t\tlevelsOfDepth += 1;\n// \t\tconsole.log(`levelsOfDepth (mutated) = ${levelsOfDepth}`);\n\n// \t\tfor (let i = 0; i < itemLen; i++) {\n// \t\t\tconsole.log(`---i[${i}] = ${item[i]}`);\n\n// \t\t\tlet itemProductSum = findItemProductSum(item[i]);\n// \t\t\tconsole.log(`itemProductSum = ${itemProductSum}`);\n\n// \t\t\titemProductSum += itemProductSum;\n// \t\t\tconsole.log(`itemProductSum (mutated) = ${itemProductSum}\\n`);\n// \t\t}\n\n// \t\tconsole.log(\n// \t\t\t`itemProductSum * levelsOfDepth = ${itemProductSum * levelsOfDepth}`\n// \t\t);\n// \t\titemProductSum *= levelsOfDepth;\n// \t} else {\n// \t\tconsole.log(`\\nInput, \"${item}\", is NOT an 'object' or 'number' data type`);\n// \t\treturn `Input is NOT a 'number' or 'object' data type; please try different data type`;\n// \t}\n\n// \treturn itemProductSum;\n// }\n\n// console.log(findItemProductSum(1)); // 1\n// console.log(findItemProductSum([1, -1])); // 0\n// console.log(findItemProductSum([1, 9, 4, 2])); // 16\n\nfunction productSum(array) {\n\tlet productSumValue;\n\tlet lenOfArray = array.length;\n\tlet levelsOfDepth = 1;\n\tconst arrayToReduce = [];\n\tconsole.log('arrayToReduce = ', arrayToReduce, '\\n');\n\n\tlet i = 0;\n\twhile (lenOfArray > 0) {\n\t\tconsole.log(`array[${i}] = `, array[i]);\n\n\t\tif (typeof array[i] === 'number' && Number.isInteger(array[i])) {\n\t\t\tconsole.log('levelsOfDepth = ', levelsOfDepth);\n\t\t\tarrayToReduce.push(array[i]);\n\t\t\tconsole.log('arrayToReduce = ', arrayToReduce, '\\n');\n\t\t\tlenOfArray -= 1;\n\t\t\ti++;\n\t\t} else if (typeof array[i] === 'object' && lenOfArray !== 0) {\n\t\t\tlevelsOfDepth += 1;\n\t\t\tconsole.log('DEPTH INCREASED => levelsOfDepth = ', levelsOfDepth);\n\t\t\tlet innerarray = productSum(array[i]) * levelsOfDepth;\n\t\t\tconsole.log('innerarray = ', innerarray);\n\t\t\tarrayToReduce.push(innerarray);\n\t\t\tconsole.log('arrayToReduce = ', arrayToReduce, '\\n');\n\t\t\tlenOfArray -= 1;\n\t\t\ti++;\n\t\t} else {\n\t\t\tconsole.log(`\\nInput is NOT an 'object' or 'number' data type`);\n\t\t\treturn `Input is NOT a 'number' or 'object' data type; please try different data type`;\n\t\t}\n\t}\n\n\tproductSumValue = arrayToReduce.reduce(function(acc, item) {\n\t\treturn (acc += item);\n\t}, 0);\n\treturn productSumValue;\n}\n\nconsole.log(productSum([1, 9, 4, 2])); // 16\n// console.log(productSum([-1, 9, 4, 2])); // 14\n// console.log(productSum([-1, [2, 4], 4, 2])); // 17\nconsole.log(productSum([1, [9, 2], 4, [2, 3]])); // 42\nconsole.log(productSum([[1, 2], 3, [4, 5]]));\n\n// assert.deepStrictEqual(\n// \tfindItemProductSum(1),\n// \t1,\n// \t\"When 'item' is passed to this function, 'item' is also returned\"\n// );\n// assert.deepStrictEqual(\n// \tfindItemProductSum(-1),\n// \t-1,\n// \t\"When 'item' is passed to this function, 'item' is also returned\"\n// );\n// assert.deepStrictEqual(\n// \tfindItemProductSum([4, 3, 2, 1]),\n// \t0,\n// \t\"When 'item' is passed to this function, 'item' is also returned\"\n// );\n// assert.deepStrictEqual(\n// \tfindItemProductSum(true),\n// \t\"Input is NOT a 'number' or 'object' data type; please try different data type\",\n// \t\"True is NOT a 'number' or 'object' data type; it is a Boolean value\"\n// );\n\n// console.log(\"***---ALL TESTS FOR 'findItemProductSum' PASSED---***\");\n\n/*--------REFLECTING/ITERATING THE PLAN--------\n- BRUTE FORCE SOLUTION ANALYSIS\n - Were you able to arrive at the correct answer with your solution?\n - Yes/No\n - Analyze the Time & Space Complexity of your solution.\n - Time Complexity: \n - Space Complexity: \n - Could either, Time or Space Complexity, be improved in your solution?\n - Yes/No\n - If so, how would you go about improving it?\n - What is the new Time & Space Complexity of your improved solution?\n*/\n"} {"doc_id": "54986e3cdcb35ddbdc27ba284c328735", "text": "/**\n * Simple queue with max size.\n */\nclass BoundedQueue {\n // Creates the queue\n constructor(maxSize = 1000) {\n this.maxSize = maxSize;\n this.backingArray = [];\n }\n\n // Adds element to back of queue, removing front element if at max size.\n push(element) {\n if (this.backingArray.length >= this.maxSize) {\n this.backingArray.shift();\n }\n this.backingArray.push(element);\n return undefined;\n }\n\n // Removes front element.\n pop() {\n return this.backingArray.shift();\n }\n\n // Empty queue.\n clear() {\n this.backingArray.length = 0;\n return undefined;\n }\n\n // Return array with all elements in queue in order.\n getAll() {\n return this.backingArray;\n }\n }"} {"doc_id": "54a41db3e306a6f60eeb78e6e59a11e6", "text": "var str = \"AbCdEf\"; //String\u30af\u30e9\u30b9// \nconst lowerStr = str.toLowerCase();\nconsole.log(lowerStr);\nconst upperStr = str.toUpperCase();\nconsole.log(upperStr);\n\n//\u9759\u7684\u30e1\u30bd\u30c3\u30c9\u30fb\u30fb\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3057\u306a\u304f\u3066\u3082\u4f7f\u3048\u308b\u30e1\u30bd\u30c3\u30c9\n//\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\u3057\u3066\u3044\u306a\u3044\u306e\u3067\u30d7\u30ed\u30d1\u30c6\u30a3\u306e\u5024\u304c\u4f7f\u3048\u306a\u3044\u3068\u3044\u3046\u5236\u9650\u306f\u3042\u308b\n// static \u30e1\u30bd\u30c3\u30c9\u540d(){\n// return \u5024\n// }\u3000\n\n//\u7d99\u627f\u30fb\u4e0a\u66f8\u304d\uff1a\u30af\u30e9\u30b9\u306e\u4e00\u90e8\u306e\u8ffd\u52a0\u30fb\u5909\u66f4\u30fb\u4e0a\u66f8\u304d\n\n//\u30dd\u30ea\u30e2\u30fc\u30d5\u30a3\u30ba\u30e0\uff1a\u7d99\u627f\u3057\u305f\u30af\u30e9\u30b9\u30fb\u7570\u306a\u308b\u30af\u30e9\u30b9\u3067\u3082\u540c\u3058\u540d\u524d\u306e\u30e1\u30bd\u30c3\u30c9\u3092\u4f7f\u3048\u308b\n//\u540c\u3058\u540d\u524d\u306e\u30e1\u30bd\u30c3\u30c9\u3060\u304c\u305d\u308c\u305e\u308c\u306e\u52d5\u304d\u65b9\u306f\u7570\u306a\u308b\n\n//\u30ab\u30d7\u30bb\u30eb\u5316\uff1a\u60c5\u5831\u96a0\u853d\u30fb\u30d7\u30ed\u30c6\u30af\u30c8\u3059\u308b\u3053\u3068\u3067\u4e2d\u8eab\u306e\u51e6\u7406\u3092\u4fdd\u8a3c\u3059\u308b\n\n// ------------------------\n\n//\u30af\u30e9\u30b9\u306e\u4f5c\u6210\nclass MyCar {\n //\u521d\u671f\u5316(constructor)\n constructor(color) {\n //\u5909\u6570\u306e\u5ba3\u8a00\u306f\u3053\u3053\u3067\u2193\n this.myPosition = 0;\n this.bodyColor = color;\n }\n\n //\u30e1\u30bd\u30c3\u30c9\u306e\u4f5c\u6210\n goForward(loc) {\n this.myPosition += loc;\n console.log(\"\u73fe\u5728\u5730\" + this.myPosition);\n }\n myColor() {\n console.log(\"\u30dc\u30c7\u30a3\u30ab\u30e9\u30fc\" + this.bodyColor);\n }\n}\n\n// var objCar = new MyCar(\"orange\"); //\u30a4\u30f3\u30b9\u30bf\u30f3\u30b9\u5316\n// objCar.goForward(20);\n// objCar.goForward(25);\n// objCar.myColor();\n\n//\u65b0\u3057\u3044\u30af\u30e9\u30b9\u306e\u4f5c\u6210 \u7d99\u627f(extends)\u3092\u5229\u7528\u3057\u305f\nclass PatrolCar extends MyCar {\n playSiren() {\n //Audio Class\n var audio = new Audio(\"patrol-car1.mp3\");\n audio.play();\n }\n}\n\nvar patCar = new PatrolCar(\"mono\");\n\n//HTML\u306ebutton\u3068\u30ea\u30f3\u30af\u3055\u305b\u308b\nfunction play() {\n patCar.playSiren();\n patCar.goForward(50);\n patCar.myColor();\n}\n\n//\u30af\u30e9\u30b9\u306b\u8ffd\u52a0\u6a5f\u80fd\u3092\u3064\u3051\u305f\u3044 super\nclass PatrolCar extends MyCar {\n constructor() {\n super(\"mono\");\n this.patLump = 10;\n }\n}"} {"doc_id": "550c7e971bbfeae67889f5ab1d90fc82", "text": "/*\n

      Given a balanced parentheses string S, compute the score of the string based on the following rule:

      \n\n
        \n\t
      • () has score 1
      • \n\t
      • AB has score A + B, where A and B are balanced parentheses strings.
      • \n\t
      • (A) has score 2 * A, where A is a balanced parentheses string.
      • \n
      \n\n

       

      \n\n
      \n

      Example 1:

      \n\n
      \nInput: "()"\nOutput: 1\n
      \n\n
      \n

      Example 2:

      \n\n
      \nInput: "(())"\nOutput: 2\n
      \n\n
      \n

      Example 3:

      \n\n
      \nInput: "()()"\nOutput: 2\n
      \n\n
      \n

      Example 4:

      \n\n
      \nInput: "(()(()))"\nOutput: 6\n
      \n\n

       

      \n\n

      Note:

      \n\n
        \n\t
      1. S is a balanced parentheses string, containing only ( and ).
      2. \n\t
      3. 2 <= S.length <= 50
      4. \n
      \n
      \n
      \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32 S\uff0c\u6309\u4e0b\u8ff0\u89c4\u5219\u8ba1\u7b97\u8be5\u5b57\u7b26\u4e32\u7684\u5206\u6570\uff1a

      \n\n
        \n\t
      • () \u5f97 1 \u5206\u3002
      • \n\t
      • AB \u5f97 A + B \u5206\uff0c\u5176\u4e2d A \u548c B \u662f\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32\u3002
      • \n\t
      • (A) \u5f97 2 * A \u5206\uff0c\u5176\u4e2d A \u662f\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32\u3002
      • \n
      \n\n

       

      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \u8f93\u5165\uff1a "()"\n\u8f93\u51fa\uff1a 1\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \u8f93\u5165\uff1a "(())"\n\u8f93\u51fa\uff1a 2\n
      \n\n

      \u793a\u4f8b 3\uff1a

      \n\n
      \u8f93\u5165\uff1a "()()"\n\u8f93\u51fa\uff1a 2\n
      \n\n

      \u793a\u4f8b 4\uff1a

      \n\n
      \u8f93\u5165\uff1a "(()(()))"\n\u8f93\u51fa\uff1a 6\n
      \n\n

       

      \n\n

      \u63d0\u793a\uff1a

      \n\n
        \n\t
      1. S \u662f\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32\uff0c\u4e14\u53ea\u542b\u6709 ( \u548c ) \u3002
      2. \n\t
      3. 2 <= S.length <= 50
      4. \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32 S\uff0c\u6309\u4e0b\u8ff0\u89c4\u5219\u8ba1\u7b97\u8be5\u5b57\u7b26\u4e32\u7684\u5206\u6570\uff1a

      \n\n
        \n\t
      • () \u5f97 1 \u5206\u3002
      • \n\t
      • AB \u5f97 A + B \u5206\uff0c\u5176\u4e2d A \u548c B \u662f\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32\u3002
      • \n\t
      • (A) \u5f97 2 * A \u5206\uff0c\u5176\u4e2d A \u662f\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32\u3002
      • \n
      \n\n

       

      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \u8f93\u5165\uff1a "()"\n\u8f93\u51fa\uff1a 1\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \u8f93\u5165\uff1a "(())"\n\u8f93\u51fa\uff1a 2\n
      \n\n

      \u793a\u4f8b 3\uff1a

      \n\n
      \u8f93\u5165\uff1a "()()"\n\u8f93\u51fa\uff1a 2\n
      \n\n

      \u793a\u4f8b 4\uff1a

      \n\n
      \u8f93\u5165\uff1a "(()(()))"\n\u8f93\u51fa\uff1a 6\n
      \n\n

       

      \n\n

      \u63d0\u793a\uff1a

      \n\n
        \n\t
      1. S \u662f\u5e73\u8861\u62ec\u53f7\u5b57\u7b26\u4e32\uff0c\u4e14\u53ea\u542b\u6709 ( \u548c ) \u3002
      2. \n\t
      3. 2 <= S.length <= 50
      4. \n
      \n*/\n\n\n/**\n * @param {string} S\n * @return {number}\n */\nvar scoreOfParentheses = function(S) {\n \n};"} {"doc_id": "5547ae47d0770bfc1f8acfa1f29be366", "text": "/* ---------- Start of the program ---------- */\n\n\n// Declaration of the strict mode\n'use strict';\n\n// Page load ending event\nwindow.addEventListener('DOMContentLoaded', function() {\n\n\t// Object with methods and properties\n\tvar temperatures = {\n\n\t\t// Inputs\n\t\tfahrenheit: document.getElementById('fahrenheit'),\n\t\tcelsius: document.getElementById('celsius'),\n\t\tkelvin: document.getElementById('kelvin'),\n\n\t\t// Formulas - from one measure to other measure\n\t\tfahrenheitCount: function() {\n\t\t\tthis.fahrenheit.addEventListener('input', function() {\n\n\t\t\t\t// From String to the Number\n\t\t\t\tvar num = parseFloat(this.value);\n\n\t\t\t\t// Formulas\n\t\t\t\ttemperatures.celsius.value = (num - 32) / 1.8;\n\t\t\t\ttemperatures.kelvin.value = ((num - 32) / 1.8) + 273.15;\n\t\t\t});\n\t\t},\n\n\t\tcelsiusCount: function() {\n\t\t\tthis.celsius.addEventListener('input', function() {\n\n\t\t\t\tvar num = parseFloat(this.value);\n\n\t\t\t\ttemperatures.fahrenheit.value = (num * 1.8) + 32;\n\t\t\t\ttemperatures.kelvin.value = num + 273.15;\n\t\t\t});\n\t\t},\n\n\t\tkelvinCount: function() {\n\t\t\tthis.kelvin.addEventListener('input', function() {\n\n\t\t\t\tvar num = parseFloat(this.value);\n\n\t\t\t\ttemperatures.celsius.value = num - 273.15;\n\t\t\t\ttemperatures.fahrenheit.value = ((num - 273.15) * 1.8) + 32;\n\t\t\t});\n\t\t}\n\t};\n\n\t// Counting methods calling\n\ttemperatures.fahrenheitCount();\n\ttemperatures.celsiusCount();\n\ttemperatures.kelvinCount();\n});\n\n\n/* ---------- End of the program ---------- */"} {"doc_id": "5598c07a16f09b734c83c04ddad5e306", "text": "/*1) Sort all the elements of the input array.\n2) Use two index variables l and r to traverse from left and right ends respectively. Initialize l as 0 and r as n-1.\n3) sum = a[l] + a[r]\n4) If sum is -ve, then l++\n5) If sum is +ve, then r\u2013\n6) Keep track of abs min sum.\n7) Repeat steps 3, 4, 5 and 6 while l < r Implementation */\n\nclass Two_elements_whose_sum_is_closest_to_zero {\n getResult() {\n var a = [1, 60, -10, 70, -80, 85]; // -80 , -10 , 1 , 60 , 70 , 85\n\n a.sort((item1, item2) => item1 - item2);\n var first = 0;\n var last = a.length - 1;\n var sum = 0;\n var min = 85;\n var minFirstElement = 0;\n var minSecondElement = 0;\n\n while (first < last) {\n sum = Math.abs(a[first] + a[last]);\n\n if (sum <= min) {\n min = sum;\n minFirstElement = a[first];\n minSecondElement = a[last];\n }\n if (sum < 0) first += 1;\n else last -= 1;\n }\n\n console.log(minFirstElement + \" \" + minSecondElement);\n }\n}\n\nlet res = new Two_elements_whose_sum_is_closest_to_zero();\nres.getResult();\n"} {"doc_id": "55e01a264148fc45ac611b63c74037ad", "text": "/*\n

      Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. \n

      \n

      Substrings that occur multiple times are counted the number of times they occur.

      \n\n

      Example 1:
      \n

      \nInput: \"00110011\"\nOutput: 6\nExplanation: There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\n
      Notice that some of these substrings repeat and are counted the number of times they occur.\n
      Also, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.\n
      \n

      \n\n

      Example 2:
      \n

      \nInput: \"10101\"\nOutput: 4\nExplanation: There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.\n
      \n

      \n\n

      Note:\n

    7. s.length will be between 1 and 50,000.
    8. \n
    9. s will only consist of \"0\" or \"1\" characters.
    10. \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32 s\uff0c\u8ba1\u7b97\u5177\u6709\u76f8\u540c\u6570\u91cf0\u548c1\u7684\u975e\u7a7a(\u8fde\u7eed)\u5b50\u5b57\u7b26\u4e32\u7684\u6570\u91cf\uff0c\u5e76\u4e14\u8fd9\u4e9b\u5b50\u5b57\u7b26\u4e32\u4e2d\u7684\u6240\u67090\u548c\u6240\u67091\u90fd\u662f\u7ec4\u5408\u5728\u4e00\u8d77\u7684\u3002

      \n\n

      \u91cd\u590d\u51fa\u73b0\u7684\u5b50\u4e32\u8981\u8ba1\u7b97\u5b83\u4eec\u51fa\u73b0\u7684\u6b21\u6570\u3002

      \n\n

      \u793a\u4f8b 1 :

      \n\n
      \n\u8f93\u5165: "00110011"\n\u8f93\u51fa: 6\n\u89e3\u91ca: \u67096\u4e2a\u5b50\u4e32\u5177\u6709\u76f8\u540c\u6570\u91cf\u7684\u8fde\u7eed1\u548c0\uff1a“0011”\uff0c“01”\uff0c“1100”\uff0c“10”\uff0c“0011” \u548c “01”\u3002\n\n\u8bf7\u6ce8\u610f\uff0c\u4e00\u4e9b\u91cd\u590d\u51fa\u73b0\u7684\u5b50\u4e32\u8981\u8ba1\u7b97\u5b83\u4eec\u51fa\u73b0\u7684\u6b21\u6570\u3002\n\n\u53e6\u5916\uff0c“00110011”\u4e0d\u662f\u6709\u6548\u7684\u5b50\u4e32\uff0c\u56e0\u4e3a\u6240\u6709\u76840\uff08\u548c1\uff09\u6ca1\u6709\u7ec4\u5408\u5728\u4e00\u8d77\u3002\n
      \n\n

      \u793a\u4f8b 2 :

      \n\n
      \n\u8f93\u5165: "10101"\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u67094\u4e2a\u5b50\u4e32\uff1a“10”\uff0c“01”\uff0c“10”\uff0c“01”\uff0c\u5b83\u4eec\u5177\u6709\u76f8\u540c\u6570\u91cf\u7684\u8fde\u7eed1\u548c0\u3002\n
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      • s.length \u57281\u523050,000\u4e4b\u95f4\u3002
      • \n\t
      • s \u53ea\u5305\u542b“0”\u6216“1”\u5b57\u7b26\u3002
      • \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32 s\uff0c\u8ba1\u7b97\u5177\u6709\u76f8\u540c\u6570\u91cf0\u548c1\u7684\u975e\u7a7a(\u8fde\u7eed)\u5b50\u5b57\u7b26\u4e32\u7684\u6570\u91cf\uff0c\u5e76\u4e14\u8fd9\u4e9b\u5b50\u5b57\u7b26\u4e32\u4e2d\u7684\u6240\u67090\u548c\u6240\u67091\u90fd\u662f\u7ec4\u5408\u5728\u4e00\u8d77\u7684\u3002

      \n\n

      \u91cd\u590d\u51fa\u73b0\u7684\u5b50\u4e32\u8981\u8ba1\u7b97\u5b83\u4eec\u51fa\u73b0\u7684\u6b21\u6570\u3002

      \n\n

      \u793a\u4f8b 1 :

      \n\n
      \n\u8f93\u5165: "00110011"\n\u8f93\u51fa: 6\n\u89e3\u91ca: \u67096\u4e2a\u5b50\u4e32\u5177\u6709\u76f8\u540c\u6570\u91cf\u7684\u8fde\u7eed1\u548c0\uff1a“0011”\uff0c“01”\uff0c“1100”\uff0c“10”\uff0c“0011” \u548c “01”\u3002\n\n\u8bf7\u6ce8\u610f\uff0c\u4e00\u4e9b\u91cd\u590d\u51fa\u73b0\u7684\u5b50\u4e32\u8981\u8ba1\u7b97\u5b83\u4eec\u51fa\u73b0\u7684\u6b21\u6570\u3002\n\n\u53e6\u5916\uff0c“00110011”\u4e0d\u662f\u6709\u6548\u7684\u5b50\u4e32\uff0c\u56e0\u4e3a\u6240\u6709\u76840\uff08\u548c1\uff09\u6ca1\u6709\u7ec4\u5408\u5728\u4e00\u8d77\u3002\n
      \n\n

      \u793a\u4f8b 2 :

      \n\n
      \n\u8f93\u5165: "10101"\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u67094\u4e2a\u5b50\u4e32\uff1a“10”\uff0c“01”\uff0c“10”\uff0c“01”\uff0c\u5b83\u4eec\u5177\u6709\u76f8\u540c\u6570\u91cf\u7684\u8fde\u7eed1\u548c0\u3002\n
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      • s.length \u57281\u523050,000\u4e4b\u95f4\u3002
      • \n\t
      • s \u53ea\u5305\u542b“0”\u6216“1”\u5b57\u7b26\u3002
      • \n
      \n*/\n\n\n/**\n * @param {string} s\n * @return {number}\n */\nvar countBinarySubstrings = function(s) {\n \n};"} {"doc_id": "56151d8f9c2df70693ee982394c5dd19", "text": "let person = {\n title: 'Duke',\n name: 'Nukem',\n age: 33\n};\n\nlet nestedArray = Object.entries(person);\n\nconsole.log(nestedArray);\n//--------------\nlet nestedArray2 = [];\n\nfor (let property in person) {\n nestedArray2.push([property, person[property]]);\n}\n\n//----------\n\n\n//Shallow copy means that it returns a new object that has the same key/value pairs, \n//but that you don't need to worry about cloning the values as well\nfunction clone(obj) {\n let cloneNow = Object.assign({}, obj);\n return cloneNow;\n}\n\nlet coolPerson = {\n title: 'Duke',\n name: 'Nukem',\n age: 33\n};\n\nlet clonedPerson = clone(coolPerson);\ncoolPerson.age = 34;\n\nconsole.log(coolPerson.age); // 34\nconsole.log(clonedPerson.age); // 33"} {"doc_id": "5671bf7004fc830d6d4710feacf65b38", "text": "/*\n

      You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

      \n\n

      Note: You can assume that

      \n\n
        \n\t
      • 0 <= amount <= 5000
      • \n\t
      • 1 <= coin <= 5000
      • \n\t
      • the number of coins is less than 500
      • \n\t
      • the answer is guaranteed to fit into signed 32-bit integer
      • \n
      \n\n

       

      \n\n

      Example 1:

      \n\n
      \nInput: amount = 5, coins = [1, 2, 5]\nOutput: 4\nExplanation: there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n
      \n\n

       

      \n\n

      Example 2:

      \n\n
      \nInput: amount = 3, coins = [2]\nOutput: 0\nExplanation: the amount of 3 cannot be made up just with coins of 2.\n
      \n\n

       

      \n\n

      Example 3:

      \n\n
      \nInput: amount = 10, coins = [10] \nOutput: 1\n
      \n\n

       

      \n

      \u7ed9\u5b9a\u4e0d\u540c\u9762\u989d\u7684\u786c\u5e01\u548c\u4e00\u4e2a\u603b\u91d1\u989d\u3002\u5199\u51fa\u51fd\u6570\u6765\u8ba1\u7b97\u53ef\u4ee5\u51d1\u6210\u603b\u91d1\u989d\u7684\u786c\u5e01\u7ec4\u5408\u6570\u3002\u5047\u8bbe\u6bcf\u4e00\u79cd\u9762\u989d\u7684\u786c\u5e01\u6709\u65e0\u9650\u4e2a\u3002 

      \n\n

      \u6ce8\u610f: \u4f60\u53ef\u4ee5\u5047\u8bbe

      \n\n
        \n\t
      • 0 <= amount (\u603b\u91d1\u989d) <= 5000
      • \n\t
      • 1 <= coin (\u786c\u5e01\u9762\u989d) <= 5000
      • \n\t
      • \u786c\u5e01\u79cd\u7c7b\u4e0d\u8d85\u8fc7500\u79cd
      • \n\t
      • \u7ed3\u679c\u7b26\u540832\u4f4d\u7b26\u53f7\u6574\u6570
      • \n
      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: amount = 5, coins = [1, 2, 5]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u6709\u56db\u79cd\u65b9\u5f0f\u53ef\u4ee5\u51d1\u6210\u603b\u91d1\u989d:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: amount = 3, coins = [2]\n\u8f93\u51fa: 0\n\u89e3\u91ca: \u53ea\u7528\u9762\u989d2\u7684\u786c\u5e01\u4e0d\u80fd\u51d1\u6210\u603b\u91d1\u989d3\u3002\n
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \u8f93\u5165: amount = 10, coins = [10] \n\u8f93\u51fa: 1\n
      \n

      \u7ed9\u5b9a\u4e0d\u540c\u9762\u989d\u7684\u786c\u5e01\u548c\u4e00\u4e2a\u603b\u91d1\u989d\u3002\u5199\u51fa\u51fd\u6570\u6765\u8ba1\u7b97\u53ef\u4ee5\u51d1\u6210\u603b\u91d1\u989d\u7684\u786c\u5e01\u7ec4\u5408\u6570\u3002\u5047\u8bbe\u6bcf\u4e00\u79cd\u9762\u989d\u7684\u786c\u5e01\u6709\u65e0\u9650\u4e2a\u3002 

      \n\n

      \u6ce8\u610f: \u4f60\u53ef\u4ee5\u5047\u8bbe

      \n\n
        \n\t
      • 0 <= amount (\u603b\u91d1\u989d) <= 5000
      • \n\t
      • 1 <= coin (\u786c\u5e01\u9762\u989d) <= 5000
      • \n\t
      • \u786c\u5e01\u79cd\u7c7b\u4e0d\u8d85\u8fc7500\u79cd
      • \n\t
      • \u7ed3\u679c\u7b26\u540832\u4f4d\u7b26\u53f7\u6574\u6570
      • \n
      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: amount = 5, coins = [1, 2, 5]\n\u8f93\u51fa: 4\n\u89e3\u91ca: \u6709\u56db\u79cd\u65b9\u5f0f\u53ef\u4ee5\u51d1\u6210\u603b\u91d1\u989d:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: amount = 3, coins = [2]\n\u8f93\u51fa: 0\n\u89e3\u91ca: \u53ea\u7528\u9762\u989d2\u7684\u786c\u5e01\u4e0d\u80fd\u51d1\u6210\u603b\u91d1\u989d3\u3002\n
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \u8f93\u5165: amount = 10, coins = [10] \n\u8f93\u51fa: 1\n
      \n*/\n\n\n/**\n * @param {number} amount\n * @param {number[]} coins\n * @return {number}\n */\nvar change = function(amount, coins) {\n \n};"} {"doc_id": "58be8805e68af9c695f0671d209b8f55", "text": "\ufeff/*Write a script that shows the sign (+, - or 0) of the product of three real numbers, without calculating it.\nUse a sequence of if operators.\nExamples:\n\na\tb\t c\t result\n5\t2\t 2\t +\n-2\t-2\t 1\t +\n-2\t4\t 3\t -\n0\t-2.5\t4\t 0\n-1\t-0.5\t-5.1\t- */\n\nconsole.log('============================================');\nconsole.log('02.Multiplication sign');\nconsole.log('---------------------------------');\n\nfunction showSign(a, b, c) {\n var numbers = [a, b ,c],\n minusCount = 0,\n i,\n len = numbers.length;\n\n if (a === 0 || b === 0 || c === 0) {\n console.log('a= ' + a + ', b= ' + b + ', c= ' + c + ' --> ' + '0');\n }\n else {\n for (i = 0; i < len; i += 1) {\n if (numbers[i] < 0) {\n minusCount += 1;\n }\n }\n if (minusCount % 2 === 0) {\n console.log('a= ' + a + ', b= ' + b + ', c= ' + c + ' --> ' + '+');\n }\n else {\n console.log('a= ' + a + ', b= ' + b + ', c= ' + c + ' --> ' + '-');\n }\n }\n}\n\nshowSign(5, 2, 2);\nshowSign(-2, -2, 1);\nshowSign(-2, 4, 3);\nshowSign(0, -2.5, 4);\nshowSign(-1, -0.5, -5.1);"} {"doc_id": "5922f9c187ace7321f23cd7395479a77", "text": "var mapOnes = {\n 0: \"\",\n 1: \"One\",\n 2: \"Two\",\n 3: \"Three\",\n 4: \"Four\",\n 5: \"Five\",\n 6: \"Six\",\n 7: \"Seven\",\n 8: \"Eight\",\n 9: \"Nine\",\n}\n\nvar mapTens = {\n 10: \"Ten\",\n 11: \"Eleven\",\n 12: \"Twelve\",\n 13: \"Thirteen\",\n 14: \"Fourteen\",\n 15: \"Fifteen\",\n 16: \"Sixteen\",\n 17: \"Seventeen\",\n 18: \"Eighteen\",\n 19: \"Nineteen\",\n}\n\nvar mapTenths = {\n 2: \"Twenty\",\n 3: \"Thirty\",\n 4: \"Forty\",\n 5: \"Fifty\",\n 6: \"Sixty\",\n 7: \"Seventy\",\n 8: \"Eighty\",\n 9: \"Ninety\",\n}\n\nfunction int(val) {\n return parseInt(val);\n}\n\nfunction str(val) {\n return val.toString();\n}\n\n\n// Convert ones number to word.\n// ----------\n// Parameters\n// ----------\n// num: int\n// Single digit integer number\nfunction convertOnes(num) {\n if (str(num).length > 1) {\n throw new Error(\"Must have at most 1 digit\");\n }\n\n num = int(num);\n return mapOnes[num];\n}\n\n\n// Convert tenths number to word.\n// ----------\n// Parameters\n// ----------\n// num: int\n// Double digit integer number\nfunction convertTenths(num) {\n if (str(num).length > 2) {\n throw new Error(\"Must have at most 2 digits\");\n }\n\n num = int(num);\n var bases = \"\";\n\n // less than 10\n if (num < 10) {\n return mapOnes[num];\n }\n\n\n // 10-19\n if (10 <= num && num < 20) {\n return mapTens[num];\n }\n\n // 20-99\n var firstNum = mapTenths[int(str(num)[0])];\n var secondNum = mapOnes[int(str(num)[1])];\n\n if (!secondNum) {\n return firstNum;\n }\n\n return firstNum + \" \" + secondNum;\n}\n\n\n// Given hundredth, tenth and one integer number for base (e.g. Billion, Million), return converted word\n// ----------\n// Parameters\n// ----------\n// hundredth: int\n// Hundredth number\n// tenth: int\n// Tenth number\n// one: int\n// One number\n// base: string\n// Base value\nfunction getDollar(hundredth, tenth, one, base) {\n var dollarWord = \"\";\n if (hundredth) {\n dollarWord += convertOnes(hundredth) + \" Hundred\";\n }\n\n // Add \"And\" if there's numbers after hundredths\n if (hundredth && (tenth || one)) {\n dollarWord += \" And \";\n }\n\n if (tenth || one) {\n dollarWord += convertTenths(int(str(tenth) + str(one)));\n }\n\n if (base) {\n dollarWord += \" \" + base;\n }\n\n return dollarWord;\n}\n\n\nfunction getBillion(hundredth, tenth, one) {\n return getDollar(hundredth, tenth, one, \"Billion\");\n}\n\n\nfunction getMillion(hundredth, tenth, one) {\n return getDollar(hundredth, tenth, one, \"Million\");\n}\n\n\nfunction getThousand(hundredth, tenth, one) {\n return getDollar(hundredth, tenth, one, \"Thousand\");\n}\n\n\nfunction getOne(hundredth, tenth, one) {\n return getDollar(hundredth, tenth, one, \"\");\n}\n\n// Given tenth and one integer number (for cent), return converted word\n// ----------\n// Parameters\n// ----------\n// tenth: int\n// Tenth number\n// one: int\n// One number\nfunction getCent(tenth, one) {\n var centWord = \"\";\n if (tenth || one) {\n centWord += convertTenths(int(str(tenth) + str(one)));\n }\n\n if (centWord) {\n centWord = \"Cents \" + centWord + \" \";\n }\n\n return centWord;\n}\n\n\nfunction getIndex(val, index, defaultVal) {\n defaultVal = defaultVal || 0;\n if (val[index] === undefined) {\n return defaultVal;\n } else {\n return val[index];\n }\n}\n\n\n// Given a max 3 character number, extract and return hundredth, tenth and one value.\n// Return array in format [int, int, int] for values [hundredth, tenth, one]\n// ----------\n// Parameters\n// ----------\n// num: string\n// Number in string\n//\nfunction extract(num) {\n var hundredth = 0;\n var tenth = 0;\n var one = 0;\n if (num.length === 3) {\n hundredth = int(num[0]);\n tenth = int(num[1]);\n one = int(num[2]);\n }\n\n if (num.length === 2) {\n tenth = int(num[0]);\n one = int(num[1]);\n }\n\n if (num.length === 1) {\n one = int(num[0]);\n }\n\n return [hundredth, tenth, one];\n}\n\n\n// Generate word for dollar\n// ----------\n// Parameters\n// ----------\n// num: string\n// Dollar number in string\nfunction generateDollarWord(num) {\n var word = \"\";\n var billionNum;\n var millionNum;\n var thousandNum;\n var oneNum;\n var hundredth;\n var tenth;\n var one;\n var extractArr;\n\n // at least 1 billion\n if (num.length > 9) {\n billionNum = int(num.slice(0, num.length - 9));\n num = str(int(num) - (billionNum * int(1e9)));\n extractArr = extract(str(billionNum));\n hundredth = extractArr[0];\n tenth = extractArr[1];\n one = extractArr[2];\n word += getBillion(hundredth, tenth, one) + \" \";\n }\n\n // at least 1 million\n if (num.length > 6) {\n millionNum = int(num.slice(0, num.length - 6));\n num = str(int(num) - (millionNum * int(1e6)));\n extractArr = extract(str(millionNum));\n hundredth = extractArr[0];\n tenth = extractArr[1];\n one = extractArr[2];\n word += getMillion(hundredth, tenth, one) + \" \";\n }\n\n // at least 1 thousand\n if (num.length > 3) {\n thousandNum = int(num.slice(0, num.length - 3));\n num = str(int(num) - (thousandNum * int(1e3)));\n extractArr = extract(str(thousandNum));\n hundredth = extractArr[0];\n tenth = extractArr[1];\n one = extractArr[2];\n word += getThousand(hundredth, tenth, one) + \" \";\n }\n\n // at least 1\n if (int(num) && num.length > 0) {\n oneNum = int(num.slice(0, num.length));\n num = str(int(num) - oneNum);\n extractArr = extract(str(oneNum));\n\n hundredth = extractArr[0];\n tenth = extractArr[1];\n one = extractArr[2];\n word += getOne(hundredth, tenth, one) + \" \";\n }\n\n return word;\n}\n\n\n// Generate word for cent\n// ----------\n// Parameters\n// ----------\n// num: string\n// Cent number in string\nfunction generateCentWord(num) {\n var word = \"\";\n var hundredth;\n var tenth;\n var one;\n var extractArr;\n\n extractArr = extract(str(num));\n hundredth = extractArr[0];\n tenth = extractArr[1];\n one = extractArr[2];\n word += getCent(tenth, one);\n return word;\n}\n\n\nfunction validate(amt) {\n if (amt === \"\") {\n throw new Error(\"Please enter a valid amount\");\n }\n\n // amt MUST be in string to avoid accidental round off\n if (parseFloat(amt) > parseFloat(1e11)) {\n throw new Error(\"Please enter an amount smaller than 100 billion\");\n }\n\n if (getIndex(amt.split(\".\"), 1, \"\").length > 2) {\n throw new Error(\"Please enter an amount within 2 decimal place\");\n }\n}\n\n\nfunction generateWord(amt) {\n var amtList;\n var dollarAmt;\n var centAmt;\n var dollarWord;\n var centWord;\n\n // remove commas and spaces from word\n amt = amt.replace(/,/g, \"\").replace(/ /g, \"\");\n validate(amt);\n\n amt = str(parseFloat(amt).toFixed(2));\n amtList = amt.split(\".\");\n dollarAmt = getIndex(amtList, 0);\n centAmt = getIndex(amtList, 1);\n\n dollarWord = generateDollarWord(dollarAmt);\n centWord = generateCentWord(centAmt);\n\n if (!dollarWord) {\n return centWord + \"Only\";\n }\n\n if (!centWord) {\n return dollarWord + \"Only\";\n }\n\n return dollarWord + \"And \" + centWord + \"Only\";\n}\n\n\nmodule.exports = generateWord;\n"} {"doc_id": "5ae4431c332848180c072d670ab95a66", "text": "// This is an input class. Do not edit.\nclass BST {\n constructor(value) {\n this.value = value;\n this.left = null;\n this.right = null;\n }\n}\n\n// Solution 1\n// O(n) time / O(n) space\n// n - number of nodes in the tree\n\nconst findKthLargestValueInBST = (tree, k) => {\n const sortedNodeValues = [];\n inOrderTraverse(tree, sortedNodeValues);\n return sortedNodeValues[sortedNodeValues.length - k];\n};\n\nconst inOrderTraverse = (node, sortedNodeValues) => {\n if (node === null) return;\n\n inOrderTraverse(node.left, sortedNodeValues);\n sortedNodeValues.push(node.value);\n inOrderTraverse(node.right, sortedNodeValues);\n};\n\n// Solution 2\n// O(n) time / O(1) space\n// n - number of nodes in the tree\n\nclass TreeInfo {\n constructor(numberOfNodesVisited, latestVisitedNodeValue) {\n this.numberOfNodesVisited = numberOfNodesVisited;\n this.latestVisitedNodeValue = latestVisitedNodeValue;\n }\n}\n\nconst findKthLargestValueInBST = (tree, k) => {\n const treeInfo = new TreeInfo(0, -1);\n reverseInOrderTraverse(tree, k, treeInfo);\n return treeInfo.latestVisitedNodeValue;\n};\n\nconst reverseInOrderTraverse = (node, k, treeInfo) => {\n if (node === null || treeInfo.numberOfNodesVisited >= k) return;\n\n reverseInOrderTraverse(node.right, k, treeInfo);\n if (treeInfo.numberOfNodesVisited < k) {\n treeInfo.numberOfNodesVisited++;\n treeInfo.latestVisitedNodeValue = node.value;\n reverseInOrderTraverse(node.left, k, treeInfo);\n }\n};\n"} {"doc_id": "5b14e665706d1efc9611fba580097fdd", "text": "/*\n

      We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?

      \n\n

      Note that our partition must use every number in A, and that scores are not necessarily integers.

      \n\n
      \nExample:\nInput: \nA = [9,1,2,3,9]\nK = 3\nOutput: 20\nExplanation: \nThe best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned A into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n
      \n\n

       

      \n\n

      Note:

      \n\n
        \n\t
      • 1 <= A.length <= 100.
      • \n\t
      • 1 <= A[i] <= 10000.
      • \n\t
      • 1 <= K <= A.length.
      • \n\t
      • Answers within 10^-6 of the correct answer will be accepted as correct.
      • \n
      \n

      \u6211\u4eec\u5c06\u7ed9\u5b9a\u7684\u6570\u7ec4 A \u5206\u6210 K \u4e2a\u76f8\u90bb\u7684\u975e\u7a7a\u5b50\u6570\u7ec4 \uff0c\u6211\u4eec\u7684\u5206\u6570\u7531\u6bcf\u4e2a\u5b50\u6570\u7ec4\u5185\u7684\u5e73\u5747\u503c\u7684\u603b\u548c\u6784\u6210\u3002\u8ba1\u7b97\u6211\u4eec\u6240\u80fd\u5f97\u5230\u7684\u6700\u5927\u5206\u6570\u662f\u591a\u5c11\u3002

      \n\n

      \u6ce8\u610f\u6211\u4eec\u5fc5\u987b\u4f7f\u7528 A \u6570\u7ec4\u4e2d\u7684\u6bcf\u4e00\u4e2a\u6570\u8fdb\u884c\u5206\u7ec4\uff0c\u5e76\u4e14\u5206\u6570\u4e0d\u4e00\u5b9a\u9700\u8981\u662f\u6574\u6570\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165: \nA = [9,1,2,3,9]\nK = 3\n\u8f93\u51fa: 20\n\u89e3\u91ca: \nA \u7684\u6700\u4f18\u5206\u7ec4\u662f[9], [1, 2, 3], [9]. \u5f97\u5230\u7684\u5206\u6570\u662f 9 + (1 + 2 + 3) / 3 + 9 = 20.\n\u6211\u4eec\u4e5f\u53ef\u4ee5\u628a A \u5206\u6210[9, 1], [2], [3, 9].\n\u8fd9\u6837\u7684\u5206\u7ec4\u5f97\u5230\u7684\u5206\u6570\u4e3a 5 + 2 + 6 = 13, \u4f46\u4e0d\u662f\u6700\u5927\u503c.\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      • 1 <= A.length <= 100.
      • \n\t
      • 1 <= A[i] <= 10000.
      • \n\t
      • 1 <= K <= A.length.
      • \n\t
      • \u7b54\u6848\u8bef\u5dee\u5728 10^-6 \u5185\u88ab\u89c6\u4e3a\u662f\u6b63\u786e\u7684\u3002
      • \n
      \n

      \u6211\u4eec\u5c06\u7ed9\u5b9a\u7684\u6570\u7ec4 A \u5206\u6210 K \u4e2a\u76f8\u90bb\u7684\u975e\u7a7a\u5b50\u6570\u7ec4 \uff0c\u6211\u4eec\u7684\u5206\u6570\u7531\u6bcf\u4e2a\u5b50\u6570\u7ec4\u5185\u7684\u5e73\u5747\u503c\u7684\u603b\u548c\u6784\u6210\u3002\u8ba1\u7b97\u6211\u4eec\u6240\u80fd\u5f97\u5230\u7684\u6700\u5927\u5206\u6570\u662f\u591a\u5c11\u3002

      \n\n

      \u6ce8\u610f\u6211\u4eec\u5fc5\u987b\u4f7f\u7528 A \u6570\u7ec4\u4e2d\u7684\u6bcf\u4e00\u4e2a\u6570\u8fdb\u884c\u5206\u7ec4\uff0c\u5e76\u4e14\u5206\u6570\u4e0d\u4e00\u5b9a\u9700\u8981\u662f\u6574\u6570\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165: \nA = [9,1,2,3,9]\nK = 3\n\u8f93\u51fa: 20\n\u89e3\u91ca: \nA \u7684\u6700\u4f18\u5206\u7ec4\u662f[9], [1, 2, 3], [9]. \u5f97\u5230\u7684\u5206\u6570\u662f 9 + (1 + 2 + 3) / 3 + 9 = 20.\n\u6211\u4eec\u4e5f\u53ef\u4ee5\u628a A \u5206\u6210[9, 1], [2], [3, 9].\n\u8fd9\u6837\u7684\u5206\u7ec4\u5f97\u5230\u7684\u5206\u6570\u4e3a 5 + 2 + 6 = 13, \u4f46\u4e0d\u662f\u6700\u5927\u503c.\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      • 1 <= A.length <= 100.
      • \n\t
      • 1 <= A[i] <= 10000.
      • \n\t
      • 1 <= K <= A.length.
      • \n\t
      • \u7b54\u6848\u8bef\u5dee\u5728 10^-6 \u5185\u88ab\u89c6\u4e3a\u662f\u6b63\u786e\u7684\u3002
      • \n
      \n*/\n\n\n/**\n * @param {number[]} A\n * @param {number} K\n * @return {number}\n */\nvar largestSumOfAverages = function(A, K) {\n \n};"} {"doc_id": "5b989ca00f6948860e5890d88c633bbf", "text": "// Prototypal Inheritance\r\n\r\nclass Hangman {\r\n constructor(word, remainingGuesses) {\r\n this.word = word.toLowerCase().split('')\r\n this.remainingGuesses = remainingGuesses\r\n this.guessedLetters = [],\r\n this.status = 'playing'\r\n }\r\n get message() {\r\n if (this.status === 'playing') {\r\n if(this.remainingGuesses <= 2) {\r\n document.querySelector('#guesses').style.color = 'orange'\r\n return `${this.remainingGuesses} guesses remaining.`\r\n }\r\n document.querySelector('#guesses').style.color = 'white'\r\n if (this.remainingGuesses === 5) {\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-01.png'\r\n }\r\n return `${this.remainingGuesses} guesses remaining.`\r\n } else if (this.status === 'finished') {\r\n document.querySelector('#guesses').style.color = 'green'\r\n return `Congratulations! You finished!`\r\n } else if (this.status === 'failed') {\r\n document.querySelector('#guesses').style.color = 'red'\r\n return `Sorry, you failed. The word was \"${this.word.join('')}.\"`\r\n }\r\n }\r\n calculateStatus() {\r\n const finished = this.word.every((letter) => this.guessedLetters.includes(letter) || letter === ' ')\r\n if (this.remainingGuesses <= 0) {\r\n this.status = 'failed'\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-06.png'\r\n } else if (finished) {\r\n this.status = 'finished'\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-01.png'\r\n } else {\r\n this.status = 'playing'\r\n\r\n if (this.remainingGuesses === 5) {\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-01.png'\r\n } else if (this.remainingGuesses === 4) {\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-02.png'\r\n } else if (this.remainingGuesses === 3) {\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-03.png'\r\n } else if (this.remainingGuesses === 2) {\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-04.png'\r\n } else if (this.remainingGuesses === 1) {\r\n document.querySelector('#smiley').src = '/images/Hangman-smileys-05.png'\r\n }\r\n }\r\n }\r\n get puzzle() {\r\n let puzzle = ''\r\n\r\n // Looping over each letter inside the word array\r\n this.word.forEach((letter) => {\r\n\r\n // Checking if the guessed letters include any of the letters from the word array,\r\n // or if one of the letters is a space\r\n if (this.guessedLetters.includes(letter) || letter === ' ') {\r\n // if the guess is included in the word array, the letter is revealed\r\n // all letters that have not been guessed return an asterisk instead\r\n puzzle += letter\r\n } else {\r\n puzzle += '*'\r\n }\r\n\r\n })\r\n return puzzle\r\n }\r\n makeGuess(guess) {\r\n this.guess = guess.toLowerCase()\r\n\r\n // Checks to see if the guess is something that's included in the\r\n // previous guesses (in the guesseLetters array) and also\r\n // to see if it's included in the word\r\n const isUnique = !this.guessedLetters.includes(guess)\r\n const isBadGuess = !this.word.includes(guess)\r\n\r\n // If the guess is unique, it's pushed to the guessedLetters array\r\n if (isUnique && this.remainingGuesses > 0) {\r\n this.guessedLetters.push(guess)\r\n }\r\n\r\n // If the guess is unique and also not in the word, we reduce the\r\n // number of remaining guesses by 1\r\n if (isUnique && isBadGuess) {\r\n this.remainingGuesses--\r\n }\r\n\r\n this.calculateStatus()\r\n }\r\n}\r\n\r\n\r\n// Hangman.prototype.getMessage = function () {\r\n// }\r\n\r\n// Hangman.prototype.calculateStatus = function () {\r\n\r\n // - - E V E R Y M E T H O D - - \r\n\r\n // Returns either true or false. Will return true if EVERY array item\r\n // matches the comparsion function. Otherwise, returns false.\r\n // Goes through each letter in this.word, and checks to see if\r\n // every letter is also included in the guessedLetters array. \r\n // If they're all there, the function returns true. If one or more\r\n // letters is not present in the guessedLetters array, returns false\r\n\r\n // Shorthand below\r\n // const finished = this.word.every((letter) => this.guessedLetters.includes(letter))\r\n\r\n // const finished = this.word.every((letter) => {\r\n // return this.guessedLetters.includes(letter)\r\n // })\r\n\r\n\r\n // - - F I L T E R M E T H O D - -\r\n\r\n // Goes through each letter in this.word, and returns those that\r\n // are NOT included in guessedLetters. If the number of missing letters\r\n // from this.word is anything other than 0, finished = false\r\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n // const lettersUnguessed = this.word.filter((letter) => {\r\n // return !this.guessedLetters.includes(letter)\r\n // })\r\n // const finished = lettersUnguessed.length === 0\r\n \r\n \r\n\r\n // - - F O R E A C H M E T H O D - -\r\n \r\n // Goes over each letter in this.word to see if that letter is also in the\r\n // guessedLetters array. If it is, that means that letter has been guessed.\r\n // Since we set finished = true, we don't update it unless we're setting\r\n // it to false.\r\n // If after going through this process it's determined that some letter\r\n // from this.word was not guessed, we set finshed = false\r\n // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n // let finished = true\r\n // this.word.forEach((letter) => {\r\n // if (this.guessedLetters.includes(letter)) {\r\n\r\n // } else {\r\n // finished = false\r\n // }\r\n // })\r\n\r\n // if (this.remainingGuesses <= 0) {\r\n // this.status = 'failed'\r\n // } else if (finished) {\r\n // this.status = 'finished'\r\n // } else {\r\n // this.status = 'playing'\r\n // }\r\n // if (this.guessedLetters.includes('c') && this.remainingGuesses > 0) {\r\n // status = 'finished'\r\n// }\r\n\r\n\r\n// Hangman.prototype.getPuzzle = function () {\r\n // setting puzzle to an empty string to be populated in the function below\r\n // let puzzle = ''\r\n\r\n // // Looping over each letter inside the word array\r\n // this.word.forEach((letter) => {\r\n\r\n // // Checking if the guessed letters include any of the letters from the word array\r\n // if (this.guessedLetters.includes(letter) || letter === ' ') {\r\n // // if the guess is included in the word array, the letter is revealed\r\n // // all letters that have not been guessed return an asterisk instead\r\n // puzzle += letter\r\n // } else {\r\n // puzzle += '*'\r\n // }\r\n \r\n // })\r\n // return puzzle\r\n// }\r\n\r\n// A method that takes in a user guess to check it against the word\r\n// in a given hangman game\r\n// Hangman.prototype.makeGuess = function(guess) {\r\n// // Setting everything to lowercase to case-insensitivity\r\n// this.guess = guess.toLowerCase()\r\n\r\n// // Checks to see if the guess is something that's included in the\r\n// // previous guesses (in the guesseLetters array) and also\r\n// // to see if it's included in the word\r\n// const isUnique = !this.guessedLetters.includes(guess)\r\n// const isBadGuess = !this.word.includes(guess)\r\n\r\n// // If the guess is unique, it's pushed to the guessedLetters array\r\n// if (isUnique && this.remainingGuesses > 0) {\r\n// this.guessedLetters.push(guess)\r\n// }\r\n\r\n// // If the guess is unique and also not in the word, we reduce the\r\n// // number of remaining guesses by 1\r\n// if (isUnique && isBadGuess) {\r\n// this.remainingGuesses--\r\n// }\r\n\r\n// this.calculateStatus()\r\n// }\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n// // First attempt at Challenge 3 - Was able to render the asterisks on\r\n// // each keypress, but couldn't figure out how to get beyond that\r\n// // instead of setting the wordElement textContent to word, we had to\r\n// // set it to game1.getPuzzle to get the correctly guessed letters to render\r\n// // Probably not the most efficient route, but it's working! Added a line\r\n// // to clear innerHTML each time the puzzle renders to prevent it from needing\r\n// // to scroll after adding children\r\n\r\n// // const generateHangmanDOM = (word) => {\r\n// // const divElement = document.createElement('div')\r\n// // const wordElement = document.createElement('h2')\r\n// // const guessElement = document.createElement('h3')\r\n// // wordElement.textContent = game2.getPuzzle()\r\n// // guessElement.textContent = `${game2.remainingGuesses} guesses remaining.`\r\n// // divElement.appendChild(wordElement)\r\n// // divElement.appendChild(guessElement)\r\n\r\n// // return divElement\r\n// // }\r\n\r\n// // const renderPuzzle = (word) => {\r\n// // document.querySelector('#puzzle-div').innerHTML = ''\r\n// // const gameElement = generateHangmanDOM(word)\r\n// // document.querySelector('#puzzle-div').appendChild(gameElement)\r\n// // }"} {"doc_id": "5bf5752224f27c51436f13c710c2280f", "text": "// 1\nconst numbers = [1, 1, 2, 3, 5];\nconst numbersAddFive = \n numbers.map(n => n +5);\n// The below line should console.log: [6, 6, 7, 8, 10]\nconsole.log(numbersAddFive); \n\n// 2 - uncomment the lines that start with \"const\" and \"console.log\"\n const numbersReformatted = \n numbers.map(str => str.toString() + \":\");// The below line should console.log: [\"1: \", \"1: \", \"2: \", \"3: \", \"5: \"] \n console.log(numbersReformatted);\n\n// 3\nconst words = [\"planes\", \"trains\", \"automobiles\"];\nconst singularWords = \n words.map(word => word.slice(0,word.length - 1));\n// The below line should console.log: [\"plane\", \"train\", \"automobile\"]\nconsole.log(singularWords);\n\n// 4:\n const firstLetters = \n words.map(word => word.slice(0,1));\n// The below line should console.log: [\"p\", \"t\", \"a\"]\n console.log(firstLetters);\n\n// Bonus:\n// const capitalizedWords = \n// The below line should console.log: [\"Planes\", \"Trains\", \"Automobiles\"]\n// console.log(capitalizedWords);"} {"doc_id": "5ca1e6263cf737f0d8c41b1e137502e7", "text": "/**\n * Circular queue without the number of items being used\n * for the traversal.\n */\nclass CircularQueue {\n /**\n * Constructor function for the Circular Queue\n * @param {*} maxSize\n */\n constructor(maxSize) {\n this.front = 0;\n this.rear = -1;\n this.maxSize = maxSize + 1; //+1 to the size passed in the constructor\n this.array = new Array(this.maxSize); // overall +2 elements are there in the array\n }\n /**\n * Checking whether Queue is empty\n * 2-conditions has to be checked contiguous or broken sequence\n * contiguous -> f = 0 / rear = -1 => front = rear + 1 | both are on same side\n * broken -> f = mid / rear = crossed the boundary => rear = front + maxsize-\u00f71 | different sides\n */\n isEmpty() {\n return (\n this.front == this.rear + 1 || this.rear == this.front + this.maxSize - 1\n );\n }\n /**\n * checking whether the queue is full or not\n * contiguous sequence : f = 0 | rear = maxsize -1 => rear = front + maxsize -2\n * broken sequence : f = mid | rear +2 => front = rear +2\n */\n isFull() {\n return (\n this.front + this.maxSize - 2 == this.rear || this.front == this.rear + 2\n );\n }\n /**\n * Generating the number of items in the queue.\n */\n size() {\n if (this.rear >= this.front) {\n //contiguous\n return this.rear - this.front + 1;\n } else {\n return this.maxSize - this.front + (this.rear + 1);\n }\n }\n /**\n * Putting elements in the queue\n * @param {*} element\n */\n enqueue(element) {\n let flag = true;\n if (!this.isFull()) {\n if (this.rear == this.maxSize - 1) {\n this.rear = -1;\n }\n this.array[++this.rear] = element;\n flag = true;\n }\n return flag;\n }\n /**\n * removing element from the queue\n */\n dequeue() {\n let temp = -1;\n if (!this.isEmpty()) {\n temp = this.array[this.front++]; //incrementing the front\n if (this.front === this.maxSize) {\n //handling if front has reached the maxsize\n this.front = 0;\n }\n }\n return temp;\n }\n /**\n * returning element on the front of the queue\n */\n peek() {\n return this.array[this.front];\n }\n /**\n * Display the queue\n */\n display() {\n console.log(\"-----------------------\");\n console.log(`front is @ ${this.front} and rear is @ ${this.rear}`);\n console.log(`Max elements (${this.maxSize}) and Size of Queue ${this.size()}`);\n let result = \"\";\n\n /**\n * contiguous sequence\n * f = 0 ; re = mid\n * f = mid ; rear - back\n *\n * broken sequence\n * rear + maxsize -2 > front\n */\n //All the elements are deleted as well but this should be handled in the isEmpty() in the start of this method\n if (this.isEmpty()) {\n console.log(`There are no elements in the Queue to display.`);\n result += `rear --> front`;\n } else {\n if (this.front < this.rear) {\n result = \"front-->\";\n for (let i = this.front; i <= this.rear; i++) {\n result += `${this.array[i]}-->`;\n }\n result += \"rear\";\n } else if (this.front > this.rear) {\n //rear have crossed the boundary\n result = \"front-->\";\n // when front is within limits while rear has crossed the boundary\n for (let i = this.front; i < this.maxSize; i++) {\n result += `${this.array[i]}-->`;\n }\n //traverse till rear as well\n for (let i = 0; i <= this.rear; i++) {\n result += `${this.array[i]}-->`;\n }\n result += \"rear\";\n } else {\n //there is only 1 element in the array;\n console.log(`what has to be done here ???? `);\n }\n }\n console.log(`Queue is :${result}`);\n console.log(\"-----------------------\");\n }\n /**\n * method for showing the operations that can be done\n * using the circular queue.\n */\n static demo() {\n let myCircularQ = new CircularQueue(10);\n myCircularQ.enqueue(1);\n myCircularQ.enqueue(2);\n myCircularQ.enqueue(3);\n myCircularQ.enqueue(4);\n myCircularQ.enqueue(5);\n myCircularQ.enqueue(6);\n myCircularQ.enqueue(7);\n myCircularQ.enqueue(8);\n myCircularQ.display();\n while (!myCircularQ.isEmpty()) {\n console.log(\n `Removed : ${myCircularQ.dequeue()} with front :(${\n myCircularQ.front\n }) & rear: (${myCircularQ.rear})`\n );\n }\n myCircularQ.display();\n myCircularQ.enqueue(21);\n myCircularQ.enqueue(31);\n myCircularQ.enqueue(41);\n myCircularQ.display();\n myCircularQ.enqueue(51);\n myCircularQ.enqueue(61);\n myCircularQ.enqueue(71);\n myCircularQ.display();\n console.log(`Elements at the front of the Queue : ${myCircularQ.peek()}`)\n }\n}\n\nCircularQueue.demo();\n"} {"doc_id": "5d94a15bb97b3aca1d716d57a97be80b", "text": "/**\n * Turn text into colored text that supports MCBE\n * @param {string} text The text you want to format to rainbow colors.\n * @returns {string}\n * @example rainbowText('This is rainbow text!');\n */\nfunction rainbowText(text) {\n const rainbowCode = ['\u00a74', '\u00a7c', '\u00a76', '\u00a7e', '\u00a7g', '\u00a72', '\u00a7a', '\u00a7b', '\u00a73', '\u00a79', '\u00a75', '\u00a7d'];\n const letter = text.replace(/\u00a7./g, '').split('');\n let newMessage = '', rainbowIndex = 0;\n letter.forEach(letter => {\n if (letter !== ' ') {\n newMessage += `${rainbowCode[rainbowIndex]}${letter}`;\n rainbowIndex + 1 >= rainbowCode.length ? rainbowIndex = 0 : rainbowIndex++;\n }\n else\n newMessage += ' ';\n });\n return newMessage;\n}\n;\n/**\n * This will display in text in thousands, millions and etc... For ex: \"1400 -> \"1.4k\", \"1000000\" -> \"1M\", etc...\n * @param {number} number The number you want to convert\n * @returns {string}\n * @example compressNumber(15000);\n */\nfunction compressNumber(value) {\n const types = [\"\", \"k\", \"M\", \"G\", \"T\", \"P\", \"E\", \"Z\", \"Y\"];\n const selectType = Math.log10(value) / 3 | 0;\n if (selectType == 0)\n return value;\n let scaled = value / Math.pow(10, selectType * 3);\n return scaled.toFixed(1) + types[selectType];\n}\n;\n/**\n * Will format your number. For ex: \"1400\" -> \"1,400\", \"1000000\" -> \"1,000,000\", etc...\n * @param {number} number\n * @returns {string}\n * @example formatNumber(15000);\n */\nfunction formatNumber(value) {\n if (typeof value !== 'number')\n return;\n return value.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n;\n/**\n * Convert seconds, minutes, hours, days and week to milliseconds and vice versa\n * @param {string | number} value string time support: second, minute, hour, day, week.\n * @param {boolean} [compact] Return time string in a compact format\n * @returns {string | number | undefined}\n * @example MS('2 days') //Output: 172800000\n * MS('1d') //Output: 86400000\n * MS('10h') //Output: 36000000\n * MS('2.5 hrs') //Output: 9000000\n * MS('2h') //Output: 7200000\n * MS('1m') //Output: 60000\n * MS('5s') //Output: 5000\n * MS('1y') //Output: 31557600000\n * MS('100') //Output: 100\n * MS('-3 days') //Output: -259200000\n * MS('-1h') //Output: -3600000\n * MS('-200') //Output: -200\n *\n * //Convert from Milliseconds\n *\n * MS(86400000, { compact: true }); //Output: 1d\n * MS(86400000); //Output: 1 day\n * MS(172800000, { compact: true }); //Output: 2d\n * MS(172800000); //Output: 2 days\n */\nfunction MS(value, { compact } = {}) {\n if (typeof value === 'string')\n return timeToMs(value);\n if (typeof value === 'number')\n return msToTime(value, compact ? true : false);\n}\n;\n/**\n *\n * @param {string} string Time to ms\n * @returns {number}\n */\nfunction timeToMs(value) {\n if (!/^-?\\s?\\d*\\.?\\d*?\\s?((years*?|yrs*?)|(weeks*?)|(days*?)|(hours*?|hrs*?)|(minutes*?|mins*?)|(seconds*?|secs*?)|(milliseconds*?|msecs*?|ms)|[smhdwy])$/.test(value))\n return;\n const number = parseFloat(value.replace(/[^-.0-9]+/g, ''));\n if (/\\d+(?=\\s?(milliseconds?|msecs?|ms))/.test(value))\n return number;\n else if (/\\d+(?=\\s?s)/.test(value))\n return number * 1000;\n else if (/\\d+(?=\\s?m)/.test(value))\n return number * 60000;\n else if (/\\d+(?=\\s?h)/.test(value))\n return number * 3.6e+6;\n else if (/\\d+(?=\\s?d)/.test(value))\n return number * 8.64e+7;\n else if (/\\d+(?=\\s?w)/.test(value))\n return number * 6.048e+8;\n else if (/\\d+(?=\\s?y)/.test(value))\n return number * 3.154e+10;\n}\n;\n/**\n *\n * @param {number} ms Ms to Time\n * @param {boolean} [compact] Compact time format\n * @returns {string}\n */\nfunction msToTime(ms, compact) {\n let negative = Math.sign(ms) === -1, absMs = Math.abs(ms);\n let seconds = absMs / 1000, minutes = absMs / 60000, hours = absMs / 3.6e+6, days = absMs / 8.64e+7, weeks = absMs / 6.048e+8;\n if (absMs < 1000)\n return plural('ms', 'millisecond', negative, absMs, compact);\n else if (seconds < 60)\n return plural('s', 'second', negative, seconds, compact);\n else if (minutes < 60)\n return plural('m', 'minute', negative, minutes, compact);\n else if (hours < 24)\n return plural('h', 'hour', negative, hours, compact);\n else if (days < 7)\n return plural('d', 'day', negative, days, compact);\n else\n return plural('w', 'week', negative, weeks, compact);\n}\n;\nfunction plural(shortType, type, negative, number, compact) {\n number = Math.round(number);\n let origNumb = `${negative ? '-' : ''}${number}`;\n if (compact)\n return `${origNumb}${shortType}`;\n if (number > 1)\n return `${origNumb} ${type}s`;\n else\n return `${origNumb} ${type}`;\n}\n;\nexport { rainbowText, compressNumber, formatNumber, MS };\n"} {"doc_id": "5fd0c2abc8ac7371a847a6292b9cdd30", "text": "/*\n

      Say you have an array for which the ith element is the price of a given stock on day i.

      \n\n

      If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

      \n\n

      Note that you cannot sell a stock before you buy one.

      \n\n

      Example 1:

      \n\n
      \nInput: [7,1,5,3,6,4]\nOutput: 5\nExplanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n             Not 7-1 = 6, as selling price needs to be larger than buying price.\n
      \n\n

      Example 2:

      \n\n
      \nInput: [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.\n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u6570\u7ec4\uff0c\u5b83\u7684\u7b2c i \u4e2a\u5143\u7d20\u662f\u4e00\u652f\u7ed9\u5b9a\u80a1\u7968\u7b2c i \u5929\u7684\u4ef7\u683c\u3002

      \n\n

      \u5982\u679c\u4f60\u6700\u591a\u53ea\u5141\u8bb8\u5b8c\u6210\u4e00\u7b14\u4ea4\u6613\uff08\u5373\u4e70\u5165\u548c\u5356\u51fa\u4e00\u652f\u80a1\u7968\uff09\uff0c\u8bbe\u8ba1\u4e00\u4e2a\u7b97\u6cd5\u6765\u8ba1\u7b97\u4f60\u6240\u80fd\u83b7\u53d6\u7684\u6700\u5927\u5229\u6da6\u3002

      \n\n

      \u6ce8\u610f\u4f60\u4e0d\u80fd\u5728\u4e70\u5165\u80a1\u7968\u524d\u5356\u51fa\u80a1\u7968\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: [7,1,5,3,6,4]\n\u8f93\u51fa: 5\n\u89e3\u91ca: \u5728\u7b2c 2 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 1\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 5 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 6\uff09\u7684\u65f6\u5019\u5356\u51fa\uff0c\u6700\u5927\u5229\u6da6 = 6-1 = 5 \u3002\n     \u6ce8\u610f\u5229\u6da6\u4e0d\u80fd\u662f 7-1 = 6, \u56e0\u4e3a\u5356\u51fa\u4ef7\u683c\u9700\u8981\u5927\u4e8e\u4e70\u5165\u4ef7\u683c\u3002\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: [7,6,4,3,1]\n\u8f93\u51fa: 0\n\u89e3\u91ca: \u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b, \u6ca1\u6709\u4ea4\u6613\u5b8c\u6210, \u6240\u4ee5\u6700\u5927\u5229\u6da6\u4e3a 0\u3002\n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u6570\u7ec4\uff0c\u5b83\u7684\u7b2c i \u4e2a\u5143\u7d20\u662f\u4e00\u652f\u7ed9\u5b9a\u80a1\u7968\u7b2c i \u5929\u7684\u4ef7\u683c\u3002

      \n\n

      \u5982\u679c\u4f60\u6700\u591a\u53ea\u5141\u8bb8\u5b8c\u6210\u4e00\u7b14\u4ea4\u6613\uff08\u5373\u4e70\u5165\u548c\u5356\u51fa\u4e00\u652f\u80a1\u7968\uff09\uff0c\u8bbe\u8ba1\u4e00\u4e2a\u7b97\u6cd5\u6765\u8ba1\u7b97\u4f60\u6240\u80fd\u83b7\u53d6\u7684\u6700\u5927\u5229\u6da6\u3002

      \n\n

      \u6ce8\u610f\u4f60\u4e0d\u80fd\u5728\u4e70\u5165\u80a1\u7968\u524d\u5356\u51fa\u80a1\u7968\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: [7,1,5,3,6,4]\n\u8f93\u51fa: 5\n\u89e3\u91ca: \u5728\u7b2c 2 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 1\uff09\u7684\u65f6\u5019\u4e70\u5165\uff0c\u5728\u7b2c 5 \u5929\uff08\u80a1\u7968\u4ef7\u683c = 6\uff09\u7684\u65f6\u5019\u5356\u51fa\uff0c\u6700\u5927\u5229\u6da6 = 6-1 = 5 \u3002\n     \u6ce8\u610f\u5229\u6da6\u4e0d\u80fd\u662f 7-1 = 6, \u56e0\u4e3a\u5356\u51fa\u4ef7\u683c\u9700\u8981\u5927\u4e8e\u4e70\u5165\u4ef7\u683c\u3002\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: [7,6,4,3,1]\n\u8f93\u51fa: 0\n\u89e3\u91ca: \u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b, \u6ca1\u6709\u4ea4\u6613\u5b8c\u6210, \u6240\u4ee5\u6700\u5927\u5229\u6da6\u4e3a 0\u3002\n
      \n*/\n\n\n/**\n * @param {number[]} prices\n * @return {number}\n */\nvar maxProfit = function(prices) {\n \n};"} {"doc_id": "60075ee218cd467d73c092bcfe34a630", "text": "var numValor1 = parseInt(prompt(\"Informe o primeiro valor: \"));\nvar numValor2 = parseInt(prompt(\"Informe o segundo valor: \"));\n\nvar opcaoOperacao = parseInt(prompt(\"Qual opera\u00e7\u00e3o quer fazer:\\n 1-somar \\n 2-sub \\n 3-mult \\n 4-div \"));\n\nif(opcaoOperacao == 1){\n var resultado = numValor1 + numValor2;\n document.write(\"

      \" + numValor1 + \" + \" + numValor2 + \" = \" + resultado + \"

      \");\n}\nelse if (opcaoOperacao == 2) {\n var resultado = numValor1 - numValor2;\n document.write(\"

      \" + numValor1 + \" - \" + numValor2 + \" = \" + resultado + \"

      \");\n}\nelse if (opcaoOperacao == 3){\n var resultado = numValor1 * numValor2;\n document.write(\"

      \" + numValor1 + \" x \" + numValor2 + \" = \" + resultado + \"

      \");\n}\nelse if (opcaoOperacao == 4){\n var resultado = numValor1 / numValor2;\n document.write(\"

      \" + numValor1 + \" / \" + numValor2 + \" = \" + resultado + \"

      \");\n}\nelse {\n document.write(\"

      Op\u00e7\u00e3o Inv\u00e1lida

      \");\n}\n/*\nEscrevendo na tela - document.write();\n\n// Como foi dado em aula\nvar primeiroValor = parseInt(prompt(\"Digite o primeiro valor: \"));\nvar segundoValor = parseInt(prompt(\"Digite o segundo valor: \"));\nvar primeiroValorInt = parseInt(primeiroValor);\n\nvar resultado = primeiroValor * segundoValor\ndocument.write(resultado);\n*/\n\n/* Desafios da aula\n1-Criar um programa que converta libra em dolar, ou graus Celsius para Fahrenheit;\n2-Exibir o resultado da convers\u00e3o na tela, no lugar da fun\u00e7\u00e3o alert.*/\n\n/*CALCULADORA E LA\u00c7OS CONDICIONAIS NO JAVASCRIPT\nPARTICIPE E V\u00c1 MAIS FUNDO\nNesta segunda aula da Imers\u00e3o Dev, vamos criar uma calculadora, que realiza as principais opera\u00e7\u00f5es! O c\u00f3digo da aula inicial para voc\u00ea acompanhar est\u00e1 aqui:\n\nhttps://codepen.io/imersao-dev/pen/fe7e8d7e1820a0883499c1b85d0ef8f3\n\nN\u00e3o se esque\u00e7a de fazer o fork desse projeto para a sua conta, e de marcar a hashtag da #imersaodev e #alura.\n\nNesta programa, vamos aprender o que s\u00e3o la\u00e7os condicionais if e else, como comparar um valor com outro para executar um c\u00f3digo ou n\u00e3o. Al\u00e9m disso, vamos aprender como escrever na tela com a fun\u00e7\u00e3o document.write.\n\n*Conte\u00fado detalhado dessa aula\nInteragir com usu\u00e1rio para receber os valores que ser\u00e3o calculados;\nCriar a l\u00f3gica para saber qual opera\u00e7\u00e3o ser\u00e1 executada;\nComparar o valor da opera\u00e7\u00e3o escolhida para descobrir qual fun\u00e7\u00e3o ser\u00e1 realizada;\nExibir uma mensagem de erro, caso a opera\u00e7\u00e3o escolhida seja inv\u00e1lida;\nExibindo os valores escolhidos e o resultado da opera\u00e7\u00e3o com document.write;\n\n*Desafios dessa aula!\nExibir um pokemon na tela e pedir para o usuario escrever o nome desse pokemon. Exibir se acertou ou errou o nome.\n\n*Links importantes para voc\u00ea acompanhar a aula\nCodepen - editor de c\u00f3digo online ()\nOperadores boleanos (https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Expressions_and_operators)\nReposit\u00f3rio do c\u00f3digo final da aula 1(https://codepen.io/imersao-dev/pen/zYNOZRX)\n\n*Links citados nessa aula\nMais sobre vari\u00e1veis (https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Grammar_and_types#vari%C3%A1veis)\n\nUm igual, dois iguais e tr\u00eas iguais? QUE??? (https://pt.stackoverflow.com/questions/7/qual-a-diferen%C3%A7a-entre-os-operadores-e-em-javascript)\n\n*Conte\u00fados extras:\n-JavaScript segundo a documenta\u00e7\u00e3o (https://developer.mozilla.org/pt-BR/docs/Web/JavaScript)\n-Primeiros passos na programa\u00e7\u00e3o (https://hipsters.tech/primeiros-passos-na-programacao-a-imersao-dev-hipsters-ponto-tech-243/)\n-O que \u00e9 Javascript? (https://www.youtube.com/watch?v=NaVSbnnV75Q)\n-Evolu\u00e7\u00e3o do Javascript(https://www.youtube.com/watch?v=Bmw_6oOvO3s)*/"} {"doc_id": "600f326efba3e94cd6be0c9efd5b97ef", "text": "/*\n

      Implement atoi which converts a string to an integer.

      \n\n

      The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

      \n\n

      The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

      \n\n

      If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

      \n\n

      If no valid conversion could be performed, a zero value is returned.

      \n\n

      Note:

      \n\n
        \n\t
      • Only the space character ' ' is considered as whitespace character.
      • \n\t
      • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
      • \n
      \n\n

      Example 1:

      \n\n
      \nInput: "42"\nOutput: 42\n
      \n\n

      Example 2:

      \n\n
      \nInput: "   -42"\nOutput: -42\nExplanation: The first non-whitespace character is '-', which is the minus sign.\n             Then take as many numerical digits as possible, which gets 42.\n
      \n\n

      Example 3:

      \n\n
      \nInput: "4193 with words"\nOutput: 4193\nExplanation: Conversion stops at digit '3' as the next character is not a numerical digit.\n
      \n\n

      Example 4:

      \n\n
      \nInput: "words and 987"\nOutput: 0\nExplanation: The first non-whitespace character is 'w', which is not a numerical \n             digit or a +/- sign. Therefore no valid conversion could be performed.
      \n\n

      Example 5:

      \n\n
      \nInput: "-91283472332"\nOutput: -2147483648\nExplanation: The number "-91283472332" is out of the range of a 32-bit signed integer.\n             Thefore INT_MIN (−231) is returned.
      \n

      \u5b9e\u73b0 atoi\uff0c\u5c06\u5b57\u7b26\u4e32\u8f6c\u4e3a\u6574\u6570\u3002

      \n\n

      \u5728\u627e\u5230\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u4e4b\u524d\uff0c\u9700\u8981\u79fb\u9664\u6389\u5b57\u7b26\u4e32\u4e2d\u7684\u7a7a\u683c\u5b57\u7b26\u3002\u5982\u679c\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u662f\u6b63\u53f7\u6216\u8d1f\u53f7\uff0c\u9009\u53d6\u8be5\u7b26\u53f7\uff0c\u5e76\u5c06\u5176\u4e0e\u540e\u9762\u5c3d\u53ef\u80fd\u591a\u7684\u8fde\u7eed\u7684\u6570\u5b57\u7ec4\u5408\u8d77\u6765\uff0c\u8fd9\u90e8\u5206\u5b57\u7b26\u5373\u4e3a\u6574\u6570\u7684\u503c\u3002\u5982\u679c\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u662f\u6570\u5b57\uff0c\u5219\u76f4\u63a5\u5c06\u5176\u4e0e\u4e4b\u540e\u8fde\u7eed\u7684\u6570\u5b57\u5b57\u7b26\u7ec4\u5408\u8d77\u6765\uff0c\u5f62\u6210\u6574\u6570\u3002

      \n\n

      \u5b57\u7b26\u4e32\u53ef\u4ee5\u5728\u5f62\u6210\u6574\u6570\u7684\u5b57\u7b26\u540e\u9762\u5305\u62ec\u591a\u4f59\u7684\u5b57\u7b26\uff0c\u8fd9\u4e9b\u5b57\u7b26\u53ef\u4ee5\u88ab\u5ffd\u7565\uff0c\u5b83\u4eec\u5bf9\u4e8e\u51fd\u6570\u6ca1\u6709\u5f71\u54cd\u3002

      \n\n

      \u5f53\u5b57\u7b26\u4e32\u4e2d\u7684\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u5e8f\u5217\u4e0d\u662f\u4e2a\u6709\u6548\u7684\u6574\u6570\uff1b\u6216\u5b57\u7b26\u4e32\u4e3a\u7a7a\uff1b\u6216\u5b57\u7b26\u4e32\u4ec5\u5305\u542b\u7a7a\u767d\u5b57\u7b26\u65f6\uff0c\u5219\u4e0d\u8fdb\u884c\u8f6c\u6362\u3002

      \n\n

      \u82e5\u51fd\u6570\u4e0d\u80fd\u6267\u884c\u6709\u6548\u7684\u8f6c\u6362\uff0c\u8fd4\u56de 0\u3002

      \n\n

      \u8bf4\u660e\uff1a

      \n\n

      \u5047\u8bbe\u6211\u4eec\u7684\u73af\u5883\u53ea\u80fd\u5b58\u50a8 32 \u4f4d\u6709\u7b26\u53f7\u6574\u6570\uff0c\u5176\u6570\u503c\u8303\u56f4\u662f [−231,  231 − 1]\u3002\u5982\u679c\u6570\u503c\u8d85\u8fc7\u53ef\u8868\u793a\u7684\u8303\u56f4\uff0c\u5219\u8fd4\u56de  INT_MAX (231 − 1) \u6216 INT_MIN (−231) \u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: "42"\n\u8f93\u51fa: 42\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: "   -42"\n\u8f93\u51fa: -42\n\u89e3\u91ca: \u7b2c\u4e00\u4e2a\u975e\u7a7a\u767d\u5b57\u7b26\u4e3a '-', \u5b83\u662f\u4e00\u4e2a\u8d1f\u53f7\u3002\n     \u6211\u4eec\u5c3d\u53ef\u80fd\u5c06\u8d1f\u53f7\u4e0e\u540e\u9762\u6240\u6709\u8fde\u7eed\u51fa\u73b0\u7684\u6570\u5b57\u7ec4\u5408\u8d77\u6765\uff0c\u6700\u540e\u5f97\u5230 -42 \u3002\n
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \u8f93\u5165: "4193 with words"\n\u8f93\u51fa: 4193\n\u89e3\u91ca: \u8f6c\u6362\u622a\u6b62\u4e8e\u6570\u5b57 '3' \uff0c\u56e0\u4e3a\u5b83\u7684\u4e0b\u4e00\u4e2a\u5b57\u7b26\u4e0d\u4e3a\u6570\u5b57\u3002\n
      \n\n

      \u793a\u4f8b 4:

      \n\n
      \u8f93\u5165: "words and 987"\n\u8f93\u51fa: 0\n\u89e3\u91ca: \u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u662f 'w', \u4f46\u5b83\u4e0d\u662f\u6570\u5b57\u6216\u6b63\u3001\u8d1f\u53f7\u3002\n     \u56e0\u6b64\u65e0\u6cd5\u6267\u884c\u6709\u6548\u7684\u8f6c\u6362\u3002
      \n\n

      \u793a\u4f8b 5:

      \n\n
      \u8f93\u5165: "-91283472332"\n\u8f93\u51fa: -2147483648\n\u89e3\u91ca: \u6570\u5b57 "-91283472332" \u8d85\u8fc7 32 \u4f4d\u6709\u7b26\u53f7\u6574\u6570\u8303\u56f4\u3002 \n     \u56e0\u6b64\u8fd4\u56de INT_MIN (−231) \u3002\n
      \n

      \u5b9e\u73b0 atoi\uff0c\u5c06\u5b57\u7b26\u4e32\u8f6c\u4e3a\u6574\u6570\u3002

      \n\n

      \u5728\u627e\u5230\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u4e4b\u524d\uff0c\u9700\u8981\u79fb\u9664\u6389\u5b57\u7b26\u4e32\u4e2d\u7684\u7a7a\u683c\u5b57\u7b26\u3002\u5982\u679c\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u662f\u6b63\u53f7\u6216\u8d1f\u53f7\uff0c\u9009\u53d6\u8be5\u7b26\u53f7\uff0c\u5e76\u5c06\u5176\u4e0e\u540e\u9762\u5c3d\u53ef\u80fd\u591a\u7684\u8fde\u7eed\u7684\u6570\u5b57\u7ec4\u5408\u8d77\u6765\uff0c\u8fd9\u90e8\u5206\u5b57\u7b26\u5373\u4e3a\u6574\u6570\u7684\u503c\u3002\u5982\u679c\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u662f\u6570\u5b57\uff0c\u5219\u76f4\u63a5\u5c06\u5176\u4e0e\u4e4b\u540e\u8fde\u7eed\u7684\u6570\u5b57\u5b57\u7b26\u7ec4\u5408\u8d77\u6765\uff0c\u5f62\u6210\u6574\u6570\u3002

      \n\n

      \u5b57\u7b26\u4e32\u53ef\u4ee5\u5728\u5f62\u6210\u6574\u6570\u7684\u5b57\u7b26\u540e\u9762\u5305\u62ec\u591a\u4f59\u7684\u5b57\u7b26\uff0c\u8fd9\u4e9b\u5b57\u7b26\u53ef\u4ee5\u88ab\u5ffd\u7565\uff0c\u5b83\u4eec\u5bf9\u4e8e\u51fd\u6570\u6ca1\u6709\u5f71\u54cd\u3002

      \n\n

      \u5f53\u5b57\u7b26\u4e32\u4e2d\u7684\u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u5e8f\u5217\u4e0d\u662f\u4e2a\u6709\u6548\u7684\u6574\u6570\uff1b\u6216\u5b57\u7b26\u4e32\u4e3a\u7a7a\uff1b\u6216\u5b57\u7b26\u4e32\u4ec5\u5305\u542b\u7a7a\u767d\u5b57\u7b26\u65f6\uff0c\u5219\u4e0d\u8fdb\u884c\u8f6c\u6362\u3002

      \n\n

      \u82e5\u51fd\u6570\u4e0d\u80fd\u6267\u884c\u6709\u6548\u7684\u8f6c\u6362\uff0c\u8fd4\u56de 0\u3002

      \n\n

      \u8bf4\u660e\uff1a

      \n\n

      \u5047\u8bbe\u6211\u4eec\u7684\u73af\u5883\u53ea\u80fd\u5b58\u50a8 32 \u4f4d\u6709\u7b26\u53f7\u6574\u6570\uff0c\u5176\u6570\u503c\u8303\u56f4\u662f [−231,  231 − 1]\u3002\u5982\u679c\u6570\u503c\u8d85\u8fc7\u53ef\u8868\u793a\u7684\u8303\u56f4\uff0c\u5219\u8fd4\u56de  INT_MAX (231 − 1) \u6216 INT_MIN (−231) \u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \u8f93\u5165: "42"\n\u8f93\u51fa: 42\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \u8f93\u5165: "   -42"\n\u8f93\u51fa: -42\n\u89e3\u91ca: \u7b2c\u4e00\u4e2a\u975e\u7a7a\u767d\u5b57\u7b26\u4e3a '-', \u5b83\u662f\u4e00\u4e2a\u8d1f\u53f7\u3002\n     \u6211\u4eec\u5c3d\u53ef\u80fd\u5c06\u8d1f\u53f7\u4e0e\u540e\u9762\u6240\u6709\u8fde\u7eed\u51fa\u73b0\u7684\u6570\u5b57\u7ec4\u5408\u8d77\u6765\uff0c\u6700\u540e\u5f97\u5230 -42 \u3002\n
      \n\n

      \u793a\u4f8b 3:

      \n\n
      \u8f93\u5165: "4193 with words"\n\u8f93\u51fa: 4193\n\u89e3\u91ca: \u8f6c\u6362\u622a\u6b62\u4e8e\u6570\u5b57 '3' \uff0c\u56e0\u4e3a\u5b83\u7684\u4e0b\u4e00\u4e2a\u5b57\u7b26\u4e0d\u4e3a\u6570\u5b57\u3002\n
      \n\n

      \u793a\u4f8b 4:

      \n\n
      \u8f93\u5165: "words and 987"\n\u8f93\u51fa: 0\n\u89e3\u91ca: \u7b2c\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u662f 'w', \u4f46\u5b83\u4e0d\u662f\u6570\u5b57\u6216\u6b63\u3001\u8d1f\u53f7\u3002\n     \u56e0\u6b64\u65e0\u6cd5\u6267\u884c\u6709\u6548\u7684\u8f6c\u6362\u3002
      \n\n

      \u793a\u4f8b 5:

      \n\n
      \u8f93\u5165: "-91283472332"\n\u8f93\u51fa: -2147483648\n\u89e3\u91ca: \u6570\u5b57 "-91283472332" \u8d85\u8fc7 32 \u4f4d\u6709\u7b26\u53f7\u6574\u6570\u8303\u56f4\u3002 \n     \u56e0\u6b64\u8fd4\u56de INT_MIN (−231) \u3002\n
      \n*/\n\n\n/**\n * @param {string} str\n * @return {number}\n */\nvar myAtoi = function(str) {\n \n};"} {"doc_id": "60395b6ae2ba75232e277843999e43c7", "text": "// Declare a fuction\n\nfunction sayHello(){\n console.log(\"Hello\");\n}\n\n// Call or invoke a fuction\n\nsayHello();\nsayHello();\nsayHello();\n\n//Declaring a function with variable\n\nfunction sayGoodbye(name){\n console.log(sayGoodbye +\"name\");\n}\nsayGoodbye(\"Ash\");\nsayGoodbye(\"Raj\");\nsayGoodbye(\"Syamil\");\n\n\n// fuction with 2 parameters with results\nfunction sum(a,b){\n return a+b;\n \n}\nconsole.log(sum(2,3));\nconsole.log(sum(4,8));\n\n\n\n// function with result...( example of abstration if you need to use later )\nfunction checkEven (number){\n if (number %2 == 0){\n return true;\n } else {\n return false;\n }\n}\nconsole.log(checkEven(4));\n\n//function with multiple results\n\nfunction areaVolume(width,length,height){\n return [ width * length, width*length*height];\n}\nconsole.log (areaVolume(3,4,5));\n\n\n\n\n\n//Arrays\n// A collection of items..\n// I create an array of numbers, which is called scores..\nvar scores = [50,80,90,60,70];\n\n//how many items are there in your array\nconsole.log(scores.length);\n\n//retrieving item number x....\n\n// an array start with an idex 0... to retrieve the item, you will do scores(index)\n\n\nconsole.log(scores[0]);\n\n//go thru the array, retrieve the value from the array\n//show it in the console...\nfor (var i=0; i< scores.length; i++){\n console.log(scores[i]);\n}\n\n//add an item at the end of the array\nscores.push(50);\nconsole.log(scores);\n\n//remove the last item from an array\nscores.pop();\nconsole.log(scores);\n\nscores.splice(1,1);\nconsole.log(scores);\n\n\n\n\n\n\n// exercise 1\nvar numberArray = [3,5,1,9,6,4,2];\n\nfunction minMaxAvg(arr){\n var average = 0;\n var sum =0 ;\n // assume the first one is the smallest one\n var min = arr[0];\n var max = arr[0];\n for ( var i=0; i\");\ndocument.write(number.toPrecision(2));\ndocument.write(\"
      \");\ndocument.write(number.toFixed(2));\n\n\n\nconsole.log(Math.round(number)); // 13 (nearest integer)\nconsole.log(Math.ceil(number)); // 13\nconsole.log(Math.floor(number)); // 12\ndocument.write(\"
      \");\ndocument.write(number.toFixed(2));\ndocument.write(Math.random());\ndocument.write(\"
      \");\ndocument.write(Math.ceil(Math.random()*100));"} {"doc_id": "610e051c2357185a55450437f0689702", "text": "\n(function() {\n\n \"use strict\";\n\n /*\n\n function name(input) {\n return ??;\n }\n\n */\n\n\n // ================ JUSTIN FUNCTION DRILLS\n\n\n // 1) Make a function called returnTwo() that returns the number 2 when called\n // ---Test this function with console.log(returnTwo())\n\n function returnTwo() {\n return 2;\n }\n\n // console.log(returnTwo());\n\n\n // 2) Make a function called returnName() that returns the string of your name\n // ---Test this function with console.log(returnName())\n\n function returnName() {\n return \"Justin\";\n }\n // console.log(returnName());\n\n\n // 3) Make a function called addThree() which takes in a number input and returns the number plus 3.\n // ---Test this function with console.log(addThree(5))\n\n function addThree(numberInput) {\n return numberInput + 3;\n }\n\n var number = 5;\n\n // console.log(addThree(number));\n\n\n // 4) Make a function called sayString() which returns the string input passed in.\n // ---Test this function with console.log(sayString())\n\n function sayString(strInput) {\n return strInput;\n }\n\n // console.log(sayString(\"Hello\"));\n\n\n // 5) Make a function called sayHowdy() which console.logs the string \u201cHowdy!\u201d\n // ---Test this function by directly calling sayHowdy()\n // ---Remember this function does not need a defined return value\n\n function sayHowdy() {\n console.log(\"Howdy\");\n }\n\n // sayHowdy();\n\n\n\n// ================ RYAN FUNCTION DRILLS\n\n// Write a function called `identity(input)` that takes in an argument called input and returns that input.\n\n// Write a function called `getRandomNumber(min, max)` that returns a random number between min and max values sent to that function call.\n\n// Write a function called `first(input)` that returns the first character in the provided string.\n\n// Write a function called `last(input)` that returns the last character of a string\n\n// Write a function called `rest(input)` that returns everything but the first character of a string.\n\n// Write a function called `reverse(input)` that takes a string and returns it reversed.\n\n// Write a function called `isNumeric(input)` that takes an input and returns a boolean if the input is numeric.\n\n// Write a function called `count(input)` that takes in a string and returns the number of characters.\n\n// Write a function called `add(a, b)` that returns the sum of a and b\n\n// Write a function called `subtract(a, b)` that return the difference between the two inputs.\n\n// Write `multiply(a, b)` function that returns the product\n\n// Write a divide(numerator, denominator) function that returns a divided by b\n\n// Write a remainder(number, divisor) function that returns the remainder left over when dividing `number` by the `divisor`\n\n// Write the function `square(a)` that takes in a number and returns the number multiplied by itself.\n\n\n// # Super Duper Gold-Star Bonus\n// Write a function called sumOfSquares(a, b) that uses only your add() function and your square function and not + or * operators\n\n\n// Write a function called doMath(operator, a, b) that takes 3 parameters. The first parameter is the name of the math function you want to apply. a and b are the two numbers to run that function on.\n\n\n\n\n /**\n * TODO:\n * Create a function called 'sayHello' that takes a parameter 'name'.\n * When called, the function should return a message that says hello to the passed in name.\n *\n * Example\n * > sayHello(\"codeup\") // returns \"Hello, codeup!\"\n */\n\n function sayHello(name) {\n return \"Hello, \" + name + \"!\";\n }\n\n var name = \"codeup\";\n\n // console.log(sayHello(name));\n\n\n /**\n * TODO:\n * Call the function 'sayHello' and pass your name as a string literal argument.\n * Store the result of the function call in a variable named 'helloMessage'.\n *\n * console.log 'helloMessage' to check your work\n */\n\n // var helloMessage = sayHello(\"Justin\");\n //\n // console.log(helloMessage);\n\n\n /**\n * TODO:\n * Store your name as a string in a variable named 'myName', and pass that\n * variable to the 'sayHello' function. You should see the same output in the\n * console.\n */\n\n var myName = \"Justin\";\n\n // console.log(sayHello(myName));\n\n // Don't modify the following line, it generates a random number between 1 and\n // 100 and stores it in a variable named random\n var random = Math.floor((Math.random() * 100) + 1);\n\n\n /**\n * TODO:\n * Create a function called 'isTwo' that takes a number as a parameter.\n * The function should return a boolean value based on whether or not the passed\n * number is the number 2.\n *\n * Example\n * > isTwo(1) // returns false\n * > isTwo(2) // returns true\n * > isTwo(3) // returns false\n *\n * Call the function 'isTwo' passing the variable 'random' as a argument.\n *\n * console.log *outside of the function* to check your work (you should see a\n * different result everytime you refresh the page if you are using the random\n * number)\n */\n\n function isTwo(numInput) {\n return numInput === 2;\n }\n\n // console.log(isTwo(random));\n\n\n\n // ************************************************************** BONUS\n /**\n * TODO:\n * Create a function called 'isOdd' that takes a number as a parameter.\n * The function should use the ternary operator to return a message.\n * The message should contain the number being checked, and whether or not the\n * number is odd\n *\n * Example\n * > isOdd(42) // returns \"42 is not odd!\"\n *\n * Call the function 'isOdd' passing the variable 'random' as a parameter.\n * console.log *outside of the function* to check your work\n */\n\n\n\n /**\n * TODO: Create a function named 'calculateTip' to calculate a tip on a bill at a\n * restaurant\n *\n * the function should accept a tip percentage and the total of the bill, and\n * return the amount to tip\n *\n * Example\n * > calculateTip(0.20, 20) // returns 4\n */\n\n function calculateTip(tipDecimal, totalBill) {\n return tipDecimal * totalBill;\n }\n\n // console.log(calculateTip(.1, 100));\n\n\n /**\n * TODO: use prompt and alert in combination with your calculateTip function to\n * prompt the user for the bill total and a percentage they would like to tip,\n * then display the dollar amount they should tip\n */\n\n var totalBill = prompt(\"What is the total bill?\");\n var tipPercentage = prompt(\"What tip percentage will you use?\");\n\n var tipDecimal = tipPercentage / 100;\n\n alert(\"The amount to tip is: \" + calculateTip(tipDecimal, totalBill));\n\n\n})();"} {"doc_id": "6192ab97b9bd8df3b6b9d31c854d4bb7", "text": "/**\n * 1.\u5e26var \u548c function \u5173\u952e\u5b57 \u58f0\u660e\u76f8\u540c\u7684\u540d\u5b57\uff0c\u7b97\u4f5c\u91cd\u540d\n * \u53d8\u91cf\u63d0\u5347\u9636\u6bb5\uff0c\u5176\u5b9e\u662f\u4e00\u4e2a\u5c5e\u6027\uff0c\u53ea\u662f\u5b58\u50a8\u503c\u7684\u7c7b\u578b\u4e0d\u540c\n * 2.\u91cd\u540d\u7684\u5904\u7406\uff1b\n * \u5982\u679c\u540d\u5b57\u91cd\u590d\u4e86\uff0c\u4e0d\u4f1a\u91cd\u65b0\u7684\u58f0\u660e\uff0c\u4f46\u662f\u4f1a\u91cd\u65b0\u7684\u5b9a\u4e49\uff08\u91cd\u65b0\u8d4b\u503c\uff09\n * \u4e0d\u7ba1\u662f\u53d8\u91cf\u63d0\u5347\u8fd8\u662f\u4ee3\u7801\u6267\u884c\u9636\u6bb5 \u7686\u662f\u5982\u6b64\uff0c\n * \n */\n\n\n//window.fn;\n//window.fn;\n\n var fn = 12;\n\n function fn(){\n}\nconsole.log()\n\n/******************TEST01************** */\n/**\n * \u53d8\u91cf\u63d0\u5347\n * fn = ....(1)\n * = ....(2)\n * = ....(3)\n * = ....(4)\n * = ....(5)\n * \u540d\u5b57\u76f8\u540c\u7684\u65f6\u5019\uff0c\u4e0d\u4f1a\u91cd\u65b0\u7684\u58f0\u660e\uff0c\u53ea\u4f1a\u91cd\u65b0\u7684\u8d4b\u503c\n */\n\nfn(); //5\nfunction fn(){ console.log(1)}\nfn(); //5\nfunction fn(){ console.log(2)}\nfn(); //5\nvar fn = 100; //\u63d0\u5347\u9636\u6bb5\u53ea\u58f0\u660e\u4e0d\u8d4b\u503c\uff0c\u6267\u884c\u9636\u6bb5 \u8d4b\u503c fn=100\nfn(); //100()\u4e0d\u80fd\u6267\u884c Uncaught TypeError: fn is not a function\nfunction fn(){ console.log(3)}\nfn();\nfunction fn(){ console.log(4)}\nfn();\nfunction fn(){ console.log(5)}\nfn();"} {"doc_id": "619d502e5d159fd178df52acad82012f", "text": "/*\n

      \nGiven a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.\n

      \n

      Example 1:
      \n

      \nInput:\ns = \"abpcplea\", d = [\"ale\",\"apple\",\"monkey\",\"plea\"]\n\nOutput: \n\"apple\"\n
      \n

      \n\n

      \n

      Example 2:
      \n

      \nInput:\ns = \"abpcplea\", d = [\"a\",\"b\",\"c\"]\n\nOutput: \n\"a\"\n
      \n

      \n\n

      Note:
      \n

        \n
      1. All the strings in the input will only contain lower-case letters.
      2. \n
      3. The size of the dictionary won't exceed 1,000.
      4. \n
      5. The length of all the strings in the input won't exceed 1,000.
      6. \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\u548c\u4e00\u4e2a\u5b57\u7b26\u4e32\u5b57\u5178\uff0c\u627e\u5230\u5b57\u5178\u91cc\u9762\u6700\u957f\u7684\u5b57\u7b26\u4e32\uff0c\u8be5\u5b57\u7b26\u4e32\u53ef\u4ee5\u901a\u8fc7\u5220\u9664\u7ed9\u5b9a\u5b57\u7b26\u4e32\u7684\u67d0\u4e9b\u5b57\u7b26\u6765\u5f97\u5230\u3002\u5982\u679c\u7b54\u6848\u4e0d\u6b62\u4e00\u4e2a\uff0c\u8fd4\u56de\u957f\u5ea6\u6700\u957f\u4e14\u5b57\u5178\u987a\u5e8f\u6700\u5c0f\u7684\u5b57\u7b26\u4e32\u3002\u5982\u679c\u7b54\u6848\u4e0d\u5b58\u5728\uff0c\u5219\u8fd4\u56de\u7a7a\u5b57\u7b26\u4e32\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165:\ns = "abpcplea", d = ["ale","apple","monkey","plea"]\n\n\u8f93\u51fa: \n"apple"\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165:\ns = "abpcplea", d = ["a","b","c"]\n\n\u8f93\u51fa: \n"a"\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      1. \u6240\u6709\u8f93\u5165\u7684\u5b57\u7b26\u4e32\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002
      2. \n\t
      3. \u5b57\u5178\u7684\u5927\u5c0f\u4e0d\u4f1a\u8d85\u8fc7 1000\u3002
      4. \n\t
      5. \u6240\u6709\u8f93\u5165\u7684\u5b57\u7b26\u4e32\u957f\u5ea6\u4e0d\u4f1a\u8d85\u8fc7 1000\u3002
      6. \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32\u548c\u4e00\u4e2a\u5b57\u7b26\u4e32\u5b57\u5178\uff0c\u627e\u5230\u5b57\u5178\u91cc\u9762\u6700\u957f\u7684\u5b57\u7b26\u4e32\uff0c\u8be5\u5b57\u7b26\u4e32\u53ef\u4ee5\u901a\u8fc7\u5220\u9664\u7ed9\u5b9a\u5b57\u7b26\u4e32\u7684\u67d0\u4e9b\u5b57\u7b26\u6765\u5f97\u5230\u3002\u5982\u679c\u7b54\u6848\u4e0d\u6b62\u4e00\u4e2a\uff0c\u8fd4\u56de\u957f\u5ea6\u6700\u957f\u4e14\u5b57\u5178\u987a\u5e8f\u6700\u5c0f\u7684\u5b57\u7b26\u4e32\u3002\u5982\u679c\u7b54\u6848\u4e0d\u5b58\u5728\uff0c\u5219\u8fd4\u56de\u7a7a\u5b57\u7b26\u4e32\u3002

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165:\ns = "abpcplea", d = ["ale","apple","monkey","plea"]\n\n\u8f93\u51fa: \n"apple"\n
      \n\n

      \u793a\u4f8b 2:

      \n\n
      \n\u8f93\u5165:\ns = "abpcplea", d = ["a","b","c"]\n\n\u8f93\u51fa: \n"a"\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      1. \u6240\u6709\u8f93\u5165\u7684\u5b57\u7b26\u4e32\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u6bcd\u3002
      2. \n\t
      3. \u5b57\u5178\u7684\u5927\u5c0f\u4e0d\u4f1a\u8d85\u8fc7 1000\u3002
      4. \n\t
      5. \u6240\u6709\u8f93\u5165\u7684\u5b57\u7b26\u4e32\u957f\u5ea6\u4e0d\u4f1a\u8d85\u8fc7 1000\u3002
      6. \n
      \n*/\n\n\n/**\n * @param {string} s\n * @param {string[]} d\n * @return {string}\n */\nvar findLongestWord = function(s, d) {\n \n};"} {"doc_id": "61f9917ea192035a788045d80615f57c", "text": "/*\n

      Given an array of characters, compress it in-place.

      \n\n

      The length after compression must always be smaller than or equal to the original array.

      \n\n

      Every element of the array should be a character (not int) of length 1.

      \n \n

      After you are done modifying the input array in-place, return the new length of the array.

      \n\n
      \n\n

      Follow up:
      \nCould you solve it using only O(1) extra space?\n

      \n\n
      \n\n

      Example 1:
      \n

      \nInput:\n[\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\n\nOutput:\nReturn 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\n\nExplanation:\n\"aa\" is replaced by \"a2\". \"bb\" is replaced by \"b2\". \"ccc\" is replaced by \"c3\".\n
      \n

      \n\n

      Example 2:
      \n

      \nInput:\n[\"a\"]\n\nOutput:\nReturn 1, and the first 1 characters of the input array should be: [\"a\"]\n\nExplanation:\nNothing is replaced.\n
      \n

      \n\n

      Example 3:
      \n

      \nInput:\n[\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\n\nOutput:\nReturn 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\n\nExplanation:\nSince the character \"a\" does not repeat, it is not compressed. \"bbbbbbbbbbbb\" is replaced by \"b12\".\nNotice each digit has it's own entry in the array.\n
      \n

      \n\n

      Note:
      \n

        \n
      1. All characters have an ASCII value in [35, 126].
      2. \n
      3. 1 <= len(chars) <= 1000.
      4. \n
      \n

      \u7ed9\u5b9a\u4e00\u7ec4\u5b57\u7b26\uff0c\u4f7f\u7528\u539f\u5730\u7b97\u6cd5\u5c06\u5176\u538b\u7f29\u3002

      \n\n

      \u538b\u7f29\u540e\u7684\u957f\u5ea6\u5fc5\u987b\u59cb\u7ec8\u5c0f\u4e8e\u6216\u7b49\u4e8e\u539f\u6570\u7ec4\u957f\u5ea6\u3002

      \n\n

      \u6570\u7ec4\u7684\u6bcf\u4e2a\u5143\u7d20\u5e94\u8be5\u662f\u957f\u5ea6\u4e3a1 \u7684\u5b57\u7b26\uff08\u4e0d\u662f int \u6574\u6570\u7c7b\u578b\uff09\u3002

      \n\n

      \u5728\u5b8c\u6210\u539f\u5730\u4fee\u6539\u8f93\u5165\u6570\u7ec4\u540e\uff0c\u8fd4\u56de\u6570\u7ec4\u7684\u65b0\u957f\u5ea6\u3002

      \n\n

       

      \n\n

      \u8fdb\u9636\uff1a
      \n\u4f60\u80fd\u5426\u4ec5\u4f7f\u7528O(1) \u7a7a\u95f4\u89e3\u51b3\u95ee\u9898\uff1f

      \n\n

       

      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \n\u8f93\u5165\uff1a\n["a","a","b","b","c","c","c"]\n\n\u8f93\u51fa\uff1a\n\u8fd4\u56de6\uff0c\u8f93\u5165\u6570\u7ec4\u7684\u524d6\u4e2a\u5b57\u7b26\u5e94\u8be5\u662f\uff1a["a","2","b","2","c","3"]\n\n\u8bf4\u660e\uff1a\n"aa"\u88ab"a2"\u66ff\u4ee3\u3002"bb"\u88ab"b2"\u66ff\u4ee3\u3002"ccc"\u88ab"c3"\u66ff\u4ee3\u3002\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \n\u8f93\u5165\uff1a\n["a"]\n\n\u8f93\u51fa\uff1a\n\u8fd4\u56de1\uff0c\u8f93\u5165\u6570\u7ec4\u7684\u524d1\u4e2a\u5b57\u7b26\u5e94\u8be5\u662f\uff1a["a"]\n\n\u8bf4\u660e\uff1a\n\u6ca1\u6709\u4efb\u4f55\u5b57\u7b26\u4e32\u88ab\u66ff\u4ee3\u3002\n
      \n\n

      \u793a\u4f8b 3\uff1a

      \n\n
      \n\u8f93\u5165\uff1a\n["a","b","b","b","b","b","b","b","b","b","b","b","b"]\n\n\u8f93\u51fa\uff1a\n\u8fd4\u56de4\uff0c\u8f93\u5165\u6570\u7ec4\u7684\u524d4\u4e2a\u5b57\u7b26\u5e94\u8be5\u662f\uff1a["a","b","1","2"]\u3002\n\n\u8bf4\u660e\uff1a\n\u7531\u4e8e\u5b57\u7b26"a"\u4e0d\u91cd\u590d\uff0c\u6240\u4ee5\u4e0d\u4f1a\u88ab\u538b\u7f29\u3002"bbbbbbbbbbbb"\u88ab“b12”\u66ff\u4ee3\u3002\n\u6ce8\u610f\u6bcf\u4e2a\u6570\u5b57\u5728\u6570\u7ec4\u4e2d\u90fd\u6709\u5b83\u81ea\u5df1\u7684\u4f4d\u7f6e\u3002\n
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      1. \u6240\u6709\u5b57\u7b26\u90fd\u6709\u4e00\u4e2aASCII\u503c\u5728[35, 126]\u533a\u95f4\u5185\u3002
      2. \n\t
      3. 1 <= len(chars) <= 1000\u3002
      4. \n
      \n

      \u7ed9\u5b9a\u4e00\u7ec4\u5b57\u7b26\uff0c\u4f7f\u7528\u539f\u5730\u7b97\u6cd5\u5c06\u5176\u538b\u7f29\u3002

      \n\n

      \u538b\u7f29\u540e\u7684\u957f\u5ea6\u5fc5\u987b\u59cb\u7ec8\u5c0f\u4e8e\u6216\u7b49\u4e8e\u539f\u6570\u7ec4\u957f\u5ea6\u3002

      \n\n

      \u6570\u7ec4\u7684\u6bcf\u4e2a\u5143\u7d20\u5e94\u8be5\u662f\u957f\u5ea6\u4e3a1 \u7684\u5b57\u7b26\uff08\u4e0d\u662f int \u6574\u6570\u7c7b\u578b\uff09\u3002

      \n\n

      \u5728\u5b8c\u6210\u539f\u5730\u4fee\u6539\u8f93\u5165\u6570\u7ec4\u540e\uff0c\u8fd4\u56de\u6570\u7ec4\u7684\u65b0\u957f\u5ea6\u3002

      \n\n

       

      \n\n

      \u8fdb\u9636\uff1a
      \n\u4f60\u80fd\u5426\u4ec5\u4f7f\u7528O(1) \u7a7a\u95f4\u89e3\u51b3\u95ee\u9898\uff1f

      \n\n

       

      \n\n

      \u793a\u4f8b 1\uff1a

      \n\n
      \n\u8f93\u5165\uff1a\n["a","a","b","b","c","c","c"]\n\n\u8f93\u51fa\uff1a\n\u8fd4\u56de6\uff0c\u8f93\u5165\u6570\u7ec4\u7684\u524d6\u4e2a\u5b57\u7b26\u5e94\u8be5\u662f\uff1a["a","2","b","2","c","3"]\n\n\u8bf4\u660e\uff1a\n"aa"\u88ab"a2"\u66ff\u4ee3\u3002"bb"\u88ab"b2"\u66ff\u4ee3\u3002"ccc"\u88ab"c3"\u66ff\u4ee3\u3002\n
      \n\n

      \u793a\u4f8b 2\uff1a

      \n\n
      \n\u8f93\u5165\uff1a\n["a"]\n\n\u8f93\u51fa\uff1a\n\u8fd4\u56de1\uff0c\u8f93\u5165\u6570\u7ec4\u7684\u524d1\u4e2a\u5b57\u7b26\u5e94\u8be5\u662f\uff1a["a"]\n\n\u8bf4\u660e\uff1a\n\u6ca1\u6709\u4efb\u4f55\u5b57\u7b26\u4e32\u88ab\u66ff\u4ee3\u3002\n
      \n\n

      \u793a\u4f8b 3\uff1a

      \n\n
      \n\u8f93\u5165\uff1a\n["a","b","b","b","b","b","b","b","b","b","b","b","b"]\n\n\u8f93\u51fa\uff1a\n\u8fd4\u56de4\uff0c\u8f93\u5165\u6570\u7ec4\u7684\u524d4\u4e2a\u5b57\u7b26\u5e94\u8be5\u662f\uff1a["a","b","1","2"]\u3002\n\n\u8bf4\u660e\uff1a\n\u7531\u4e8e\u5b57\u7b26"a"\u4e0d\u91cd\u590d\uff0c\u6240\u4ee5\u4e0d\u4f1a\u88ab\u538b\u7f29\u3002"bbbbbbbbbbbb"\u88ab“b12”\u66ff\u4ee3\u3002\n\u6ce8\u610f\u6bcf\u4e2a\u6570\u5b57\u5728\u6570\u7ec4\u4e2d\u90fd\u6709\u5b83\u81ea\u5df1\u7684\u4f4d\u7f6e\u3002\n
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      1. \u6240\u6709\u5b57\u7b26\u90fd\u6709\u4e00\u4e2aASCII\u503c\u5728[35, 126]\u533a\u95f4\u5185\u3002
      2. \n\t
      3. 1 <= len(chars) <= 1000\u3002
      4. \n
      \n*/\n\n\n/**\n * @param {character[]} chars\n * @return {number}\n */\nvar compress = function(chars) {\n \n};"} {"doc_id": "63439ab02559f577ffcc668d30056b0e", "text": "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n/*eslint-disable*/\n\nfactors = function factors(number) {\n /*\n The factors function is to generate the factors of number and \n store values in factorsOfNumber variable\n */\n var factorsOfNumber = []; //holds the generated factors\n var quotient = 0; // temporary store for a factor\n\n for (var divisor = 1; divisor < number; divisor++) {\n if (number % divisor == 0) {\n quotient = number / divisor;\n factorsOfNumber.push(divisor); // add a factor to factorsOfNumber array\n factorsOfNumber.push(quotient); // add a factor to factorsOfNumber array\n } // ends if conditional\n } // ends for loop\n\n return factorsOfNumber;\n};\n\nstringProcessor = function stringProcessor(number) {\n\n var resultingFactors = factors(number);\n var isThree = false;\n var isFive = false;\n var isSeven = false;\n\n //console.log(resultingFactors);\n\n var generatedString = \"\";\n\n for (var i = 0; i < resultingFactors.length; i++) {\n if (resultingFactors[i] == 3) {\n isThree = true;\n }\n\n if (resultingFactors[i] == 5) {\n isFive = true;\n }\n\n if (resultingFactors[i] == 7) {\n isSeven = true;\n }\n } // ends for loop to set the boolean value of test variables\n\n if (isThree) {\n generatedString += \"Pling\";\n } // ends if to check the occurence of 3\n\n if (isFive) {\n generatedString += \"Plang\";\n } // ends if to check the occurence of 5\n\n if (isSeven) {\n generatedString += \"Plong\";\n } // ends if to check the occurence of 7\n\n if (generatedString == \"\") {\n return generatedString + number;\n } else {\n return generatedString;\n } // ends if conditional to check generated string\n}; // ends stringProcessor \n\nexports.default = stringProcessor;"} {"doc_id": "64510db9a57e27b8aed910a65642d4bc", "text": "/*\nJS PROGRAM TO FIND THE ROWS WITH MINIMUMM NUMBER OF 1s\n\nINPUT FORMAT :\nnumber of rows and number of column\n||THE ARRAY ||\n\n\nOUTPUT FORMAT:\nith row which has least number of 1s\nthe elements of row which has least number of 1s\n\n\nINPUT:\n5 4\n1 1 1 2\n1 1 5 2\n0 0 1 1\n1 1 2 2\n1 0 1 1\n\nOUTPUT:\n2 row:\n1 1 5 2\n------------\n3 row:\n0 0 1 1\n------------\n4 row:\n1 1 2 2\n------------\n\n\nTime complexity : O(N^2);\nSpace complexity : O(N^2);\n\n\n\n*/\n\nfindMinNumberOfOnes = (numOfRows, numOfCols, array) => {\n\n let row = new Array(numOfRows).fill(0); // an array for number of 1s in each row\n\n for (let i = 0; i < numOfRows; i++) {\n for (let j = 0; j < numOfCols; j++) {\n if (array[i][j] == 1) {\n row[i]++;\n }\n }\n }\n\n let min_1s_in_row = row[0];\n\n for (let i = 0; i < numOfRows; i++) {\n min_1s_in_row = Math.min(min_1s_in_row, row[i]);\n } // variable min_is_in_row contains the least number of 1s present in a row\n\n for (let i = 0; i < numOfRows; i++) {\n\n if (min_1s_in_row == row[i]) { // print the number and elements of row which has least number of 1s\n console.log(i + 1 + \" row:\");\n for (let j = 0; j < numOfCols; j++) {\n console.log(array[i][j] + \" \");\n }\n console.log(\"------\");\n }\n }\n\n};\n\n// SAMPLE INPUTS\n\nconst rows = 5;\nconst cols = 4;\nconst array = [[1, 1, 1, 2], [1, 1, 5, 2], [0, 0, 1, 1], [1, 1, 2, 2], [1, 0, 1, 1]];\n\nfindMinNumberOfOnes(rows, cols, array);\n\n\n"} {"doc_id": "6479e7de8a09909c1609c6e4679b1896", "text": "// JS PROTOTYPE INHERITANCE CHEAT SHEET v1.02 (abstract class missing...)\n\n// - ANIMAL -------------------------------------------------\nvar animal = (function () {\n // HQ - tip ---> hidden functions on the top of the module\n function isInteger(value) {\n return value === parseInt(value, 10);\n }\n\n function throwIntegerError(type) {\n var message = type + ' must be an integer value';\n\n throw Error(message);\n }\n\n function checkName(nameToCheck) {\n if (!nameToCheck) {\n throw Error('Name missing!');\n }\n\n if (!nameToCheck.length || nameToCheck.length < 3) {\n throw Error('Name must be at least 3 symbols!');\n }\n }\n\n function checkAge(age) {\n if (!age) {\n throw Error('Age missing!');\n }\n\n if (!isInteger(+age)) {\n throwIntegerError('Age');\n }\n\n if (!age < 0 || age > 150) {\n throw Error('Invalid age - mus be between 0 ans 150');\n }\n }\n\n // function declared outside defineProperty and returned as value of the property!!\n function animalTestFunction(a, b) {\n return (a * b) + ' ' + this.name + ' - test func + this.name';\n }\n\n // -- Maybe more HQ way\n var animal = {};\n\n Object.defineProperty(animal, 'init', {\n value: function (name, age) {\n this.name = name;\n this.age = age;\n return this; // very important!!!\n },\n enumerable: true\n });\n\n // Not sure which is better defineProperty or defineProperties so the rest of them at once for the purpose the cheat sheet\n\n Object.defineProperties(animal, {\n 'name': {\n get: function () {\n return this._name;\n },\n set: function (value) {\n checkName(value);\n\n this._name = value;\n }\n },\n 'age': {\n get: function () {\n return this._age;\n },\n set: function (value) {\n checkAge(value);\n\n this._age = value;\n }\n },\n toString: {\n value: function () {\n return 'Animal I am, hmmm. ' + this.name + 'my name is.. ' + this.age + ' year I\\'ve being...'\n }\n },\n onlyParentProp: {\n value: 'https://www.youtube.com/watch?v=8tb3RLqY9Xo',\n enumerable: true\n },\n animalTestFunc: {\n value: animalTestFunction,\n writable: false,\n enumerable: true// declared somewhere above - DO NOT use () when reference the function that way !!!!\n }\n });\n\n// ---> Maybe not HQ way to make the object\n\n //var animal = {\n // init: function (name, age) {\n // this.name = name;\n // this.age = age;\n // return this; // very important!!!\n // },\n // get name() {\n // return this._name;\n // },\n // set name(value) {\n // checkName(value);\n //\n // this._name = value;\n // },\n // get age() {\n // return this._age;\n // },\n // set age(value) {\n // checkAge(value);\n //\n // this._age = value;\n // },\n // toString: function () {\n // return 'Animal I am, hmmm. ' + this.name + 'my name is.. ' + this.age + ' year I\\'ve being...'\n // }\n //};\n\n return animal; // DO NOT FORGET TO RETURN THE OBJECT!!!!!\n}());\n\n// - MAMMAL -------------------------------------------------\nvar mammal = (function (parent) {\n // HQ - tip ---> hidden functions on the top of the module\n function checkToys(toy) {\n if (!toy || toy.length < 3) {\n throw new Error('I want my toys!!!')\n }\n }\n\n// ---> Ste child __proto__ to be the parent __proto__\n var mammal = Object.create(parent);\n\n// ---> 'HQ' way to declare properties // parent can be assigned parent = {} ... Object.defineProperty/ies(parent, {....})\n Object.defineProperty(mammal, 'init', {\n value: function (name, age, legs, eyes) {\n parent.init.call(this, name, age);\n this.legs = legs;\n this.eyes = eyes;\n this._toys = [];\n\n return this; // very important!!!\n },\n enumerable: true\n });\n\n Object.defineProperty(mammal, 'toString', {\n value: function () {\n var baseResult = parent.toString.call(this);\n\n return baseResult + ' My legs, hmmmm ... ' + this.legs + ' they are. I look at you with ' + this.eyes + ' eyes, hmmm ...'\n },\n enumerable: true\n });\n\n Object.defineProperties(mammal, {\n mammalPropOnly: {\n value: 'Try this - https://www.youtube.com/watch?v=dRcHTdWY5lU',\n enumerable: true\n },\n calcSumOfTwoIntegers: {\n value: function (a, b) {\n return (a + b) + ' ' + this.name + ' - calc sum + this.name';\n },\n enumerable: true\n }\n });\n\n Object.defineProperties(mammal, {\n addToy: {\n value: function (toy) {\n checkToys(toy);\n\n this._toys.push(toy);\n return this; // return this if you want to chain!!!\n },\n enumerable: true\n },\n getAllToys: {\n value: function () {\n return this._toys.slice(0); // It is a good to return slice of the private array!!!!\n },\n enumerable: true\n }\n });\n\n// ---> Easier to write way to declare way .. (same as above) // BUT there are some bugs SO USE defineProperty/ies !!!!!\n // ---> NOT working when override toString for example, if in the parent is set with defineProperty !!!!\n\n //mammal.init = function(name, age, legs, eyes){\n // parent.init.call(this, name, age);\n // this.legs = legs;\n // this.eyes = eyes;\n //\n // return this; // very important!!!\n //};\n //\n //mammal.toString = function () {\n // var baseResult = parent.toString.call(this);\n //\n // return baseResult + ' My legs, hmmmm ... ' + this.legs + ' they are. I look at you with ' + this.eyes + ' eyes, hmmm ...'\n //};\n\n return mammal; // DO NOT FORGET TO RETURN THE OBJECT!!!!!\n}(animal));\n\n// ---> Adding extra property after prototype initialisation and it works :)\n// ---> value: must be a function with return if you want to use this.something in the property/function!!!\nObject.defineProperty(animal, 'say', {\n value: function () {\n return 'Say YO mf ' + this.name\n }\n }\n);\n\n//var someAnimal = Object.create(animal).init('Pesho', 18);\nvar someAnimal = Object.create(mammal).init('Pesho', 18, 4, 2);\nvar someAnotherAnimal = Object.create(mammal).init('Johnny', 16, 3, 2).addToy('Danbo').addToy('Homer').addToy('Bart');\nconsole.log(Object.getPrototypeOf(mammal));\nconsole.log(Object.getPrototypeOf(someAnimal));\nconsole.log(someAnimal); // in the console shows only properties that are set as enumerable!!\nconsole.log(someAnimal.toString());\nconsole.log(someAnimal.say());\nconsole.log(someAnimal.hasOwnProperty('_name'));\nconsole.log(someAnimal.onlyParentProp);\nconsole.log(someAnimal.mammalPropOnly);\nconsole.log(someAnimal.calcSumOfTwoIntegers(1, 2));\nconsole.log(mammal.calcSumOfTwoIntegers.call({name: ' Gosho is calling'}, 1, 2));\nconsole.log(mammal.calcSumOfTwoIntegers.apply({name: ' Hohn is applying'}, [3, 5]));\nconsole.log(someAnotherAnimal.animalTestFunc(2, 4));\nconsole.log(mammal.calcSumOfTwoIntegers.call({name: ' Gosho is testing'}, 1, 2));\nconsole.log(mammal.calcSumOfTwoIntegers.apply({name: ' Hohn is testing'}, [3, 5]));\nconsole.log(someAnimal.animalTestFunc === someAnotherAnimal.animalTestFunc); // return TRUE !! nice - use one instance of the function :)\nconsole.log(someAnimal.toString === someAnotherAnimal.toString); // return TRUE !! nice use one instance of the function :)\nconsole.log(someAnotherAnimal.getAllToys());\n\nfor (var prop in someAnimal) {\n console.log(prop)\n}\n"} {"doc_id": "648447a9bed52378e8cddc7355847fd5", "text": "// Assignment Code\nvar generateBtn = document.querySelector(\"#generate\");\nvar alphabetLow = 'abcdefghijklmnopqrstuvwxyz';\nvar alphabetUp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\nvar Numbers = \"0123456789\";\nvar specChar = [' ','!','\"','#','$','%','&','\\'','(',')','*','+','\\,','<','>','?','@','[',']','\\\\','^','`','_','{','}','|','~','.','-','/'];\nvar NumChar = Numbers.split(\"\");\nvar upperCase = alphabetUp.split('');\nvar lowerCase = alphabetLow.split('');\n\n\n// Write password to the #password input\nfunction writePassword() {\nvar password = generatePassword();\nvar passwordText = document.querySelector(\"#password\");\n\npasswordText.value = password;\n\n}\n\n//Chooses Random Character from Array\nfunction randomCharFromArray(arr){\n return arr[Math.floor(Math.random()* Math.floor(arr.length))]\n}\n\n// Creates Password\nfunction generatePassword(){\n \n // Determines Password Length\n var PassLength = prompt(\"How many characters would you like in your password:\");\n\n //Registers if Numbers were Added\n if (PassLength >= 8 && PassLength <= 128){\n \n // Prompts User for Desired \n var AlphaLower = confirm(\"Would you like to include Lowercase letters?\");\n var AlphaUpper = confirm(\"Would you like to include Uppercase letters?\");\n var Special = confirm(\"Would you like to include special characters?\");\n var Numerals = confirm(\"Would you like to include numerals?\")\n var CharArray = [specChar,NumChar,upperCase,lowerCase]\n var string = \"\"\n\n // If Lower Case Characters are Requested\n if (AlphaLower === false){\n CharArray.splice(3,1)\n }\n\n //If Upper Case Characters are Requested\n if (AlphaUpper === false){\n CharArray.splice(2,1) \n }\n\n //If Numerals are Requested\n if (Numerals === false){\n CharArray.splice(1,1) \n }\n\n //If Special Letters are Requested\n if (Special === false){\n CharArray.splice(0,1) \n }\n\n // Run through loop to create Password\n for (var i = 0; i < PassLength; i++){\n string = string + randomCharFromArray(randomCharFromArray(CharArray))\n }\n \n //Outcome for Generate Password Function\n return string\n \n } else {\n alert(\"Invalid Number. \\nMust be a number between 8 and 128 \\nPlease try again and enter a valid number\")\n return \"\"\n }\n}\n\n// Add event listener to generate button\ngenerateBtn.addEventListener(\"click\", writePassword);\n"} {"doc_id": "65524fe24cc21a5982efeed70124764d", "text": "/*\n

      S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

      \n\n

      S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

      \n\n

      Return any permutation of T (as a string) that satisfies this property.

      \n\n
      \nExample :\nInput: \nS = "cba"\nT = "abcd"\nOutput: "cbad"\nExplanation: \n"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". \nSince "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.\n
      \n\n

       

      \n\n

      Note:

      \n\n
        \n\t
      • S has length at most 26, and no character is repeated in S.
      • \n\t
      • T has length at most 200.
      • \n\t
      • S and T consist of lowercase letters only.
      • \n
      \n

      \u5b57\u7b26\u4e32S\u548c T \u53ea\u5305\u542b\u5c0f\u5199\u5b57\u7b26\u3002\u5728S\u4e2d\uff0c\u6240\u6709\u5b57\u7b26\u53ea\u4f1a\u51fa\u73b0\u4e00\u6b21\u3002

      \n\n

      S \u5df2\u7ecf\u6839\u636e\u67d0\u79cd\u89c4\u5219\u8fdb\u884c\u4e86\u6392\u5e8f\u3002\u6211\u4eec\u8981\u6839\u636eS\u4e2d\u7684\u5b57\u7b26\u987a\u5e8f\u5bf9T\u8fdb\u884c\u6392\u5e8f\u3002\u66f4\u5177\u4f53\u5730\u8bf4\uff0c\u5982\u679cS\u4e2dx\u5728y\u4e4b\u524d\u51fa\u73b0\uff0c\u90a3\u4e48\u8fd4\u56de\u7684\u5b57\u7b26\u4e32\u4e2dx\u4e5f\u5e94\u51fa\u73b0\u5728y\u4e4b\u524d\u3002

      \n\n

      \u8fd4\u56de\u4efb\u610f\u4e00\u79cd\u7b26\u5408\u6761\u4ef6\u7684\u5b57\u7b26\u4e32T\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165:\nS = "cba"\nT = "abcd"\n\u8f93\u51fa: "cbad"\n\u89e3\u91ca: \nS\u4e2d\u51fa\u73b0\u4e86\u5b57\u7b26 "a", "b", "c", \u6240\u4ee5 "a", "b", "c" \u7684\u987a\u5e8f\u5e94\u8be5\u662f "c", "b", "a". \n\u7531\u4e8e "d" \u6ca1\u6709\u5728S\u4e2d\u51fa\u73b0, \u5b83\u53ef\u4ee5\u653e\u5728T\u7684\u4efb\u610f\u4f4d\u7f6e. "dcba", "cdba", "cbda" \u90fd\u662f\u5408\u6cd5\u7684\u8f93\u51fa\u3002\n
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • S\u7684\u6700\u5927\u957f\u5ea6\u4e3a26\uff0c\u5176\u4e2d\u6ca1\u6709\u91cd\u590d\u7684\u5b57\u7b26\u3002
      • \n\t
      • T\u7684\u6700\u5927\u957f\u5ea6\u4e3a200\u3002
      • \n\t
      • S\u548cT\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u7b26\u3002
      • \n
      \n

      \u5b57\u7b26\u4e32S\u548c T \u53ea\u5305\u542b\u5c0f\u5199\u5b57\u7b26\u3002\u5728S\u4e2d\uff0c\u6240\u6709\u5b57\u7b26\u53ea\u4f1a\u51fa\u73b0\u4e00\u6b21\u3002

      \n\n

      S \u5df2\u7ecf\u6839\u636e\u67d0\u79cd\u89c4\u5219\u8fdb\u884c\u4e86\u6392\u5e8f\u3002\u6211\u4eec\u8981\u6839\u636eS\u4e2d\u7684\u5b57\u7b26\u987a\u5e8f\u5bf9T\u8fdb\u884c\u6392\u5e8f\u3002\u66f4\u5177\u4f53\u5730\u8bf4\uff0c\u5982\u679cS\u4e2dx\u5728y\u4e4b\u524d\u51fa\u73b0\uff0c\u90a3\u4e48\u8fd4\u56de\u7684\u5b57\u7b26\u4e32\u4e2dx\u4e5f\u5e94\u51fa\u73b0\u5728y\u4e4b\u524d\u3002

      \n\n

      \u8fd4\u56de\u4efb\u610f\u4e00\u79cd\u7b26\u5408\u6761\u4ef6\u7684\u5b57\u7b26\u4e32T\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165:\nS = "cba"\nT = "abcd"\n\u8f93\u51fa: "cbad"\n\u89e3\u91ca: \nS\u4e2d\u51fa\u73b0\u4e86\u5b57\u7b26 "a", "b", "c", \u6240\u4ee5 "a", "b", "c" \u7684\u987a\u5e8f\u5e94\u8be5\u662f "c", "b", "a". \n\u7531\u4e8e "d" \u6ca1\u6709\u5728S\u4e2d\u51fa\u73b0, \u5b83\u53ef\u4ee5\u653e\u5728T\u7684\u4efb\u610f\u4f4d\u7f6e. "dcba", "cdba", "cbda" \u90fd\u662f\u5408\u6cd5\u7684\u8f93\u51fa\u3002\n
      \n\n

      \u6ce8\u610f:

      \n\n
        \n\t
      • S\u7684\u6700\u5927\u957f\u5ea6\u4e3a26\uff0c\u5176\u4e2d\u6ca1\u6709\u91cd\u590d\u7684\u5b57\u7b26\u3002
      • \n\t
      • T\u7684\u6700\u5927\u957f\u5ea6\u4e3a200\u3002
      • \n\t
      • S\u548cT\u53ea\u5305\u542b\u5c0f\u5199\u5b57\u7b26\u3002
      • \n
      \n*/\n\n\n/**\n * @param {string} S\n * @param {string} T\n * @return {string}\n */\nvar customSortString = function(S, T) {\n \n};"} {"doc_id": "66a8c084886c89b6927b652ef2e2617d", "text": "/*\nInternational Morse Code defines a standard encoding where each letter is\nmapped to a series of dots and dashes, as follows: \"a\" maps to \".-\", \"b\" maps to \"-...\", \"c\" maps to \"-.-.\", and so on.\n\nFor convenience, the full table for the 26 letters of the English alphabet\nis given below:\n\n[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\n\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\n\"-.--\",\"--..\"]\nNow, given a list of words, each word can be written as a concatenation of\nthe Morse code of each letter. For example, \"cba\" can be written as\n\"-.-..--...\", (which is the concatenation \"-.-.\" + \"-...\" + \".-\").\nWe'll call such a concatenation, the transformation of a word.\n\nReturn the number of different transformations among all words we have.\n\nExample:\nInput: words = [\"gin\", \"zen\", \"gig\", \"msg\"]\nOutput: 2\nExplanation:\nThe transformation of each word is:\n\"gin\" -> \"--...-.\"\n\"zen\" -> \"--...-.\"\n\"gig\" -> \"--...--.\"\n\"msg\" -> \"--...--.\"\n\nThere are 2 different transformations, \"--...-.\" and \"--...--.\".\nNote:\n\nThe length of words will be at most 100.\nEach words[i] will have length in range [1, 12].\nwords[i] will only consist of lowercase letters.\n*/\n\nconst morseAlphabet = [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\n \".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\n \"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"];\n\nconst englishAlphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');\n\nclass Dictionary {\n constructor(keysAlphabet, valuesAlphabet) {\n if (keysAlphabet.length !== valuesAlphabet.length)\n throw new RangeError('The number of keys and values do not match.');\n\n for (let i = 0, l = valuesAlphabet.length; i < l; i++) {\n this[keysAlphabet[i]] = valuesAlphabet[i];\n }\n\n console.log('Dictionary is created');\n console.log(this);\n }\n}\n\nconst englishMorseDictionary = new Dictionary(englishAlphabet, morseAlphabet);\n\nfunction uniqueMorseRepresentations(words) {\n words = new Set(words);\n let uniqueRepresentations = new Set();\n\n for (let word of words) {\n let morseWord = '';\n\n for (let char of word) {\n morseWord += englishMorseDictionary[char];\n }\n\n uniqueRepresentations.add(morseWord);\n }\n\n return uniqueRepresentations.size;\n}\n"} {"doc_id": "676b71afb496ba48b6dc338c9efd64c2", "text": "/******************************************************************************\n** Directions:\n** For each question, replace the blank\n** with a word from the word bank.\n**\n\n -= WORD BANK =-\n | ================= |\n | * property |\n | * method |\n | * this |\n | * scope |\n | * array |\n | * object |\n | ================= |\n\n===============================================\n Question #1:\n This composite data type stores elements in an ordered list\n-----------------------------------------------\n Answer #1: array\n===============================================\n\n===============================================\n Question #2:\n This composite data type stores a data according to a 'key' value\n-----------------------------------------------\n Answer #2: object\n===============================================\n\n===============================================\n Question #3:\n The area of a program where a variable name is considered valid.\n-----------------------------------------------\n Answer #3: scope\n===============================================\n\n===============================================\n Question #4:\n String.prototype.length is known as [blank].\n-----------------------------------------------\n Answer #4: property\n===============================================\n\n===============================================\n Question #5:\n An object may refer to its own properties and methods with this keyword.\n-----------------------------------------------\n Answer #5: this\n===============================================\n\n===============================================\n Question #6:\n A function within an object is called a [blank] .\n-----------------------------------------------\n Answer #6: method\n===============================================\n*/\n\n/******************************************************************************\n** Write a function #myIndexOf(array, ele) that takes an array and an element.\n** Return the index of the element in the array, or -1 if it doesn't exist. Assume\n** the `ele` will be a primitive data type (no arrays or objects). DO NOT USE\n** Array.prototype.indexOf\n** Example\n** myIndexOf([1,2,3,4,5], 5) => 4\n** myIndexOf([\"a\", \"b\", \"c\"], \"a\") => 0\n** myIndexOf([\"a\", \"b\", \"c\"], \"d\") => -1\n*/\n\nfunction myIndexOf(array, ele) {\n // your code here...\n for (var i = 0; i < array.length; i++) {\n if (array[i] === ele) {\n return i;\n }\n }\n\n return -1;\n}\n\n/******************************************************************************\n** Write a function `minMaxProduct(array)` that returns the difference between the\n** largest value and the smallest value in the array. Assume `array` is an array of\n** numbers. Assume an array of at least two numbers.\n** Example\n** minMaxProduct([1,2,3,4,5]) => 5\n** minMaxProduct([5,4,3,2,1]) => 5\n** minMaxProduct([4,2,5,1,-5]) => -25\n*/\nfunction minMaxProduct(array) {\n // your code here...\n var min = array[0];\n var max = array[0];\n\n for (var i = 0; i < array.length; i++) {\n var num = array[i];\n\n if (min > num) {\n min = num;\n } else if (max < num) {\n max = num;\n }\n }\n\n return max * min;\n}\n\n/******************************************************************************\n** Write a function `leastCommonMultiple(num1, num2)` that returns the\n** lowest number which is a multiple of both inputs.\n** Example\n** lcm(2, 3) => 6\n** lcm(6, 10) => 30\n** lcm(24, 26) => 312\n*/\n\nfunction leastCommonMultiple(num1, num2) {\n // your code here...\n var i = num1;\n\n while(true) {\n if (i % num2 === 0) {\n return i;\n }\n i += num1;\n }\n}\n\n/******************************************************************************\n** Write a function `hipsterfy(sentence)` that takes takes a string containing\n** several words as input. Remove the last vowel from each word. 'y' is not a vowel.\n** Example\n** hipsterfy(\"proper\") => \"propr\"\n** hipsterfy(\"proper tonic panther\") => \"propr tonc panthr\"\n** hipsterfy(\"towel flicker banana\") => \"towl flickr banan\"\n** hipsterfy(\"runner anaconda\") => \"runnr anacond\"\n** hipsterfy(\"turtle cheeseburger fries\") => \"turtl cheeseburgr fris\"\n*/\n\nfunction hipsterfyWord(word){\n var vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"];\n\n for (var i = word.length - 1; i >= 0; i -= 1) {\n if (vowels.indexOf(word[i]) !== -1) {\n var hipsterWord = word.slice(0, i) + word.slice(i + 1);\n return hipsterWord;\n }\n }\n\n return word;\n}\n\nfunction hipsterfy(sentence) {\n // your code here...\n var hipsterified = [];\n var splitSentence = sentence.split(\" \");\n\n for (var i = 0; i < splitSentence.length; i += 1) {\n var word = splitSentence[i];\n hipsterified.push(hipsterfyWord(word));\n }\n\n return hipsterified.join(\" \");\n}\n\n\n/******************************************************************************\n** Write a function #magicCipher(sentence, cipher) that takes in an string(sentence)\n** and an object(cipher). Return a string where every character is replaced with its\n** cooresponding value in the cipher. If the character doesn't exist in the\n** cipher, use the character.\n** Example\n** magicCipher(\"add me on facebook\" , { a : \"c\", d : \"q\"}) => \"cqq me on fccebook\"\n** magicCipher(\"where are you?\" , { v : \"l\", '?' : \"!\"}) => \"where are you!\"\n** magicCipher(\"twmce\" , { m : \"n\", t : \"d\", w : \"a\"}) => \"dance\"\n*/\n\nfunction magicCipher(sentence, cipher) {\n // your code here...\n var decoded = \"\";\n\n for (var i = 0; i < sentence.length; i++) {\n var char = sentence[i];\n var decodedChar = cipher[char] || char;\n decoded += decodedChar;\n }\n\n return decoded;\n}\n\n/**************DO NOT MODIFY ANYTHING UNDER THIS LINE*************************/\nmodule.exports = {\n leastCommonMultiple : leastCommonMultiple,\n myIndexOf : myIndexOf,\n magicCipher : magicCipher,\n minMaxProduct : minMaxProduct,\n hipsterfy : hipsterfy\n};\n"} {"doc_id": "680be7fc0bffd1651e57377886793208", "text": "// 6. modify basic JS object, with \"this\" keyword\nlet person = {\n firstName: \"Jane\",\n lastName: \"Doe\",\n age: 45,\n streetAddress: \"WindingRiver Drive\",\n city: \"Troy\",\n State: \"Utah\",\n zipCode: \"48881\",\n fullName: function() {\n return this.firstName + \" \" + this.lastName\n },\n fullAddress: function() {\n return this.streetAddress+\" \"+ this.city+\" \"+ this.State+\" \"+this.zipCode\n }\n}\n \n\ndocument.getElementById(\"1A\").innerHTML = person.fullName();\ndocument.getElementById(\"1B\").innerHTML = person.fullAddress();\n\n// Instructions\n// modify person object, above, as follows\n// add properties, streetAddress, city, state, zipCode\n// add method, fullAddress(), which prints full address on a single line.\n// Display output of fullAddress() in
      \nperson.streetAddress = \"123 Main Street\";\n\n// ==================\n\n// 7. create basic DOM object\n/*let div2a = document.getElementById(\"2A\");\nlet table2a = createTable(\"table2a\");\ndiv2a.appendChild(table2a);\ntable2a.setAttribute(\"style\", \"border:1px solid black;\")\ntable2a.setAttribute(\"width\", \"100%\")\nappendTableRow3(table2a,\"1\",\"2\",\"3\");\nappendTableRow3(table2a,\"4\",\"5\",\"6\");\nappendTableRow3(table2a,\"7\",\"8\",\"9\");\n*/\nlet div2b = document.getElementById(\"2B\");\nlet table2b = createTable(\"table2b\");\ndiv2b.appendChild(table2b);\n//table2b.setAttribute(\"style\", \"border:1px solid black;\",\"class\",\"table:table-striped\")\ntable2b.setAttribute(\"style\",\"border: 1px solid black;\")\ntable2b.setAttribute(\"width\", \"100%\")\nappendTableRow5(table2b,\"1\",\"2\",\"3\",\"4\",\"5\");\nappendTableRow5(table2b,\"6\",\"7\",\"8\",\"9\",\"10\");\nappendTableRow5(table2b,\"11\",\"12\",\"13\",\"14\",\"15\");\nappendTableRow5(table2b,\"16\",\"17\",\"18\",\"19\",\"20\");\nappendTableRow5(table2b,\"21\",\"22\",\"23\",\"24\",\"25\");\n\n// Instructions\n// add a new function, appendTableRow5(), which adds 5-column rows instead of 3-column rows\n// create a 5-row by 5-column table showing the numbers, 1 through 25\n// put borders around the cells, too, not just around the edge of the table\n// Display output in
      \n\n// ==================\n\n// 8. create \"totals\" row and column in a table\n\n// Instructions\n// don't change table3A. it's just a template.\n// Use table03A to create table3B. Create new functions as in item 2, above. \n// in table3B, add a column, \"Price * Qty\", and use JS to compute the correct values to put in the column\n// add to table03B a \"totals\" row which gives the \"grand total\" of all numbers in the \"Price * Qty\" column\nlet div3B = document.getElementById(\"3B\");\nlet table03B = createTable(\"table03B\");\ndiv3B.appendChild(table03B);\ntable03B.setAttribute(\"style\",\"border: 1px solid black;\")\ntable03B.setAttribute(\"width\", \"100%\")\nappendTableRow3(table03B,\"Item\", \"Price\", \"Qty\",\"Price * Qty\");\n// table03B.setAttribute(\"style\",\"font_weight:bold\");\n//appendTableRow3.setAttribute(\"style\",\"font_weight:bold\");\nappendTableRow3(table03B,\"Thingamabob\",\"1.00\",\"1\",\"1\");\nappendTableRow3(table03B,\"Whachamacallit\",\"2.00\",\"2\",\"4\");\nappendTableRow3(table03B,\"Doohickey\",\"3.00\",\"3\",\"9\");\nappendTableRow3(table03B,\"Grand Total\",\"6.00\",\"6\",\"14\");\n\n\n// 9. Refactor a non-object-oriented form\n\n\n // initialize error div id array\n let divs = new Array();\n divs[0] = \"errFirst\";\n divs[1] = \"errLast\";\n divs[2] = \"errEmail\";\n divs[3] = \"errUid\";\n divs[4] = \"errPassword\";\n divs[5] = \"errConfirm\";\n\n // function: validate() ---------------------------------------------\n function validate(x) {\n // initialize input array\n var inputs = new Array();\n \n inputs[0] = document.getElementById('first').value;\n inputs[1] = document.getElementById('last').value;\n inputs[2] = document.getElementById('email').value;\n inputs[3] = document.getElementById('uid').value;\n inputs[4] = document.getElementById('password').value;\n inputs[5] = document.getElementById('confirm').value;\n // initialize error array\n var errors = new Array();\n \n for(let i = 0; i < 6; i++){\n errors[i] = \"\";\n }\n \n switch(x) {\n case 0:\n errors[0] = \"Please enter your first name!\";\n break;\n \n case 1:\n errors[1] = \"Please enter your last name!\";\n break;\n \n case 2:\n errors[2] = \"Please enter your email!\";\n break;\n \n case 3:\n errors[3] = \"Please enter your user id!\";\n break;\n \n case 4:\n errors[4] = \"Please enter your password!\";\n break;\n \n case 5:\n errors[5] = \"Please confirm your password!\";\n break;\n \n }\n //errors[0] = \"Please enter your first name!\";\n //errors[1] = \"Please enter your last name!\";\n //errors[2] = \"Please enter your email!\";\n //errors[3] = \"Please enter your user id!\";\n //errors[4] = \"Please enter your password!\";\n //errors[5] = \"Please confirm your password!\";\n // update error array with error message\n for (i in inputs) {\n var errMessage = errors[i];\n var div = divs[i];\n if (inputs[i] == \"\")\n document.getElementById(div).innerHTML = errMessage;\n else if (i == 2) {\n var atpos = inputs[i].indexOf(\"@\");\n var dotpos = inputs[i].lastIndexOf(\".\");\n if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= inputs[i].length)\n document.getElementById('errEmail').innerHTML \n = \"Enter a valid email address!\";\n else\n document.getElementById(div).innerHTML = \"OK!\";\n } else if (i == 5) {\n var first = document.getElementById('password').value;\n var second = document.getElementById('confirm').value;\n if (second != first)\n document.getElementById('errConfirm').innerHTML \n = \"Your passwords don't match!\";\n else\n document.getElementById(div).innerHTML = \"OK!\";\n } else\n document.getElementById(div).innerHTML = \"OK!\";\n }\n }\n\n // function: finalValidate() ------------------------------------\n \n\nfunction finalValidate() {\n let count = 0;\n for (i = 0; i < 6; i++) {\n var div = divs[i];\n if (document.getElementById(div).innerHTML == \"OK!\") {\n count = count + 1;\n }else{\n //errMessage=0;\n // document.getElementById(div).innerHTML = errMessage;\n \n }\n \n }\n if (count == 6)\n document.getElementById(\"errFinal\").innerHTML \n = \"All the data you entered is correct!!!\";\n }\n\n\n// 10. Create a more object-oriented form\n\n\n// Step 1. Create/append the DOM object \nvar f = document.createElement(\"form\");\n\nvar i = document.createElement(\"input\"); //input element, text\ni.setAttribute('type',\"text\");\ni.setAttribute('name',\"first\");\n\nvar t = document.createElement(\"input\"); //input element, text\nt.setAttribute('type',\"text\");\nt.setAttribute('name',\"last\");\n\nvar m = document.createElement(\"input\"); //input element, text\nm.setAttribute('type',\"text\");\nm.setAttribute('name',\"email\");\n\nvar k = document.createElement(\"input\"); //input element, text\nk.setAttribute('type',\"text\");\nk.setAttribute('name',\"uid\");\n\nvar l = document.createElement(\"input\"); //input element, text\nl.setAttribute('type',\"text\");\nl.setAttribute('name',\"password\");\n\nvar n = document.createElement(\"input\"); //input element, text\nn.setAttribute('type',\"text\");\nn.setAttribute('name',\"confirm\");\n\nvar s = document.createElement(\"input\"); //input element, Submit button\ns.setAttribute('type',\"submit\");\ns.setAttribute('value',\"Validate\");\n\nf.appendChild(i);\nf.appendChild(t);\nf.appendChild(m);\nf.appendChild(k);\nf.appendChild(l);\nf.appendChild(n);\nf.appendChild(s);\n\n\n//and some more input elements here\n//and dont forget to add a submit button\n\ndocument.getElementsByTagName('body')[0].appendChild(f);\n\n// Step 2. Create an JS object array containing form info \nlet formArray = [\n {label: \"First name:\", inputType: \"text\", id: \"first\", \n onkeyup: \"validate();\", errorId: \"errFirst\"}, \n {label: \"Last name:\", inputType: \"text\", id: \"last\", \n onkeyup: \"validate();\", errorId: \"errLast\" }, \n {label: \"Email:\", inputType: \"text\", id: \"email\", \n onkeyup: \"validate();\", errorId: \"errEmail\"}, \n {label: \"User id:\", inputType: \"text\", id: \"uid\", \n onkeyup: \"validate();\", errorId: \"errUid\" }, \n {label: \"Password:\", inputType: \"password\", id: \"password\", \n onkeyup: \"validate();\", errorId: \"errPassword\"}, \n {label: \"Confirm Password:\", inputType: \"password\", id: \"confirm\", \n onkeyup: \"validate();\", errorId: \"errConfirm\"}\n];\n\n// Step 3. loop through the JS object array to populate the form\n\n// your code here\n\n\n// append to tableobj a 3-column table row \nfunction appendTableRow3(tableobj, col1, col2, col3, col4){\n let td1 = document.createElement(\"td\");\n let td2 = document.createElement(\"td\");\n let td3 = document.createElement(\"td\");\n let td4 = document.createElement(\"td\");\n let td5 = document.createElement(\"td\");\n \n td1.setAttribute(\"style\",\"border: 1px solid black;\")\n td2.setAttribute(\"style\",\"border: 1px solid black;\")\n td3.setAttribute(\"style\",\"border: 1px solid black;\")\n td4.setAttribute(\"style\",\"border: 1px solid black;\")\n\n // insert content into columns\n td1.innerHTML = col1;\n td2.innerHTML = col2;\n td3.innerHTML = col3;\n td4.innerHTML = col4;\n \n // create table row DOM object\n let tr = document.createElement(\"tr\");\n // append table divisions (columns) to table row\n tr.appendChild(td1);\n tr.appendChild(td2);\n tr.appendChild(td3);\n tr.appendChild(td4);\n tr.appendChild(td5);\n // append the row to the tbody element in the table\n tableobj.children[0].appendChild(tr);\n}\n\nfunction appendTableRow5 (tableobj, col1, col2, col3, col4, col5) {\n // create column (table division) DOM objects\n let td1 = document.createElement(\"td\");\n let td2 = document.createElement(\"td\");\n let td3 = document.createElement(\"td\");\n let td4 = document.createElement(\"td\");\n let td5 = document.createElement(\"td\");\n td1.setAttribute(\"style\",\"border: 1px solid black;\")\n td2.setAttribute(\"style\",\"border: 1px solid black;\")\n td3.setAttribute(\"style\",\"border: 1px solid black;\")\n td4.setAttribute(\"style\",\"border: 1px solid black;\")\n td5.setAttribute(\"style\",\"border: 1px solid black;\")\n // insert content into columns\n td1.innerHTML = col1;\n td2.innerHTML = col2;\n td3.innerHTML = col3;\n td4.innerHTML = col4;\n td5.innerHTML = col5;\n // create table row DOM object\n let tr = document.createElement(\"tr\");\n // append table divisions (columns) to table row\n tr.appendChild(td1);\n tr.appendChild(td2);\n tr.appendChild(td3);\n tr.appendChild(td4);\n tr.appendChild(td5);\n // append the row to the tbody element in the table\n tableobj.children[0].appendChild(tr);\n}\n\n// return a DOM object containing an empty table (with tbody element)\nfunction createTable(id) {\n let table = document.createElement(\"table\");\n table.setAttribute(\"id\", id);\n let tbody = document.createElement(\"tbody\");\n table.appendChild(tbody);\n return table;\n} \n"} {"doc_id": "6821ca35986f740746389bca3d02b690", "text": "/*\n

      \nSpecial binary strings are binary strings with the following two properties:\n

      \n

    11. The number of 0's is equal to the number of 1's.
    12. \n
    13. Every prefix of the binary string has at least as many 1's as 0's.
    14. \n

      \nGiven a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)\n

      \nAt the end of any number of moves, what is the lexicographically largest resulting string possible?\n

      \n\n

      Example 1:
      \n

      \nInput: S = \"11011000\"\nOutput: \"11100100\"\nExplanation:\nThe strings \"10\" [occuring at S[1]] and \"1100\" [at S[3]] are swapped.\nThis is the lexicographically largest string possible after some number of swaps.\n
      \n

      \n\n

      Note:

        \n
      1. S has length at most 50.
      2. \n
      3. S is guaranteed to be a special binary string as defined above.
      4. \n

      \u7279\u6b8a\u7684\u4e8c\u8fdb\u5236\u5e8f\u5217\u662f\u5177\u6709\u4ee5\u4e0b\u4e24\u4e2a\u6027\u8d28\u7684\u4e8c\u8fdb\u5236\u5e8f\u5217\uff1a

      \n\n
        \n\t
      • 0 \u7684\u6570\u91cf\u4e0e 1 \u7684\u6570\u91cf\u76f8\u7b49\u3002
      • \n\t
      • \u4e8c\u8fdb\u5236\u5e8f\u5217\u7684\u6bcf\u4e00\u4e2a\u524d\u7f00\u7801\u4e2d 1 \u7684\u6570\u91cf\u8981\u5927\u4e8e\u7b49\u4e8e 0 \u7684\u6570\u91cf\u3002
      • \n
      \n\n

      \u7ed9\u5b9a\u4e00\u4e2a\u7279\u6b8a\u7684\u4e8c\u8fdb\u5236\u5e8f\u5217 S\uff0c\u4ee5\u5b57\u7b26\u4e32\u5f62\u5f0f\u8868\u793a\u3002\u5b9a\u4e49\u4e00\u4e2a\u64cd\u4f5c \u4e3a\u9996\u5148\u9009\u62e9 S \u7684\u4e24\u4e2a\u8fde\u7eed\u4e14\u975e\u7a7a\u7684\u7279\u6b8a\u7684\u5b50\u4e32\uff0c\u7136\u540e\u5c06\u5b83\u4eec\u4ea4\u6362\u3002\uff08\u4e24\u4e2a\u5b50\u4e32\u4e3a\u8fde\u7eed\u7684\u5f53\u4e14\u4ec5\u5f53\u7b2c\u4e00\u4e2a\u5b50\u4e32\u7684\u6700\u540e\u4e00\u4e2a\u5b57\u7b26\u6070\u597d\u4e3a\u7b2c\u4e8c\u4e2a\u5b50\u4e32\u7684\u7b2c\u4e00\u4e2a\u5b57\u7b26\u7684\u524d\u4e00\u4e2a\u5b57\u7b26\u3002)

      \n\n

      \u5728\u4efb\u610f\u6b21\u6570\u7684\u64cd\u4f5c\u4e4b\u540e\uff0c\u4ea4\u6362\u540e\u7684\u5b57\u7b26\u4e32\u6309\u7167\u5b57\u5178\u5e8f\u6392\u5217\u7684\u6700\u5927\u7684\u7ed3\u679c\u662f\u4ec0\u4e48\uff1f

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: S = "11011000"\n\u8f93\u51fa: "11100100"\n\u89e3\u91ca:\n\u5c06\u5b50\u4e32 "10" \uff08\u5728S[1]\u51fa\u73b0\uff09 \u548c "1100" \uff08\u5728S[3]\u51fa\u73b0\uff09\u8fdb\u884c\u4ea4\u6362\u3002\n\u8fd9\u662f\u5728\u8fdb\u884c\u82e5\u5e72\u6b21\u64cd\u4f5c\u540e\u6309\u5b57\u5178\u5e8f\u6392\u5217\u6700\u5927\u7684\u7ed3\u679c\u3002\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      1. S \u7684\u957f\u5ea6\u4e0d\u8d85\u8fc7 50\u3002
      2. \n\t
      3. S \u4fdd\u8bc1\u4e3a\u4e00\u4e2a\u6ee1\u8db3\u4e0a\u8ff0\u5b9a\u4e49\u7684\u7279\u6b8a \u7684\u4e8c\u8fdb\u5236\u5e8f\u5217\u3002
      4. \n
      \n

      \u7279\u6b8a\u7684\u4e8c\u8fdb\u5236\u5e8f\u5217\u662f\u5177\u6709\u4ee5\u4e0b\u4e24\u4e2a\u6027\u8d28\u7684\u4e8c\u8fdb\u5236\u5e8f\u5217\uff1a

      \n\n
        \n\t
      • 0 \u7684\u6570\u91cf\u4e0e 1 \u7684\u6570\u91cf\u76f8\u7b49\u3002
      • \n\t
      • \u4e8c\u8fdb\u5236\u5e8f\u5217\u7684\u6bcf\u4e00\u4e2a\u524d\u7f00\u7801\u4e2d 1 \u7684\u6570\u91cf\u8981\u5927\u4e8e\u7b49\u4e8e 0 \u7684\u6570\u91cf\u3002
      • \n
      \n\n

      \u7ed9\u5b9a\u4e00\u4e2a\u7279\u6b8a\u7684\u4e8c\u8fdb\u5236\u5e8f\u5217 S\uff0c\u4ee5\u5b57\u7b26\u4e32\u5f62\u5f0f\u8868\u793a\u3002\u5b9a\u4e49\u4e00\u4e2a\u64cd\u4f5c \u4e3a\u9996\u5148\u9009\u62e9 S \u7684\u4e24\u4e2a\u8fde\u7eed\u4e14\u975e\u7a7a\u7684\u7279\u6b8a\u7684\u5b50\u4e32\uff0c\u7136\u540e\u5c06\u5b83\u4eec\u4ea4\u6362\u3002\uff08\u4e24\u4e2a\u5b50\u4e32\u4e3a\u8fde\u7eed\u7684\u5f53\u4e14\u4ec5\u5f53\u7b2c\u4e00\u4e2a\u5b50\u4e32\u7684\u6700\u540e\u4e00\u4e2a\u5b57\u7b26\u6070\u597d\u4e3a\u7b2c\u4e8c\u4e2a\u5b50\u4e32\u7684\u7b2c\u4e00\u4e2a\u5b57\u7b26\u7684\u524d\u4e00\u4e2a\u5b57\u7b26\u3002)

      \n\n

      \u5728\u4efb\u610f\u6b21\u6570\u7684\u64cd\u4f5c\u4e4b\u540e\uff0c\u4ea4\u6362\u540e\u7684\u5b57\u7b26\u4e32\u6309\u7167\u5b57\u5178\u5e8f\u6392\u5217\u7684\u6700\u5927\u7684\u7ed3\u679c\u662f\u4ec0\u4e48\uff1f

      \n\n

      \u793a\u4f8b 1:

      \n\n
      \n\u8f93\u5165: S = "11011000"\n\u8f93\u51fa: "11100100"\n\u89e3\u91ca:\n\u5c06\u5b50\u4e32 "10" \uff08\u5728S[1]\u51fa\u73b0\uff09 \u548c "1100" \uff08\u5728S[3]\u51fa\u73b0\uff09\u8fdb\u884c\u4ea4\u6362\u3002\n\u8fd9\u662f\u5728\u8fdb\u884c\u82e5\u5e72\u6b21\u64cd\u4f5c\u540e\u6309\u5b57\u5178\u5e8f\u6392\u5217\u6700\u5927\u7684\u7ed3\u679c\u3002\n
      \n\n

      \u8bf4\u660e:

      \n\n
        \n\t
      1. S \u7684\u957f\u5ea6\u4e0d\u8d85\u8fc7 50\u3002
      2. \n\t
      3. S \u4fdd\u8bc1\u4e3a\u4e00\u4e2a\u6ee1\u8db3\u4e0a\u8ff0\u5b9a\u4e49\u7684\u7279\u6b8a \u7684\u4e8c\u8fdb\u5236\u5e8f\u5217\u3002
      4. \n
      \n*/\n\n\n/**\n * @param {string} S\n * @return {string}\n */\nvar makeLargestSpecial = function(S) {\n \n};"} {"doc_id": "68527fd227700aee842d087518f154b5", "text": "//destructuring objects \nvar {\n color,\n age\n} = {\n color: 'red',\n age: 20,\n name: 'John'\n}\n\nconsole.log(color);\nconsole.log(age);\nconsole.log('----------------------');\n\n//\n\nfunction generateObject() {\n return {\n color: 'red',\n age: 20,\n name: 'John',\n company: 'Software Development'\n }\n}\n\n// this example look for the same named object key in the object\nvar {\n company\n} = generateObject();\nconsole.log(company);\n\n//this will lookup company and asign it to workSpace \n\nvar {\n company: workSpace,\n age: howOld\n} = generateObject();\n\nconsole.log(workSpace, howOld);"} {"doc_id": "685deaf7c4acfdd7bf9233bb5c8c2565", "text": "/*\nWrite a function called \"sumDigits\".\n\nGiven a number, \"sumDigits\" returns the sum of all its digits.\n\nvar output = sumDigits(1148);\nconsole.log(output); // --> 14\n\nIf the number is negative, the first digit should count as negative.\n\nvar output = sumDigits(-316);\nconsole.log(output); // --> 4\n\nNotes:\n* In order to use some of the methods that will be most helpful to you, you will most likely want to do some string to number conversion and vice versa.\n* Be sure to familiarize yourself with the \"toString\" method, as well as the \"Number\" function.\n\n*/\n\nfunction sumDigits(num) {\n // your code here\n /* START SOLUTION */\n num = num.toString();\n\n var isNegative;\n if (num[0] === \"-\") {\n isNegative = true;\n num = num.substring(1);\n }\n\n var total = 0;\n for(var i = 0; i < num.length; i++) {\n total += Number(num[i]);\n }\n return isNegative ? total - Number(num[0]) * 2 : total;\n /* END SOLUTION */\n}\n"} {"doc_id": "692d03a38b28f83e8b09cb67aedc9685", "text": " // Your first ever JavaScript variable! ^_^\r\nvar myFirstVariable = 10;\r\n// Your second ever JavaScript variable! Woooo!\r\nvar mySecondVariable = 5;\r\n // Your third ever JavaScript variable! You're a pro now!\r\nvar myThirdVariable = myFirstVariable + mySecondVariable;\r\n\r\nconsole.log(myThirdVariable);\r\n\r\n// Output: 15\r\n\r\n/**\r\n * Adds two numbers a & b and returns the result.\r\n * @param {Number} a The left hand value.\r\n * @param {Number} b The right hand value.\r\n */\r\nfunction add(a, b) {\r\n var result = a + b;\r\n\r\n return result;\r\n}\r\n\r\n// This will result in an undefined error,\r\n// as result was defined in the add function\r\n// and is locally scoped to that function.\r\nconsole.log(result);\r\n\r\nvar result = add(10, 10);\r\n\r\nconsole.log(result);\r\n\r\n// Output: 20\r\n\r\n// ======= let =======\r\nlet someVariable = 10;\r\n\r\n// block-scope\r\n{\r\n let someVariable = 20;\r\n}\r\n\r\nconsole.log(someVariable);\r\n\r\n// Output:\r\n// 10\r\n\r\n// ======== const ========\r\nconst PI = 3.14;\r\n\r\n{\r\n PI = 0;\r\n}\r\n\r\nPI = 1;\r\n\r\n// Output:\r\n// TypeError: invalid assignment to const `PI'"} {"doc_id": "699df19f2378bce09ee2f3f4c649b5d3", "text": "let myArray = [1,2,3,24];\n\n\nfunction printReverse(array) {\n\t// console.log(array.reverse());\n\tfor (let x = array.length - 1; x >= 0; x--) {\n\t\tconsole.log(array[x]);\n\t}\n}\n\nfunction isUniform(array) {\n\tfor (let x = array.length - 1; x > 0 ; x--) {\n\t\tif (array[x] !== array[x - 1]) {\n\t\t\t false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nfunction sumArray(array) {\n\tlet sum = 0;\n\n\tarray.forEach(function(item) {\n\t\tsum += item;\n\t});\n\n\treturn sum;\n}\n\nfunction max(array) {\n\tarray.sort(function(num1, num2) {\n\t\treturn num1 > num2 ? -1 : 1;\n\t})\n\n\t// Another way is to loop through and compare items\n\treturn array[0];\n}\n\n// My For forEach\nfunction myForEach(array, myfunction) {\n\tfor (let x = 0; x < array.length; x++) {\n\t\tconsole.log(myfunction(array[x]));\n\t}\n}\n\n// Add to Array\nArray.prototype.myForEach = function(myfunction) {\n\tfor (let x = 0; x < this.length; x++) {\n\t\tconsole.log(myfunction(this[x]));\n\t}\n}\n\n\nprintReverse(myArray);\nconsole.log(\"----------\");\nconsole.log(isUniform(myArray) + \"\\n----------\");\nconsole.log(sumArray(myArray) + \"\\n----------\");\nconsole.log(max(myArray) + \"\\n----------\");\nmyForEach(myArray, function(num) {\n\treturn num * 2;\n});\nconsole.log(\"----------\");\nmyArray.myForEach(function(num) {\n\treturn num * 3;\n});\n\nconsole.log(\"----------\");\n\n\nArray.prototype.multiplyByFive = function() {\n for(let x = 0; x < this.length; x++) {\n \tthis[x] = this[x] * 5;\n }\n}\n\n// We can then call this method on an Array\n\nlet myNumbers = [1, 3, 5, 7, 9];\n\nmyNumbers.multiplyByFive();\n\nconsole.log(myNumbers);\n\n\n// function expression catSays\nvar catSays = function() {\n \n return \"meow\";\n};\n\n// function declaration helloCat accepting a callback\nfunction helloCat(callbackFunc) {\n return \"Hello \" + callbackFunc(3);\n}\n\n// pass in catSays as a callback function\nconsole.log(helloCat(catSays));\n\n\n\n\n\n\n\n"} {"doc_id": "69a8b49f9cd54fe6f8dd4b8a211aac41", "text": "//Parsing JSON as a variable\n//Create a variable that holds JSON formatted data\nvar Input = '[{\"Name\":\"Vahn\", \"HP\": 50},{\"Name\":\"Noa\", \"HP\": 40}]';\n//Create a new variable to hold the parsed data of the previous variable\nvar Parsed = JSON.parse(Input);\n//Example showing you can add more objects to the Parsed variable\nParsed.push({ Name: \"Gala\", HP: 75 });\n//Create variable that turns a JavaScript Object into JSON\nvar Output = JSON.stringify(Parsed);\n//Print the new JSON that should have our new addition \"Gala\" now as part of the JSON data\nconsole.log(Output);\n\n//Parsing RAW JSON\n//Create a variable that holds the data of the parsed function performed on JSON\nvar Parse = JSON.parse('[{\"Name\":\"Vahn\", \"HP\": 50},{\"Name\":\"Noa\", \"HP\": 40}]');\n//Same as above\nParse.push({ Name: \"Gala\", HP: 75 });\n//Same as above\nvar Output1 = JSON.stringify(Parse);\n//Print the line to the console.\nconsole.log(Output1);"} {"doc_id": "6bc4830937e5b03edb0aa487099cb5f3", "text": "/**\n * Created by\uff1aCaMnter\n */\n\n/*****************\n * \u5c5e\u6027\u7684\u53ef\u679a\u4e3e\u6027 *\n *****************/\n\n/**\n * \u5bf9\u8c61\u7684\u6bcf\u4e2a\u5c5e\u6027\u90fd\u6709\u4e00\u4e2a\u63cf\u8ff0\u5bf9\u8c61\uff08Descriptor\uff09\uff0c\u7528\u6765\u63a7\u5236\u8be5\u5c5e\u6027\u7684\u884c\u4e3a\u3002\n * Object.getOwnPropertyDescriptor \u65b9\u6cd5\u53ef\u4ee5\u83b7\u53d6\u8be5\u5c5e\u6027\u7684\u63cf\u8ff0\u5bf9\u8c61\n */\nlet o1 = {save: \"Save you from anything\", camnter: \"CaMnter\"};\nconsole.log(\"[object]\\t\\t[test-\" + 1 + \"]\\t\\t[Object.getOwnPropertyDescriptor(o1, 'save')] = \", '\\n', Object.getOwnPropertyDescriptor(o1, 'save'), '\\n');\n\n/**\n * \u63cf\u8ff0\u5bf9\u8c61\u7684 enumerable \u5c5e\u6027\uff0c\u79f0\u4e3a \u201d\u53ef\u679a\u4e3e\u6027\u201c\uff0c\u5982\u679c\u8be5\u5c5e\u6027\u4e3a false\uff0c\u5c31\u8868\u793a\u67d0\u4e9b\u64cd\u4f5c\u4f1a\u5ffd\u7565\u5f53\u524d\u5c5e\u6027\u3002\n *\n * ES5 \u6709\u4e09\u4e2a\u64cd\u4f5c\u4f1a\u5ffd\u7565 enumerable \u4e3a false \u7684\u5c5e\u6027\n * - for...in \u5faa\u73af\uff1a\u53ea\u904d\u5386\u5bf9\u8c61\u81ea\u8eab\u7684\u548c\u7ee7\u627f\u7684\u53ef\u679a\u4e3e\u7684\u5c5e\u6027\n * - Object.keys()\uff1a\u8fd4\u56de\u5bf9\u8c61\u81ea\u8eab\u7684\u6240\u6709\u53ef\u679a\u4e3e\u7684\u5c5e\u6027\u7684\u952e\u540d\n * - JSON.stringify()\uff1a\u53ea\u4e32\u884c\u5316\u5bf9\u8c61\u81ea\u8eab\u7684\u53ef\u679a\u4e3e\u7684\u5c5e\u6027\n *\n * ES6 \u65b0\u589e\u4e86\u4e00\u4e2a\u64cd\u4f5c Object.assign()\uff0c\u4f1a\u5ffd\u7565 enumerable \u4e3a false \u7684\u5c5e\u6027\uff0c\u53ea\u62f7\u8d1d\u5bf9\u8c61\u81ea\u8eab\u7684\u53ef\u679a\u4e3e\u7684\u5c5e\u6027\n *\n * \u8fd9\u56db\u4e2a\u64cd\u4f5c\u4e4b\u4e2d\uff0c\u53ea\u6709 for...in \u4f1a\u8fd4\u56de\u7ee7\u627f\u7684\u5c5e\u6027\u3002\u5b9e\u9645\u4e0a\uff0c\u5f15\u5165 enumerable \u7684\u6700\u521d\u76ee\u7684\uff0c\u5c31\u662f\u8ba9\u67d0\u4e9b\u5c5e\u6027\u53ef\u4ee5\u89c4\u907f\u6389 for...in \u64cd\u4f5c\u3002\n * \u6bd4\u5982\uff0c\u5bf9\u8c61\u539f\u578b\u7684 toString \u65b9\u6cd5\uff0c\u4ee5\u53ca\u6570\u7ec4\u7684 length \u5c5e\u6027\uff0c\u5c31\u901a\u8fc7\u8fd9\u79cd\u624b\u6bb5\uff0c\u4e0d\u4f1a\u88ab for...in \u904d\u5386\u5230\n */\nconsole.log(\"[object]\\t\\t[test-\" + 2 + \"]\\t\\t[Object.getOwnPropertyDescriptor(Object.prototype, 'toString').enumerable] = \", Object.getOwnPropertyDescriptor(Object.prototype, 'toString').enumerable, '\\n');\nconsole.log(\"[object]\\t\\t[test-\" + 2 + \"]\\t\\t[Object.getOwnPropertyDescriptor([], 'length').enumerable] = \", Object.getOwnPropertyDescriptor([], 'length').enumerable, '\\n');\n\n/**\n * ES6 \u89c4\u5b9a\uff0c\u6240\u6709 Class \u7684\u539f\u578b\u7684\u65b9\u6cd5\u90fd\u662f\u4e0d\u53ef\u679a\u4e3e\u7684\n * \u64cd\u4f5c\u4e2d\u5f15\u5165\u7ee7\u627f\u7684\u5c5e\u6027\u4f1a\u8ba9\u95ee\u9898\u590d\u6742\u5316\uff0c\u5927\u591a\u6570\u65f6\u5019\uff0c\u6211\u4eec\u53ea\u5173\u5fc3\u5bf9\u8c61\u81ea\u8eab\u7684\u5c5e\u6027\u3002\u6240\u4ee5\uff0c\n *\n * \u6ce8\u610f: \u5c3d\u91cf\u4e0d\u8981\u7528 for...in \u5faa\u73af\uff0c\u800c\u7528 Object.keys() \u4ee3\u66ff\n */\nconsole.log(\"[object]\\t\\t[test-\" + 3 + \"]\\t\\t[Object.getOwnPropertyDescriptor(class {foo() {}}.prototype, 'foo').enumerable] = \", Object.getOwnPropertyDescriptor(class {foo() {}}.prototype, 'foo').enumerable, '\\n');"} {"doc_id": "6cb9ec42e6ccaa2ee3fb9c5b24ea90b1", "text": "/*\nWrite a function called \"isOdd\".\n\nGiven a number, \"isOdd\" returns whether the given number is odd.\n\nvar output = isOdd(9);\nconsole.log(output); // --> true\n*/\n\nfunction isOdd(num) {\n // your code here\n /* START SOLUTION */\n return num % 2 !== 0;\n /* END SOLUTION */\n}\n\ndescribe(\"isOdd\", function() {\n it(\"should return a boolean\", function() {\n expect(typeof isOdd(40)).toEqual(\"boolean\");\n });\n it(\"should return if the number is odd\", function() {\n expect(isOdd(7)).toBe(true);\n });\n it(\"should return false if the number is 0\", function() {\n expect(isOdd(0)).toBe(false);\n });\n});\n"} {"doc_id": "6cbbb3e6a621668155bce987f99e859c", "text": "/*\n

      Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.  Return a list of all possible strings we could create.

      \n\n
      \nExamples:\nInput: S = "a1b2"\nOutput: ["a1b2", "a1B2", "A1b2", "A1B2"]\n\nInput: S = "3z4"\nOutput: ["3z4", "3Z4"]\n\nInput: S = "12345"\nOutput: ["12345"]\n
      \n\n

      Note:

      \n\n
        \n\t
      • S will be a string with length at most 12.
      • \n\t
      • S will consist only of letters or digits.
      • \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32S\uff0c\u901a\u8fc7\u5c06\u5b57\u7b26\u4e32S\u4e2d\u7684\u6bcf\u4e2a\u5b57\u6bcd\u8f6c\u53d8\u5927\u5c0f\u5199\uff0c\u6211\u4eec\u53ef\u4ee5\u83b7\u5f97\u4e00\u4e2a\u65b0\u7684\u5b57\u7b26\u4e32\u3002\u8fd4\u56de\u6240\u6709\u53ef\u80fd\u5f97\u5230\u7684\u5b57\u7b26\u4e32\u96c6\u5408\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165: S = "a1b2"\n\u8f93\u51fa: ["a1b2", "a1B2", "A1b2", "A1B2"]\n\n\u8f93\u5165: S = "3z4"\n\u8f93\u51fa: ["3z4", "3Z4"]\n\n\u8f93\u5165: S = "12345"\n\u8f93\u51fa: ["12345"]\n
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      • S \u7684\u957f\u5ea6\u4e0d\u8d85\u8fc712\u3002
      • \n\t
      • S \u4ec5\u7531\u6570\u5b57\u548c\u5b57\u6bcd\u7ec4\u6210\u3002
      • \n
      \n

      \u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32S\uff0c\u901a\u8fc7\u5c06\u5b57\u7b26\u4e32S\u4e2d\u7684\u6bcf\u4e2a\u5b57\u6bcd\u8f6c\u53d8\u5927\u5c0f\u5199\uff0c\u6211\u4eec\u53ef\u4ee5\u83b7\u5f97\u4e00\u4e2a\u65b0\u7684\u5b57\u7b26\u4e32\u3002\u8fd4\u56de\u6240\u6709\u53ef\u80fd\u5f97\u5230\u7684\u5b57\u7b26\u4e32\u96c6\u5408\u3002

      \n\n
      \n\u793a\u4f8b:\n\u8f93\u5165: S = "a1b2"\n\u8f93\u51fa: ["a1b2", "a1B2", "A1b2", "A1B2"]\n\n\u8f93\u5165: S = "3z4"\n\u8f93\u51fa: ["3z4", "3Z4"]\n\n\u8f93\u5165: S = "12345"\n\u8f93\u51fa: ["12345"]\n
      \n\n

      \u6ce8\u610f\uff1a

      \n\n
        \n\t
      • S \u7684\u957f\u5ea6\u4e0d\u8d85\u8fc712\u3002
      • \n\t
      • S \u4ec5\u7531\u6570\u5b57\u548c\u5b57\u6bcd\u7ec4\u6210\u3002
      • \n
      \n*/\n\n\n/**\n * @param {string} S\n * @return {string[]}\n */\nvar letterCasePermutation = function(S) {\n \n};"} {"doc_id": "6e279ceb9ac6660a52be8a18e5d6a3e1", "text": "// Codewars - Andreas Sosilo\n// 8 kyu - Counting sheep...\n\n/*\nTask:\n-----\nConsider an array of sheep where some sheep may be missing from their place.\nWe need a function that counts the number of sheep present in the array (true means present).\n\nFor example,\n\n[true, true, true, false,\n true, true, true, true ,\n true, false, true, false,\n true, false, false, true ,\n true, true, true, true ,\n false, false, true, true]\nThe correct answer would be 17.\n\nHint: Don't forget to check for bad values like null/undefined\n*/\n\nfunction countSheeps (arrayOfSheep) {\n if (arrayOfSheep === null || arrayOfSheep === undefined) return `There are no sheeps at all`\n // Creat a variable to count the true sheep\n let count = 0\n // Using for-in loop to check the true sheeps\n for (let key in arrayOfSheep) {\n if (arrayOfSheep[key] === true) {\n count++\n }\n }\n // Return the number of true sheeps\n return count\n}\n\n// BEST SOLUTION USING FILTER\n// function countSheeps (arrayOfSheeps) {\n// return arrayOfSheeps.filter(Boolean).length\n// }\n\n// TEST CASES\nvar array1 =\n[\n true, true, true, false,\n true, true, true, true,\n true, false, true, false,\n true, false, false, true,\n true, true, true, true,\n false, false, true, true\n]\nconsole.log(countSheeps(array1)) // 'There are 17 sheeps in total'\n"} {"doc_id": "6e2eb91395db4c82ae90f95a671ec6e4", "text": "///////////////////////////////////////////\n\n// \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043a\u043b\u0430\u0441\u0441 RandColor\nclass RandColor {\n constructor() {}\n\n // \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043c\u0435\u0442\u043e\u0434 rgb \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 rgb(); \u0441 \u0440\u0430\u043d\u0434\u043e\u043c\u043d\u044b\u043c\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\u043c\u0438.\n rgb() {\n let color = [\n Math.floor(Math.random() * 225),\n Math.floor(Math.random() * 225),\n Math.floor(Math.random() * 225)\n ];\n return `rgb(${color})`;\n }\n\n // \u0421\u043e\u0437\u0434\u0430\u0451\u043c \u043c\u0435\u0442\u043e\u0434 rgba \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 rgba(); \u0441 \u0440\u0430\u043d\u0434\u043e\u043c\u043d\u044b\u043c\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\u043c\u0438.\n rgba() {\n let color = [\n Math.floor(Math.random() * 225),\n Math.floor(Math.random() * 225),\n Math.floor(Math.random() * 225),\n (Math.random() * (1 - 0.5) + 0.5).toFixed(1)\n ];\n return `rgba(${color})`;\n }\n\n // \u0421\u043e\u0437\u0434\u0430\u0451\u043c hex \u043a\u043e\u0442\u043e\u0440\u044b\u0439 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 #hex-\u0446\u0432\u0435\u0442 \u0441 \u0440\u0430\u043d\u0434\u043e\u043c\u043d\u044b\u043c\u0438 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\u043c\u0438.\n hex(reduce = 0) {\n let arr = [0, 1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e', 'f'];\n\n let randValue = (count) => {\n let result = '#';\n for (let i = 0; i < count; i++)\n result += arr[Math.floor(Math.random() * arr.length)];\n return result;\n }\n\n if (reduce) return randValue(3);\n else return randValue(6);\n }\n}\n\n\n// \u041f\u0440\u0438\u0441\u0432\u0430\u0438\u0432\u0430\u0435\u043c \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439 \u043d\u043e\u0432\u044b\u0439 \u043e\u0431\u044a\u0435\u043a\u0442 \u043a\u043b\u0430\u0441\u0441\u0430.\n// let randColor = new RandColor();\n\n// console.log(randColor.rgb());\n// console.log(randColor.rgba());\n// console.log(randColor.hex());"} {"doc_id": "6e7ee859b96d05ee6f8bc72ca8c0401b", "text": "//Q: \"write a function that takes in a string, and returns count of each char in string\"\n\n//simple example\n// charCount('aaaa'); // {a:4}\n\n// - should it just return letters? Also spaces?\n\n//complex example\n// \"my phone number is 1234134\" // casing, numbers, etc.?\n\n// empty inputs\n//charCount(\"\") //what do we want to return, undefined, null?\n\nlet str = \"Hello\"\n\n// function charCount(str){\n// //make object to return at end\n// let result = {};\n// //loop over string, forEach character\n// for(let i = 0; i < str.length; i++){\n// let char = str[i].toLowerCase()\n\n// if (result[char] > 0){\n// //if CHAR is a number/character && is key in object, add 1 to count\n// //if already a key in object\n// result[char]++\n// } else {\n// //if CHAR is a number/letter && not in object, add it and set value to 1\n// //not already key in object\n// result[char] = 1\n// }\n\n// //if CHAR is something else, don't do anything\n// }\n\n\n// // return object at end\n// console.log(result)\n// }\n\n// charCount(str)\n\n// --------- REFACTOR 1 --------- //\n\n// 1 - sanitize data to be alphanumeric\n\n// function charCount(str) {\n// let obj = {};\n\n// for(let i = 0; i < str.length; i++){\n// let char = str[i].toLowerCase()\n\n// if(/[a-z0-9]/.test(char)){\n// // sanitize data to only include ALPHA-NUMERIC\n// //.test() method = tests for a match in a string\n// if(obj[char] > 0){\n// obj[char]++\n// } else {\n// obj[char] = 1\n// }\n// }\n\n// }\n// console.log(obj)\n// }\n\n\n//------- REFACTOR 2 -----------//\n\n// 1 - for loop first creates variable for number, THEN loops\n// - easier to use FOR OF loop\n\nfunction charCount(str) {\n let obj = {};\n\n for(let char of str) {\n if (isAlphaNumeric(char)) {\n char = char.toLowerCase()\n\n // sanitize data to only include ALPHA-NUMERIC\n //.test() method = tests for a match in a string\n \n //if truthy, add 1, else set value to 1\n obj[char] = ++obj[char] || 1;\n }\n\n }\n console.log(obj)\n}\n\ncharCount(str)\n\n// ---------- REFACTOR 3 --------- //\n\nfunction isAlphaNumeric(char){\n let code = char.charCodeAt(0)\n\n if(!(code > 47 && code < 58) && // numeric (0-9)\n !(code > 64 && code < 91) && // upper alpha (A-Z)\n !(code > 96 && code < 123) // lower alpha (a-z)\n ){\n return false\n }\n return true\n}\n"} {"doc_id": "701e40f67a35a08195b1a66d4e0d1860", "text": "var operacao = prompt(\"Qual opera\u00e7\u00e3o voc\u00ea deseja fazer? Digite 1 para soma, 2 para subtra\u00e7\u00e3o, 3 para multiplica\u00e7\u00e3o e 4 para divis\u00e3o: \");\nvar primeiroValor = parseFloat(prompt(\"Digite o primeiro valor: \"));\nvar segundoValor = parseFloat(prompt(\"Digite o segundo valor: \"));\nvar resultado = 0;\nvar operador = '';\nif (operacao == 1) {\n resultado = primeiroValor + segundoValor;\n operador = ' + ';\n} else if (operacao ==2) {\n resultado = primeiroValor - segundoValor;\n operador = \" - \";\n} else if (operacao == 3) {\n resultado = primeiroValor * segundoValor;\n operador = \" x \";\n} else if (operacao == 4) {\n resultado = primeiroValor / segundoValor;\n operador = \" / \";\n} else {\n alert(\"Op\u00e7\u00e3o inv\u00e1lida\");\n}\n\n document.write(\"

      \" + primeiroValor + operador + segundoValor + \" = \" + resultado.toFixed(2) + \"

      \");\n\n\n\n\n//if = se\n// else = sen\u00e3o\n// else if = sen\u00e3o se"} {"doc_id": "7028f6f1f9998c1e0aea8b5452da7805", "text": "\ufeff//Write a script that finds the index of given element in a sorted array of integers\n//by using the binary search algorithm.\n\nconsole.log('=====================================');\nconsole.log('07. Binary search');\nconsole.log('-------------------------');\n\nvar arr = [1, 2, 3, 4, 5, 6, 8, 9, 11, 14, 15],\n srchValRec = 3,\n srchValIt = 0,\n minInd = 0,\n maxInd = arr.length - 1,\n midInd;\n\nfunction binarySearchRecursive(array, number, min, max) {\n midInd = (min + (max - min) / 2) | 0;\n\n if (max < min) {\n return -1;\n }\n else {\n if (array[midInd] < number) {\n return binarySearchRecursive(arr, number, midInd + 1, max);\n }\n else if (array[midInd] > number) {\n return binarySearchRecursive(arr, number, min, midInd - 1);\n }\n else {\n return midInd;\n }\n }\n}\n\nfunction binarySearchIterative(array, number, min, max) {\n while (max >= min) {\n midInd = (min + (max - min) / 2) | 0;\n\n if (array[midInd] === number) {\n return midInd;\n }\n else if (array[midInd] < number) {\n min = midInd + 1;\n }\n else {\n max = midInd - 1;\n }\n }\n return -1;\n}\n\nconsole.log('Array= [' + arr.join(', ') + ']');\nconsole.log('Index of ' + srchValIt + '= ' + binarySearchIterative(arr, srchValIt, minInd, maxInd) + ' -> iterative');\nconsole.log('Index of ' + srchValRec + '= ' + binarySearchRecursive(arr, srchValRec, minInd, maxInd) + ' -> recursive');"} {"doc_id": "7031284ec5ac2977d81c46f782fa255c", "text": "// Elements\n\nconst form = document.querySelector('#weather-search');\nconst tempElement = document.querySelector('#temp');\nconst descriptionElement = document.querySelector('#description');\nconst cityElement = document.getElementById('city');\n\n// Event\n\nform.addEventListener('submit', handleWeatherRequest);\n\n// Execution\n\nasync function handleWeatherRequest(event) {\n // stop the form submit from refreshing the page\n event.preventDefault();\n const city = cityElement.value;\n const apiKey = '870b1b10b58578f725b70b13aff6c357';\n\n const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=${apiKey}`;\n console.log(url);\n\n // get weather data from open weather map API\n // save the response\n const response = await fetch(url);\n // convert the response to json data\n // save the json in a weatherData variable\n const weatherData = await response.json();\n console.log({ weatherData });\n\n // get the weather descripton from response data\n const weatherDescription = weatherData.weather[0].description;\n\n // convert the temperature from kelvin to celcius\n const tempCelcius = Math.floor(weatherData.main.temp - 273);\n\n // update the temperature and decription on the page\n document.querySelector('#temp').innerHTML = `\n \t\t${tempCelcius}oC\n \t`;\n document.querySelector('#description').innerHTML = `\n \t\tThe weather in ${city} is
      \n \t\t${weatherDescription}\n \t`;\n}\n"} {"doc_id": "71b495e7f124087e9460dda44b972e3f", "text": "/*\n\nTask:\n\nGiven an array:\n ['1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '0', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1']\n\n1. Find the longest sequence of \"1\"s.\n2. Arrange the sequence of \"1\"s and \"0\"s in ascending order in a new array while alternating the \"1\"s and \"0\"s.\n\n*/\n\n\nconst taskArr = ['1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '0', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1'];\n\nconst longestSequence = (taskArr) => {\n let intArr = [];\n\n taskArr.forEach((data) => {\n intArr.push(parseInt(data));\n });\n\n let countOne = [];\n let count1 = [];\n\n intArr.forEach((number) => {\n if (number === 1) {\n countOne.push(number);\n } else if (number === 0) {\n count1.push(countOne.length);\n countOne = [];\n }\n });\n\n const newArr = count1.filter( (data) => data !== 0 );\n \n\n let highest = 0;\n newArr.forEach( (data) => {\n\n if(highest < data){\n highest = data;\n }\n \n \n });\n console.log( `longest sequence of \"1\"s = ${highest} \\n`)\n\n\n console.log(` Sequence counts list = ${newArr} \\n` );\n return highest;\n};\n\nlongestSequence(taskArr);\n\n\nconst arrangeAscending = (taskArr) => {\n\n let intArr = [];\n\n taskArr.forEach((data) => {\n intArr.push(parseInt(data));\n });\n\n let one = [];\n let zero = [];\n\n intArr.forEach( (num) => {\n if(num === 0 ){\n zero.push(num);\n }\n else {\n one.push(num);\n }\n\n })\n\n const resultArr = zero.concat(one);\n\n console.log(`Arrange the sequence of \"1\"s and \"0\"s in ascending order = \\n\\n ${resultArr} \\n`);\n return resultArr;\n\n}\n\n\narrangeAscending(taskArr);"}