├── .travis.yml ├── README.md ├── databases └── 01-projectList │ └── projectList.js ├── intro ├── 01-add │ ├── add.js │ └── add.spec.js ├── 02-centuryFromYear │ ├── centuryFromYear.js │ └── centuryFromYear.spec.js ├── 03-checkPalindrome │ ├── checkPalindrome.js │ └── checkPalindrome.spec.js ├── 04-adjacentElementsproduct │ ├── adjacentElementsProduct.js │ └── adjacentElementsProduct.spec.js ├── 05-shapeArea │ ├── shapeArea.js │ └── shapeArea.spec.js ├── 06-makeArrayConsecutive2 │ ├── makeArrayConsecutive2.js │ └── makeArrayConsecutive2.spec.js ├── 07-almostIncreasingSequence │ ├── almostIncreasingSequence.js │ └── almostIncreasingSequence.spec.js ├── 08-matrixElementsSum │ ├── matrixElementsSum.js │ └── matrixElementsSum.spec.js ├── 09-allLongestStrings │ ├── allLongestStrings.js │ └── allLongestStrings.spec.js ├── 10-commonCharacterCount │ ├── commonCharacterCount.js │ └── commonCharacterCount.spec.js ├── 11-isLucky │ ├── isLucky.js │ └── isLucky.spec.js ├── 12-sortByHeight │ ├── sortByHeight.js │ └── sortByHeight.spec.js ├── 13-reverseInParentheses │ ├── reverseInParentheses.js │ └── reverseInParentheses.spec.js ├── 14-alternatingSums │ ├── alternatingSums.js │ └── alternatingSums.spec.js ├── 15-addBorder │ ├── addBorder.js │ └── addBorder.spec.js ├── 16-areSimilar │ ├── areSimilar.js │ └── areSimilar.spec.js ├── 17-arrayChange │ ├── arrayChange.js │ └── arrayChange.spec.js ├── 18-palindromeRearranging │ ├── palindromeRearranging.js │ └── palindromeRearranging.spec.js ├── 19-areEquallyStrong │ └── areEquallyStrong.js ├── 20-arrayMaximalAdjacentDifference │ └── arrayMaximalAdjacentDifference.js ├── 21-isIPv4Address │ └── isIPv4Address.js ├── 22-avoidObstacles │ ├── avoidObstacles.js │ └── avoidObstacles.spec.js ├── 23-boxBlur │ ├── boxBlur.js │ └── boxBlur.spec.js ├── 24-mineSweeper │ ├── mineSweeper.js │ └── mineSweeper.spec.js ├── 25-arrayReplace │ ├── arrayReplace.js │ └── arrayReplace.spec.js ├── 26-evenDigitsOnly │ ├── evenDigitsOnly.js │ └── evenDigitsOnly.spec.js ├── 27-variableName │ ├── variableName.js │ └── variableName.spec.js ├── 28-alphabeticShift │ ├── alphabeticShift.js │ └── alphabeticShift.spec.js ├── 29-chessBoardCellColor │ ├── chessBoardCellColor.js │ └── chessBoardCellColor.spec.js ├── 30-circleOfNumbers │ ├── circleOfNumbers.js │ └── circleOfNumbers.spec.js ├── 31-depositProfit │ ├── depositProfit.js │ └── depositProfit.spec.js ├── 32-absoluteValuesSumMinimization │ ├── absoluteValuesSumMinimization.js │ └── absoluteValuesSumMinimization.spec.js ├── 33-stringsRearrangement │ ├── stringsRearrangement.js │ └── stringsRearrangement.spec.js ├── 34-extractEachKth │ ├── extractEachKth.js │ └── extractEachKth.spec.js ├── 35-firstDigit │ ├── firstDigit.js │ └── firstDigit.spec.js ├── 36-differentSymbolsNaive │ ├── differentSymbolsNaive.js │ └── differentSymbolsNaive.spec.js ├── 37-arrayMaxConsecutiveSum │ ├── arrayMaxConsecutiveSum.js │ └── arrayMaxConsecutiveSum.spec.js ├── 38-growingPlant │ ├── growingPlant.js │ └── growingPlant.spec.js ├── 39-knapSackLight │ ├── knapSackLight.js │ └── knapSackLight.spec.js ├── 40-longestDigitsPrefix │ ├── longestDigitsPrefix.js │ └── longestDigitsPrefix.spec.js ├── 41-digitDegree │ ├── digitDegree.js │ └── digitDegree.spec.js ├── 42-bishopAndPawn │ ├── bishopAndPawn.js │ └── bishopAndPawn.spec.js ├── 43-isBeautifulString │ └── isBeautifulString.js ├── 44-findEmailDomain │ └── findEmailDomain.js ├── 45-buildPalindrome │ └── buildPalindrome.js ├── 46-electionWinners │ └── electionWinners.js ├── 47-isMAC48Address │ └── isMAC48Address.js ├── 48-isDigit │ └── isDigit.js ├── 49-lineEncoding │ └── lineEncoding.js ├── 50-chessKnight │ └── chessKnight.js ├── 51-deleteDigit │ ├── deleteDigit.js │ └── deleteDigit.spec.js ├── 52-longestWord │ ├── longestWord.js │ └── longestWord.spec.js ├── 53-validTime │ ├── validTime.js │ └── validTime.spec.js ├── 54-sumUpNumbers │ ├── sumUpNumbers.js │ └── sumUpNumbers.spec.js ├── 55-differentSquares │ ├── differentSqares.js │ └── differentSquares.spec.js ├── 56-digitsProduct │ ├── digitsProduct.js │ └── digitsProduct.spec.js ├── 57-fileNaming │ ├── fileNaming.js │ └── fileNaming.spec.js ├── 58-messageFromBinaryCode │ ├── messageFromBinaryCode.js │ └── messageFromBinaryCode.spec.js ├── 59-spiralNumbers │ ├── spiralNumbers.js │ └── spiralNumbers.spec.js └── 60-sudoku │ ├── sudoku.js │ └── sudoku.spec.js ├── package.json └── the_core ├── 01-addTwoDigits ├── addTwoDigits.js └── addTwoDigits.spec.js ├── 02-largestNumber ├── largestNumber.js └── largestNumber.spec.js ├── 03-candies ├── candies.js └── candies.spec.js ├── 04-seatsInTheater └── seatsInTheater.js ├── 05-maxMultiple └── maxMultiple.js ├── 06-circleOfNumbers └── circleOfNumbers.js ├── 07-lateTime └── lateTime.js ├── 08-phoneCall └── phoneCall.js ├── 09-reachNewLevel └── reachNewLevel.js ├── 10-knapsackLight └── knapsackLight.js ├── 100-reverseOnDiagnosis └── reverseOnDiagnosis.js ├── 101-swapDiagnosis └── swapDiagnosis.js ├── 102-crossingSum └── crossingSum.js ├── 103-drawRectangle └── drawRectangle.js ├── 104-volleyballPositions └── volleyballPositinos.js ├── 105-starRotation └── starRotation.js ├── 106-sudoku └── sudoku.js ├── 107-minesweeper └── minesweeper.js ├── 108-boxBlur └── boxBlur.js ├── 109-contoursShifting └── contourShifting.js ├── 11-extraNumber └── extraNumber.js ├── 110-polygonPerimeter └── polygonPerimeter.js ├── 111-gravitation └── gravitation.js ├── 112-isInformationConsistent └── isInformationConsistent.js ├── 113-correctNanogram └── correctNanogram.js ├── 114-shuffledArray └── shuffledArray.js ├── 115-sortByHeight └── sortByHeight.js ├── 116-sortByLength └── sortByLength.js ├── 117-boxesPacking └── boxesPacking.js ├── 118-maximumSum └── maximumSum.js ├── 119-rowsRearranging └── rowsRearranging.js ├── 12-isInfiniteProcess └── isInfiniteProcess.js ├── 120-digitDifferenceSort └── digitDifferenceSort.js ├── 121-uniqueDigitProducts └── uniqueDigitProducts.js ├── 122-bishopAndPawn └── bishopAndPawn.js ├── 123-chessKnightMoves └── chessKnightMoves.js ├── 124-bishopDiagonal └── bishopDiagonal.js ├── 125-whoseTurn └── whoseTurn.js ├── 126-chessBishopDream └── chessBishopDream.js ├── 127-chessTriangle └── chessTriangle.js ├── 128-amazonCheckmate └── amazonCheckmate.js ├── 129-pawnRace └── pawnRace.js ├── 13-arthimeticExpression └── arthimeticExpression.js ├── 130-validTime └── validTimie.js ├── 131-videoPart └── videoPart.js ├── 132-dayOfWeek └── dayOfWeek.js ├── 133-curiousClock └── curiousClock.js ├── 134-newYearCelebrations └── newYearCelebrations.js ├── 135-regularMonths └── regularMonths.js ├── 136-missedClasses └── missedClasses.js ├── 137-holiday └── holiday.js ├── 138-isSentenceCorrect └── isSentenceCorrect.js ├── 139-replaceAllDigitsRegEx └── replaceAllDigitsRegEx.js ├── 14-tennisSet └── tennisSet.js ├── 140-swapAdjacentWords └── swapAdjacentWords.js ├── 141-nthNumber └── nthNumber.js ├── 142-isSubsequence └── isSubsequence.js ├── 143-eyeRhyme └── eyeRhyme.js ├── 144-programTranslation └── programTranslation.js ├── 145-repetitionEncryption └── repetitionEncryption.js ├── 146-bugsAndBugFixes └── bugsAndBugFixes.js ├── 147-LRCAndSubRip └── LRCAndSubRip.js ├── 148-HTMLTable └── HTMLTable.js ├── 149-chessNotation └── chessNotation.js ├── 15-willYou └── willYou.js ├── 150-cellsJoining └── cellsJoining.js ├── 151-firstOperationalCharacter └── firstOperationalCharacter.js ├── 152-countElements └── countElements.js ├── 153-treeBottom └── treeBottom.js ├── 154-befunge └── befunge.js ├── 155-pipesGame └── pipesGame.js ├── 156-game2048 └── game2048.js ├── 157-snakeGame └── snakeGame.js ├── 158-tetrisGame └── pipesGame.js ├── 159-pyraminxPuzzle └── pyraminxPuzzle.js ├── 16-metroCard └── metroCard.js ├── 160-linesGame └── linesGame.js ├── 161-fractal └── fractal.js ├── 162-timeASCIIRepresentation └── timeASCIIRepresentation.js ├── 17-killKthBit └── killKthBit.js ├── 18-arrayPacking └── arrayPacking.js ├── 19-rangeBitCount └── rangeBitCount.js ├── 20-mirrorBits └── mirrorBits.js ├── 21-secondRightMostZeroBit └── secondRightMostZeroBit.js ├── 22-swapAdjacentBit └── swapAdjacentBit.js ├── 23-differentRightmostBit └── differentRightMostBit.js ├── 24-equalPairOfBits └── equalPairOfBits.js ├── 25-leastFactorial └── leastFactorial.js ├── 26-countSumOfTwoRepresentations2 └── countSumOfTwoRepresentations2.js ├── 27-magicWell └── magicWell.js ├── 28-lineUp └── lineUp.js ├── 29-additionWithoutCarrying └── additionWithoutCarrying.js ├── 30-appleBoxes └── appleBoxes.js ├── 31-increaseNumberRoundness └── increaseNumberRoundness.js ├── 32-Rounders └── rounders.js ├── 33-candles └── candles.js ├── 34-countBlackCells └── countBlackCells.js ├── 35-createArray └── createArray.js ├── 36-arrayReplace └── arrayReplace.js ├── 37-firstReverseTry └── firstReverseTry.js ├── 38-concatanateArrays └── concatanateArrays.js ├── 39-removeArrayPart └── removeArrayPart.js ├── 40-isSmooth └── isSmooth.js ├── 41-replaceMiddle └── replaceMiddle.js ├── 42-makeArrayConsecutive2 └── makeArrayConsecutive2.js ├── 43-isPower └── isPower.js ├── 44-isSumOfConsecutive2 └── isSumOfConsecutive2.js ├── 45-squareDigitsSequence └── squareDigitsSequence.js ├── 46-pagesNumberingWithInk └── pagesNumberingWithInk.js ├── 47-comfortableNumbers └── comfortableNumbers.js ├── 48-weakNumbers └── weakNumbers.js ├── 49-rectangleRotation └── rectangleRotation.js ├── 50-crosswordFormations └── crosswordFormations.js ├── 51-encloseInBrackets └── encloseInBrackets.js ├── 52-properNounCorrection └── properNounCorrection.js ├── 53-isTandemRepeat └── isTandemRepeat.js ├── 54-isCaseInsensitivePallindrome └── crosswordFormations.js ├── 55-findEmailDomain └── findEmailDomain.js ├── 56-HTMLEndTagByStartTag └── HTMLEndTagByStartTag.js ├── 57-isMacAddress └── isMacAddress.js ├── 58-isUnstablePair └── isUnstablePair.js ├── 59-stringsConcentration └── stringsConcentration.js ├── 60-isSubstitutionCipher └── isSubstitutionCipher.js ├── 61-createAnagram └── createAnagram.js ├── 62-constructSquare └── constructSquare.js ├── 63-numbersGrouping └── numbersGrouping.js ├── 64-differentSquares └── differentSquares.js ├── 65-mostFrequentDigitSum └── mostFrequestDigitSum.js ├── 66-numberOfClans └── numberOfClans.js ├── 67-houseNumbersSum └── houseNumbersSum.js ├── 68-allLongestStrings └── allLongestStrings.js ├── 69-houseOfCats └── houseOfCats.js ├── 70-alphabetSequence └── alphabetSequence.js ├── 71-minimumNumberOfcoins └── minimumNumberOfcoins.js ├── 72-addBorder └── addBorder.js ├── 73-switchLights └── switchLights.js ├── 74-timedReading └── timedReading.js ├── 75-electionsWinner └── electionsWinner.js ├── 76-integerToStringOfFixedLength └── integerToStringOfFixedLength.js ├── 77-areSimilar └── areSimilar.js ├── 78-adaNumber └── adaNumber.js ├── 79-threeSplit └── threeSplit.js ├── 80-characterParity └── characterParity.js ├── 81-reflectString └── reflectString.js ├── 82-newNumeralSystem └── newNumeralSystem.js ├── 83-cipher26 └── cipher26.js ├── 84-stolenLunch └── stolenLunch.js ├── 85-higherVersion └── higherVersion.js ├── 86-decipher └── decipher.js ├── 87-alphaneumericLess └── alphaneumericLess.js ├── 88-arrayConversion └── arrayConversion.js ├── 89-arrayPreviousLess └── arrayPreviousLess.js ├── 90-pariOfShoes └── pairOfShoes.js ├── 91-combs └── combs.js ├── 92-stringsCrossover └── stringsCrossover.js ├── 93-cyclicStrings └── cyclicString.js ├── 94-beautifulTexts └── beautifulTexts.js ├── 95-runnersMeetings └── runnersMeetings.js ├── 96-christmasTree └── christmasTree.js ├── 97-fileNaming └── fileNaming.js ├── 98-extractMaximumColumn └── extractMaximumColumn.js └── 99-areIsomorphic └── areIsomorphic.js /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" 4 | 5 | env: 6 | - version="1.0.0" 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Codesignal-Solutions 2 | Solutions to code signal problems. 3 | -------------------------------------------------------------------------------- /databases/01-projectList/projectList.js: -------------------------------------------------------------------------------- 1 | /* Question : Your boss wants to identify the successful projects running in your company, so he asked you to prepare a list of all the currently active projects 2 | and their average monthly income. 3 | 4 | You have stored the information about these projects in a simple database with a single Projects table that has five columns: 5 | 6 | internal_id: the company's internal identifier for the project; 7 | project_name: the official name of the project; 8 | team_size: the number of employees working on the project; 9 | team_lead: the name of the project manager; 10 | income: the average monthly income of the project. 11 | Your boss says that internal project ids are irrelevant to him and that he isn't interested in how big the teams are. Since that's the case, he wants you to 12 | create another table by removing the internal_id and team_size columns from the existing Projects table. Return it sorted by internal_id in ascending order. */ 13 | 14 | // URL : https://app.codesignal.com/arcade/db/welcome-to-the-table/RXErLMFkXFkM4MpYY 15 | 16 | CREATE PROCEDURE solution() 17 | BEGIN 18 | SELECT project_name, team_lead, income FROM Projects ORDER BY internal_id; 19 | END -------------------------------------------------------------------------------- /intro/01-add/add.js: -------------------------------------------------------------------------------- 1 | /* Question : Write a function that returns the sum of two numbers. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-1/jwr339Kq6e3LQTsfa 4 | 5 | function add(param1, param2) { 6 | return param1 + param2; 7 | } 8 | 9 | exports.add = add; 10 | -------------------------------------------------------------------------------- /intro/01-add/add.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var add = require('./add').add; 3 | 4 | describe('add', function(){ 5 | function testCondition(param1, param2, sum) { 6 | it(`adds two parameters ${param1},${param2} and returns ${sum}`, function() { 7 | assert.equal(add(param1,param2), sum); 8 | }); 9 | } 10 | let testCases = [[1,2,3], [0,1000,1000], [2,-39,-37], [99,100,199], [-100,100,0], [-1000,-1000,-2000]]; 11 | testCases.forEach(element => testCondition(...element)); 12 | }); 13 | -------------------------------------------------------------------------------- /intro/02-centuryFromYear/centuryFromYear.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a year, return the century it is in. 2 | The first century spans from the year 1 up to and including the year 100, 3 | the second - from the year 101 up to and including the year 200, etc. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/intro/level-1/egbueTZRRL5Mm4TXN 6 | 7 | function centuryFromYear(year) { 8 | return Math.ceil(year/100); 9 | } 10 | 11 | exports.centuryFromYear = centuryFromYear; 12 | 13 | -------------------------------------------------------------------------------- /intro/02-centuryFromYear/centuryFromYear.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var centuryFromYear = require('./centuryFromYear').centuryFromYear; 3 | 4 | describe('Century from given year.', function(){ 5 | function testCondition(year, century) { 6 | it(`Century of ${year} is ${century}`, function() { 7 | assert.equal(centuryFromYear(year), century); 8 | }); 9 | } 10 | let testCases = [[1905, 20], [1700, 17], [1988, 20], [2000, 20], [2001, 21], [200, 2], 11 | [374, 4], [45, 1], [8,1]]; 12 | testCases.forEach(element => testCondition(...element)); 13 | }); 14 | -------------------------------------------------------------------------------- /intro/03-checkPalindrome/checkPalindrome.js: -------------------------------------------------------------------------------- 1 | /* Q: Given the string, check if it is a palindrome. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-1/s5PbmwxfECC52PWyQ/ 4 | 5 | function checkPalindrome(inputString) { 6 | return inputString === inputString.split("").reverse().join(""); 7 | } 8 | 9 | exports.checkPalindrome = checkPalindrome; 10 | -------------------------------------------------------------------------------- /intro/03-checkPalindrome/checkPalindrome.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var checkPalindrome = require('./checkPalindrome').checkPalindrome; 3 | 4 | describe('Check if the given string is Palindrome.', function(){ 5 | function testCondition(inputString, result) { 6 | it(`${inputString} is a ${result ? '' : 'not a'} Palindrome`, function() { 7 | assert.equal(checkPalindrome(inputString), result); 8 | }); 9 | } 10 | let testCases = [['aabaa', true], ['abac', false], ['a', true], ['az', false], 11 | ['abacaba', true], ['z', true], ['aaabaaaa', false], 12 | ['zzzazzazz', false], ['hlbeeykoqqqqokyeeblh', true], ['hlbeeykoqqqokyeeblh', true]]; 13 | testCases.forEach(element => testCondition(...element)); 14 | }); 15 | -------------------------------------------------------------------------------- /intro/04-adjacentElementsproduct/adjacentElementsProduct.js: -------------------------------------------------------------------------------- 1 | /* Q: Given an array of integers, find the pair of adjacent elements that 2 | has the largest product and return that product. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/intro/level-2/xzKiBHjhoinnpdh6m/ 5 | 6 | function adjacentElementsProduct(inputArray) { 7 | let greatestProduct = inputArray[0] * inputArray[1]; 8 | for (let i = 1; i testCondition(...element)); 14 | }); 15 | -------------------------------------------------------------------------------- /intro/05-shapeArea/shapeArea.js: -------------------------------------------------------------------------------- 1 | /* Q: Below we will define an n-interesting polygon. 2 | Your task is to find the area of a polygon for a given n. 3 | 4 | A 1-interesting polygon is just a square with a side of length 1. 5 | An n-interesting polygon is obtained by taking the n - 1-interesting 6 | polygon and appending 1-interesting polygons to its rim, side by side. 7 | 1-, 2-, 3- and 4-interesting polygons can be found at the link below. */ 8 | 9 | // URL : https://app.codesignal.com/arcade/intro/level-2/yuGuHvcCaFCKk56rJ 10 | 11 | function shapeArea(n) { 12 | let area = 1; 13 | for (let i=1; i<=n; i++) { 14 | area += i*2 + (i-2)*2 15 | } 16 | return area; 17 | } 18 | 19 | exports.shapeArea = shapeArea; 20 | -------------------------------------------------------------------------------- /intro/05-shapeArea/shapeArea.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var shapeArea = require('./shapeArea').shapeArea; 3 | 4 | describe('Area of the given shape.', function(){ 5 | function testCondition(shape, area) { 6 | it(`Area of ${shape}-interesting polygon is ${area}`, function() { 7 | assert.equal(shapeArea(shape), area); 8 | }); 9 | } 10 | let testCases = [[2,5], [3, 13], [1, 1], [5, 41], [7000, 97986001], [8000, 127984001], 11 | [9999, 199940005], [9998, 199900013], [8999,161946005]]; 12 | testCases.forEach(element => testCondition(...element)); 13 | }); 14 | -------------------------------------------------------------------------------- /intro/06-makeArrayConsecutive2/makeArrayConsecutive2.js: -------------------------------------------------------------------------------- 1 | /* Q: Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, 2 | each statue having an non-negative integer size. Since he likes to make things perfect, 3 | he wants to arrange them from smallest to largest so that each statue will be bigger 4 | than the previous one exactly by 1. He may need some additional statues to be able to 5 | accomplish that. Help him figure out the minimum number of additional statues needed. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/intro/level-2/bq2XnSr5kbHqpHGJC 8 | 9 | function makeArrayConsecutive2(statues) { 10 | return Math.max(...statues) - Math.min(...statues) - statues.length + 1 11 | } 12 | 13 | exports.makeArrayConsecutive2 = makeArrayConsecutive2 14 | -------------------------------------------------------------------------------- /intro/06-makeArrayConsecutive2/makeArrayConsecutive2.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var makeArrayConsecutive2 = require('./makeArrayConsecutive2').makeArrayConsecutive2; 3 | 4 | describe('Make array consecutive.', function(){ 5 | function testCondition(arr, elemsRequired) { 6 | it(`Array ${arr} will be consecutive with ${elemsRequired} more elements`, function() { 7 | assert.equal(makeArrayConsecutive2(arr), elemsRequired); 8 | }); 9 | } 10 | let testCases = [[[6, 2, 3, 8], 3], [[0, 3], 2], [[5, 4, 6], 0], [[6, 3], 2], [[1], 0]]; 11 | testCases.forEach(element => testCondition(...element)); 12 | }); 13 | -------------------------------------------------------------------------------- /intro/07-almostIncreasingSequence/almostIncreasingSequence.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a sequence of integers as an array, determine whether it is possible 2 | to obtain a strictly increasing sequence by removing no more than one element from the array. 3 | 4 | Note: sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. 5 | Sequence containing only one element is also considered to be strictly increasing. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/intro/level-2/2mxbGwLzvkTCKAJMG 8 | 9 | function almostIncreasingSequence(sequence) { 10 | nonSyncElement = 0; 11 | for (var a=0; a testCondition(...element)); 13 | }); 14 | -------------------------------------------------------------------------------- /intro/08-matrixElementsSum/matrixElementsSum.js: -------------------------------------------------------------------------------- 1 | /* Q: After becoming famous, the CodeBots decided to move into a new building together. 2 | Each of the rooms has a different cost, and some of them are free, but there's a 3 | rumour that all the free rooms are haunted! Since the CodeBots are quite superstitious, 4 | they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms. 5 | Given matrix, a rectangular matrix of integers, where each value represents the cost of 6 | the room, your task is to return the total sum of all rooms that are suitable 7 | for the CodeBots (ie: add up all the values that don't appear below a 0). */ 8 | 9 | // URL : https://app.codesignal.com/arcade/intro/level-2/xskq4ZxLyqQMCLshr 10 | 11 | function matrixElementsSum(matrix) { 12 | hauntedColumns = [] 13 | totalCost = 0 14 | matrix.forEach((arr) => { 15 | arr.forEach((elem, pos ) => { 16 | if (elem == 0) hauntedColumns.push(pos); 17 | if (!hauntedColumns.includes(pos)) totalCost += elem; 18 | }); 19 | }); 20 | return totalCost; 21 | } 22 | 23 | exports.matrixElementsSum = matrixElementsSum; 24 | -------------------------------------------------------------------------------- /intro/08-matrixElementsSum/matrixElementsSum.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var matrixElementsSum = require('./matrixElementsSum').matrixElementsSum; 3 | 4 | describe('Matrix Elements Sum.', function(){ 5 | function testCondition(arr, matrixElemsSum) { 6 | it(`Matrix Elements Sum is ${matrixElemsSum}.`, function() { 7 | assert.equal(matrixElementsSum(arr), matrixElemsSum); 8 | }); 9 | } 10 | let testCases = [[[[0,1,1,2], [0,5,0,0], [2,0,3,3]], 9], [[[1,1,1,0], [0,5,0,1], [2,1,3,10]], 9], 11 | [[[1,1,1], [2,2,2], [3,3,3]], 18]]; 12 | testCases.forEach(element => testCondition(...element)); 13 | }); 14 | -------------------------------------------------------------------------------- /intro/09-allLongestStrings/allLongestStrings.js: -------------------------------------------------------------------------------- 1 | /* Q: Given an array of strings, return another array containing all of its longest strings. 2 | Example 3 | For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be 4 | allLongestStrings(inputArray) = ["aba", "vcd", "aba"]. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-3/fzsCQGYbxaEcTr2bL 7 | 8 | function allLongestStrings(inputArray) { 9 | arr = [inputArray[0]]; 10 | inputArray.forEach(element => { 11 | if (arr[0].length < element.length ) { 12 | arr = [element] 13 | } else if (arr[0].length == element.length) { 14 | arr.push(element) 15 | } 16 | }); 17 | return arr[0] == inputArray[0] ? arr.slice(1) : arr 18 | } 19 | 20 | exports.allLongestStrings = allLongestStrings; -------------------------------------------------------------------------------- /intro/09-allLongestStrings/allLongestStrings.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var allLongestStrings = require('./allLongestStrings').allLongestStrings; 3 | 4 | describe('All Longest Strings', function(){ 5 | function testCondition(inputArray, arr) { 6 | it(`Array with all longest strings is ${arr}`, function() { 7 | assert.deepEqual(allLongestStrings(inputArray), arr); 8 | }); 9 | } 10 | let testCases = [[["aba", "aa", "ad", "vcd", "aba"], ["aba", "vcd", "aba"]], 11 | [['aa'], ['aa']], [["abc", "eeee", "abcd", "dcd"], 12 | ["eeee", "abcd"]]]; 13 | testCases.forEach(element => testCondition(...element)); 14 | }); 15 | -------------------------------------------------------------------------------- /intro/10-commonCharacterCount/commonCharacterCount.js: -------------------------------------------------------------------------------- 1 | /* Q: Given two strings, find the number of common characters between them. 2 | Example 3 | For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3. 4 | Strings have 3 common characters - 2 "a"s and 1 "c". */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-3/JKKuHJknZNj4YGL32 7 | 8 | function commonCharacterCount(s1, s2) { 9 | let arr1 = s1.split(''), arr2 = s2.split(''); 10 | commonCharCount = 0; 11 | if (arr1.length > arr2.length) { 12 | arr2.forEach(element => 13 | {if (arr1.indexOf(element) > -1 && arr1.splice(arr1.indexOf(element), 1)) commonCharCount += 1 }) 14 | } else { 15 | arr1.forEach(element => {if (arr2.indexOf(element) > -1 && arr2.splice(arr2.indexOf(element), 1)) commonCharCount += 1}) 16 | } 17 | return commonCharCount; 18 | } 19 | 20 | 21 | exports.commonCharacterCount = commonCharacterCount; 22 | -------------------------------------------------------------------------------- /intro/10-commonCharacterCount/commonCharacterCount.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var commonCharacterCount = require('./commonCharacterCount').commonCharacterCount; 3 | 4 | describe('Common Character Count.', function(){ 5 | function testCondition(inputArray, res) { 6 | it(`Common Character count is ${res}`, function() { 7 | assert.deepEqual(commonCharacterCount(...inputArray), res); 8 | }); 9 | } 10 | let testCases = [[["aabcc", "adcaa"], 3], [["zzzz", "zzzzzzz"], 4], [["abca", "xyzbac"], 3]]; 11 | testCases.forEach(element => testCondition(...element)); 12 | }); 13 | -------------------------------------------------------------------------------- /intro/11-isLucky/isLucky.js: -------------------------------------------------------------------------------- 1 | /* Q: Ticket numbers usually consist of an even number of digits. 2 | A ticket number is considered lucky if the sum of the first half 3 | of the digits is equal to the sum of the second half. 4 | 5 | Given a ticket number n, determine if it's lucky or not. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/intro/level-3/3AdBC97QNuhF6RwsQ/ 8 | 9 | function isLucky(n) { 10 | let count = 0; 11 | n = Array.from(String(n), Number); 12 | n.forEach( (el, i) => { (i < n.length / 2) ? count += el : count -= el }); 13 | return count == 0; 14 | } 15 | 16 | exports.isLucky = isLucky; 17 | -------------------------------------------------------------------------------- /intro/11-isLucky/isLucky.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var isLucky = require('./isLucky').isLucky; 3 | 4 | describe('Common Character Count.', function(){ 5 | function testCondition(input, res) { 6 | it(`${input} is ${res ? 'not ' : ''}Lucky`, function() { 7 | assert.deepEqual(isLucky(input), res); 8 | }); 9 | } 10 | let testCases = [[1230, true], [239017, false], [134008, true]]; 11 | testCases.forEach(element => testCondition(...element)); 12 | }); -------------------------------------------------------------------------------- /intro/12-sortByHeight/sortByHeight.js: -------------------------------------------------------------------------------- 1 | /* Q: Some people are standing in a row in a park. There are trees between 2 | them which cannot be moved. Your task is to rearrange the people by their 3 | heights in a non-descending order without moving the trees. People can be very tall! */ 4 | 5 | // URL : https://app.codesignal.com/arcade/intro/level-3/D6qmdBL2NYz49XHwM 6 | 7 | function sortByHeight(a) { 8 | let sorted = a.filter(elem => elem > 0).sort((el1, el2) => el1 - el2); 9 | return a.map(el => el > 0 ? sorted.shift() : -1 ) 10 | } 11 | 12 | exports.sortByHeight = sortByHeight; -------------------------------------------------------------------------------- /intro/12-sortByHeight/sortByHeight.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var sortByHeight = require('./sortByHeight').sortByHeight; 3 | 4 | describe('Sort By Height.', function(){ 5 | function testCondition(input, res) { 6 | it(`${res} is sorted by height.`, function() { 7 | assert.deepEqual(sortByHeight(input), res); 8 | }); 9 | } 10 | let testCases = [[[-1, 150, 190, 170, -1, -1, 160, 180], [-1, 150, 160, 170, -1, -1, 180, 190]], 11 | [[-1, -1, -1, -1, -1], [-1, -1, -1, -1, -1]], [[-1], [-1]]]; 12 | testCases.forEach(element => testCondition(...element)); 13 | }); -------------------------------------------------------------------------------- /intro/13-reverseInParentheses/reverseInParentheses.js: -------------------------------------------------------------------------------- 1 | /* Q: Write a function that reverses characters in (possibly nested) parentheses in the input string. 2 | Input strings will always be well-formed with matching ()s. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/intro/level-3/9DgaPsE2a7M6M2Hu6 5 | 6 | function reverseInParentheses(inputString) { 7 | if (inputString.match(/\([a-z]*\)/)) { 8 | return reverseInParentheses(inputString.replace(/\([a-z]*\)/, 9 | Array.from(inputString.match(/\([a-z]*\)/)[0].replace(/\(|\)/g,'')).reverse().join(''))); 10 | } 11 | else return inputString; 12 | } 13 | 14 | exports.reverseInParentheses = reverseInParentheses; 15 | -------------------------------------------------------------------------------- /intro/13-reverseInParentheses/reverseInParentheses.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var reverseInParentheses = require('./reverseInParentheses').reverseInParentheses; 3 | 4 | describe('Reverse in Parentheses.', function(){ 5 | function testCondition(input, res) { 6 | it(`${res} is reversed in parentheses.`, function() { 7 | assert.equal(reverseInParentheses(input), res); 8 | }); 9 | } 10 | let testCases = [["(bar)", "rab"], ["foo(bar)baz", "foorabbaz"], ["foo(bar)baz(blim)", "foorabbazmilb"]]; 11 | testCases.forEach(element => testCondition(...element)); 12 | }); -------------------------------------------------------------------------------- /intro/14-alternatingSums/alternatingSums.js: -------------------------------------------------------------------------------- 1 | /* Q: Several people are standing in a row and need to be divided into two teams. 2 | The first person goes into team 1, the second goes into team 2, the third goes 3 | into team 1 again, the fourth into team 2, and so on. 4 | 5 | You are given an array of positive integers - the weights of the people. 6 | Return an array of two integers, where the first element is the total weight of team 1, 7 | and the second element is the total weight of team 2 after the division is complete. */ 8 | 9 | // URL : https://app.codesignal.com/arcade/intro/level-4/cC5QuL9fqvZjXJsW9 10 | 11 | function alternatingSums(a) { 12 | res = [0, 0] 13 | a.map((el, index) => index%2 == 0 ? res[0] += el : res[1] += el) 14 | return res 15 | } 16 | 17 | exports.alternatingSums = alternatingSums; 18 | -------------------------------------------------------------------------------- /intro/14-alternatingSums/alternatingSums.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var alternatingSums = require('./alternatingSums').alternatingSums; 3 | 4 | describe('Alternating Sums.', function(){ 5 | function testCondition(input, res) { 6 | it(`Alternating sum of ${input} is ${res}`, function() { 7 | assert.deepEqual(alternatingSums(input), res); 8 | }); 9 | } 10 | let testCases = [[[50, 60, 60, 45, 70],[180, 105]], [[100, 50], [100, 50]], [[80], [80, 0]]]; 11 | testCases.forEach(element => testCondition(...element)); 12 | }); 13 | -------------------------------------------------------------------------------- /intro/15-addBorder/addBorder.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a rectangular matrix of characters, add a border of asterisks(*) to it. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-4/ZCD7NQnED724bJtjN 4 | 5 | function addBorder(picture) { 6 | picture.push('*'.repeat(picture[0].length)) 7 | picture.unshift('*'.repeat(picture[0].length)) 8 | return picture.map(el => `*${el}*`) 9 | } 10 | 11 | exports.addBorder = addBorder; 12 | -------------------------------------------------------------------------------- /intro/15-addBorder/addBorder.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var addBorder = require('./addBorder').addBorder; 3 | 4 | describe('Add Border.', function(){ 5 | function testCondition(inputArray, res) { 6 | it(`Given array with border is ${res}`, function() { 7 | assert.deepEqual(addBorder(inputArray), res); 8 | }); 9 | } 10 | let testCases = [[["abc", "ded"], ["*****", "*abc*", "*ded*", "*****"]], 11 | [["a"], ["***", "*a*", "***"]]]; 12 | testCases.forEach(element => testCondition(...element)); 13 | }); 14 | -------------------------------------------------------------------------------- /intro/16-areSimilar/areSimilar.js: -------------------------------------------------------------------------------- 1 | /* Q: Two arrays are called similar if one can be obtained from another by 2 | swapping at most one pair of elements in one of the arrays. 3 | 4 | Given two arrays a and b, check whether they are similar. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-4/xYXfzQmnhBvEKJwXP 7 | 8 | function areSimilar(a, b) { 9 | res = a.map((e,i)=> e==b[i] ? null : e).filter(Boolean).length 10 | hasSameElements = JSON.stringify(a.sort((a, b) => a - b)) == JSON.stringify(b.sort((a, b) => a - b)) 11 | return hasSameElements && (res == 2 || res == 0) 12 | } 13 | 14 | exports.areSimilar = areSimilar; 15 | -------------------------------------------------------------------------------- /intro/16-areSimilar/areSimilar.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var areSimilar = require('./areSimilar').areSimilar; 3 | 4 | describe('Are similar arrays?', function(){ 5 | function testCondition(input, res) { 6 | it(`Given are ${res ? '' : 'not '}Similar arrays. `, function() { 7 | assert.equal(areSimilar(...input), res); 8 | }); 9 | } 10 | let testCases = [[[[1, 2, 3],[1, 2, 3]], true], [[[1, 2, 3],[2,1,3]], true], [[[1, 2, 2],[2, 1, 1]], false]]; 11 | testCases.forEach(element => testCondition(...element)); 12 | }); 13 | -------------------------------------------------------------------------------- /intro/17-arrayChange/arrayChange.js: -------------------------------------------------------------------------------- 1 | /* Q: You are given an array of integers. On each move you are allowed to increase exactly 2 | one of its element by one. Find the minimal number of moves required to obtain a strictly 3 | increasing sequence from the input. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/intro/level-4/xvkRbxYkdHdHNCKjg 6 | 7 | function arrayChange(inputArray) { 8 | moves = 0; 9 | for(i=0; i testCondition(...element)); 13 | }); 14 | -------------------------------------------------------------------------------- /intro/18-palindromeRearranging/palindromeRearranging.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a string, find out if its characters can be rearranged to form a palindrome. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-4/Xfeo7r9SBSpo3Wico 4 | 5 | function palindromeRearranging(inputString) { 6 | return [...new Set(inputString)].map(i=>inputString.split("").filter(j=>j==i).length%2).reduce((x,y)=>x+y)<=1 7 | } 8 | 9 | exports.palindromeRearranging = palindromeRearranging; 10 | -------------------------------------------------------------------------------- /intro/18-palindromeRearranging/palindromeRearranging.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/18-palindromeRearranging/palindromeRearranging.spec.js -------------------------------------------------------------------------------- /intro/19-areEquallyStrong/areEquallyStrong.js: -------------------------------------------------------------------------------- 1 | /* Q: Call two arms equally strong if the heaviest weights they each are able to lift are equal. 2 | Call two people equally strong if their strongest arms are equally strong (the strongest arm 3 | can be both the right and the left), and so are their weakest arms. 4 | Given your and your friend's arms' lifting capabilities find out if you two are equally strong.*/ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-5/g6dc9KJyxmFjB98dL 7 | 8 | function areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight) { 9 | return yourLeft+yourRight === friendsLeft+friendsRight && (yourLeft === friendsLeft || yourLeft === friendsRight); 10 | } 11 | 12 | exports.areEquallyStrong = areEquallyStrong; 13 | -------------------------------------------------------------------------------- /intro/20-arrayMaximalAdjacentDifference/arrayMaximalAdjacentDifference.js: -------------------------------------------------------------------------------- 1 | /* Q: Given an array of integers, find the maximal absolute difference between any two of 2 | its adjacent elements.*/ 3 | 4 | // URL : https://app.codesignal.com/arcade/intro/level-5/EEJxjQ7oo7C5wAGjE 5 | 6 | function arrayMaximalAdjacentDifference(inputArray) { 7 | return Math.max(...inputArray.slice(1).map((x,i)=>Math.abs(x-inputArray[i]))) 8 | } 9 | 10 | exports.arrayMaximalAdjacentDifference = arrayMaximalAdjacentDifference; 11 | -------------------------------------------------------------------------------- /intro/21-isIPv4Address/isIPv4Address.js: -------------------------------------------------------------------------------- 1 | /* Q: An IP address is a numerical label assigned to each device (e.g., computer, printer) participating 2 | in a computer network that uses the Internet Protocol for communication. There are two versions of 3 | the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address. 4 | Given a string, find out if it satisfies the IPv4 address naming rules. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-5/veW5xJednTy4qcjso 7 | 8 | function isIPv4Address(inputString) { 9 | var s = inputString.split(".") 10 | return s.length===4&&s.every(x=>x!=""&&!isNaN(x)&&x>=0&&x<256) 11 | } 12 | 13 | exports.isIPv4Address = isIPv4Address; 14 | -------------------------------------------------------------------------------- /intro/22-avoidObstacles/avoidObstacles.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a string, find out if its characters can be rearranged to form a palindrome. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-4/Xfeo7r9SBSpo3Wico 4 | 5 | function avoidObstacles(inputArr) { 6 | for(var n=1;;n++) if(inputArr.every(x=>x%n)) return n 7 | } 8 | 9 | exports.avoidObstacles = avoidObstacles; 10 | -------------------------------------------------------------------------------- /intro/22-avoidObstacles/avoidObstacles.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var avoidObstacles = require('./avoidObstacles').avoidObstacles; 3 | 4 | describe('How many Moves?', function(){ 5 | function testCondition(input, res) { 6 | it(`Moves needed are ${res ? '' : 'not '} `, function() { 7 | console.log(res) 8 | assert.equal(avoidObstacles(input), res); 9 | }); 10 | } 11 | let testCases = [[[5, 3, 6, 7, 9],4], [[2, 3],4], [[1, 4, 10, 6, 2],7]]; 12 | testCases.forEach(element => testCondition(...element)); 13 | }); 14 | -------------------------------------------------------------------------------- /intro/23-boxBlur/boxBlur.js: -------------------------------------------------------------------------------- 1 | /* Q: Last night you partied a little too hard. Now there's a black and white photo of you that's about to go viral! You can't let this ruin your reputation, so you want to apply the box blur algorithm to the photo to hide its content. 2 | The pixels in the input image are represented as integers. The algorithm distorts the input image in the following way: Every pixel x in the output image has a value equal to the average value of the pixel values from the 3 × 3 square that has its center at x, including x itself. All the pixels on the border of x are then removed. 3 | Return the blurred image as an integer, with the fractions rounded down. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/intro/level-5/5xPitc3yT3dqS7XkP 6 | 7 | function boxBlur(image) { 8 | 9 | let arr = []; 10 | 11 | for (let y = 0; y < image.length - 2; y++) { 12 | let line = []; 13 | for (let x = 0; x < image[y].length - 2; x++) { 14 | let sum = 0; 15 | for (let a = y; a < y + 3; a++) { 16 | for (let b = x; b < x + 3; b++) { 17 | sum += image[a][b]; 18 | } 19 | } 20 | line.push(Math.floor(sum / 9)); 21 | } 22 | arr.push(line); 23 | } 24 | return arr; 25 | } 26 | 27 | exports.boxBlur = boxBlur; 28 | -------------------------------------------------------------------------------- /intro/23-boxBlur/boxBlur.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var boxBlur = require('./boxBlur').boxBlur; 3 | 4 | describe('Box Blur.', function(){ 5 | function testCondition(inputArray, res) { 6 | it(`Given image to blur is ${res}`, function() { 7 | assert.deepEqual(boxBlur(inputArray), res); 8 | }); 9 | } 10 | let testCases = [ 11 | [ 12 | [[1,1,1], 13 | [1,7,1], 14 | [1,1,1]], 15 | [[1]] 16 | ], 17 | [ 18 | [[0,18,9], 19 | [27,9,0], 20 | [81,63,45]], 21 | [[28]] 22 | ], 23 | [ 24 | [[36,0,18,9], 25 | [27,54,9,0], 26 | [81,63,72,45]], 27 | [[40,30]] 28 | ], 29 | ]; 30 | testCases.forEach(element => testCondition(...element)); 31 | }); 32 | -------------------------------------------------------------------------------- /intro/24-mineSweeper/mineSweeper.js: -------------------------------------------------------------------------------- 1 | /* Q: In the popular Minesweeper game you have a board with some mines and those cells that don't contain a mine have a number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a Minesweeper game setup. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-5/ZMR5n7vJbexnLrgaM 4 | 5 | function mineSweeper(arr) { 6 | res = Array.from({length:arr.length},x=>Array.from({length:arr[0].length},x=>0)) 7 | for (i = 0; i < arr.length; i++) { 8 | for (j = 0; j < arr[i].length; j++) { 9 | if (arr[i][j]) { 10 | if (i-1 >= 0) { 11 | res[i-1][j]++ 12 | if (j-1 >= 0) {res[i-1][j-1]++} 13 | if (j+1 < arr[i].length) {res[i-1][j+1]++}} 14 | if (j-1 >= 0) {res[i][j-1]++} 15 | if (j+1 < arr[i].length) {res[i][j+1]++;} 16 | if (i+1 < arr.length) { 17 | res[i+1][j]++ 18 | if (j-1 >= 0) {res[i+1][j-1]++} 19 | if (j+1 < arr[i].length) {res[i+1][j+1]++}}}}} 20 | return res 21 | } 22 | 23 | exports.mineSweeper = mineSweeper; 24 | -------------------------------------------------------------------------------- /intro/24-mineSweeper/mineSweeper.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var mineSweeper = require('./mineSweeper').mineSweeper; 3 | 4 | describe('Box Blur.', function(){ 5 | function testCondition(inputArray, res) { 6 | it(`Given image to blur is ${res}`, function() { 7 | assert.deepEqual(mineSweeper(inputArray), res); 8 | }); 9 | } 10 | let testCases = [ 11 | [ 12 | [[true,false,false], 13 | [false,true,false], 14 | [false,false,false]], 15 | 16 | [[1,2,1], 17 | [2,1,1], 18 | [1,1,1]] 19 | ], 20 | [ 21 | [[false,false,false], 22 | [false,false,false]], 23 | 24 | [[0,0,0], 25 | [0,0,0]] 26 | ], 27 | [ 28 | [[true,false], 29 | [true,false], 30 | [false,true], 31 | [false,false], 32 | [false,false]], 33 | 34 | [[1,2], 35 | [2,3], 36 | [2,1], 37 | [1,1], 38 | [0,0]] 39 | ], 40 | ]; 41 | testCases.forEach(element => testCondition(...element)); 42 | }); 43 | -------------------------------------------------------------------------------- /intro/25-arrayReplace/arrayReplace.js: -------------------------------------------------------------------------------- 1 | /* Q:Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-6/mCkmbxdMsMTjBc3Bm 4 | 5 | function arrayReplace(inputArray, elemToReplace, substitutionElem) { 6 | for(var i = 0; i < inputArray.length; i++){ 7 | if (inputArray[i] == elemToReplace) 8 | inputArray[i] = substitutionElem 9 | } 10 | } 11 | 12 | exports.arrayReplace = arrayReplace; 13 | -------------------------------------------------------------------------------- /intro/25-arrayReplace/arrayReplace.spec.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var arrayReplace = require('./arrayReplace').arrayReplace; 3 | 4 | describe('Box Blur.', function(){ 5 | function testCondition(inputArray, res) { 6 | it(`Given image to blur is ${res}`, function() { 7 | assert.deepEqual(arrayReplace(inputArray), res); 8 | }); 9 | } 10 | let testCases = [ 11 | [ 12 | [[1, 2, 1], 1, 3], 13 | [3, 2, 3] 14 | ], 15 | [ 16 | [[1, 2, 1, 2, 1], 2, 2], 17 | [1, 2, 1, 2, 1] 18 | ], 19 | [ 20 | [[2, 1], 3, 9], 21 | [2, 1] 22 | ], 23 | ]; 24 | testCases.forEach(element => testCondition(...element)); 25 | }); 26 | -------------------------------------------------------------------------------- /intro/26-evenDigitsOnly/evenDigitsOnly.js: -------------------------------------------------------------------------------- 1 | /* Q: Check if all digits of the given integer are even. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-6/6cmcmszJQr6GQzRwW 4 | 5 | function evenDigitsOnly(n) { 6 | var array = String(n).split(''), flag = true 7 | for (var i = 0; i < array.length && flag; i++){ 8 | if (array[i] % 2 != 0) 9 | flag = false 10 | } 11 | return flag 12 | } 13 | 14 | exports.evenDigitsOnly = evenDigitsOnly; 15 | -------------------------------------------------------------------------------- /intro/26-evenDigitsOnly/evenDigitsOnly.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/26-evenDigitsOnly/evenDigitsOnly.spec.js -------------------------------------------------------------------------------- /intro/27-variableName/variableName.js: -------------------------------------------------------------------------------- 1 | /* Q: Correct variable names consist only of English letters, digits and underscores and they can't start with a digit. Check if the given string is a correct variable name. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-6/6Wv4WsrsMJ8Y2Fwno 4 | 5 | function variableName(n) { 6 | return /^[a-z_]\w*$/i.test(n) 7 | } 8 | 9 | exports.variableName = variableName; 10 | -------------------------------------------------------------------------------- /intro/27-variableName/variableName.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/27-variableName/variableName.spec.js -------------------------------------------------------------------------------- /intro/28-alphabeticShift/alphabeticShift.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-6/t97bpjfrMDZH8GJhi 4 | 5 | function alphabeticShift(inputString) { 6 | return inputString.split('').map(v => {return v=='z'?'a' : String.fromCharCode(v.charCodeAt(0)+1);}).join('') 7 | } 8 | 9 | 10 | exports.alphabeticShift = alphabeticShift; 11 | -------------------------------------------------------------------------------- /intro/28-alphabeticShift/alphabeticShift.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/28-alphabeticShift/alphabeticShift.spec.js -------------------------------------------------------------------------------- /intro/29-chessBoardCellColor/chessBoardCellColor.js: -------------------------------------------------------------------------------- 1 | /* Q: Given two cells on the standard chess board, determine whether they have the same color or not... */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-6/PWLT8GBrv9xXy4Dui 4 | 5 | function chessBoardCellColor(cell1, cell2) { 6 | return (cell1[0].charCodeAt(0) + 1 + +cell1[1]) % 2 === (cell2[0].charCodeAt(0) + 1 + +cell2[1]) % 2 7 | } 8 | 9 | 10 | exports.chessBoardCellColor = chessBoardCellColor; -------------------------------------------------------------------------------- /intro/29-chessBoardCellColor/chessBoardCellColor.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/29-chessBoardCellColor/chessBoardCellColor.spec.js -------------------------------------------------------------------------------- /intro/30-circleOfNumbers/circleOfNumbers.js: -------------------------------------------------------------------------------- 1 | /* Q: Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any two neighboring numbers is equal (note that 0 and n - 1 are neighboring, too). */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-7/vExYvcGnFsEYSt8nQ 4 | 5 | function circleOfNumbers(n, firstNumber) { 6 | return (n/2+firstNumber) % n; 7 | } 8 | 9 | 10 | exports.circleOfNumbers = circleOfNumbers; -------------------------------------------------------------------------------- /intro/30-circleOfNumbers/circleOfNumbers.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/30-circleOfNumbers/circleOfNumbers.spec.js -------------------------------------------------------------------------------- /intro/31-depositProfit/depositProfit.js: -------------------------------------------------------------------------------- 1 | /* Q: You have deposited a specific amount of money into your bank account. Each year your balance increases at the same growth rate. 2 | With the assumption that you don't make any additional deposits, find out how long it would take for your balance to pass a specific threshold. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/intro/level-7/8PxjMSncp9ApA4DAb 5 | 6 | function depositProfit(deposit, rate, threshold) { 7 | return Math.ceil(Math.log(threshold/deposit)/Math.log(rate/100+1)); 8 | } 9 | 10 | 11 | exports.depositProfit = depositProfit; -------------------------------------------------------------------------------- /intro/31-depositProfit/depositProfit.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/31-depositProfit/depositProfit.spec.js -------------------------------------------------------------------------------- /intro/32-absoluteValuesSumMinimization/absoluteValuesSumMinimization.js: -------------------------------------------------------------------------------- 1 | /* Q:Given a sorted array of integers a, your task is to determine which element of a is closest to all other values of a. In other words, find the element x in a, which minimizes the following sum: 2 | abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x) (where abs denotes the absolute value) 3 | 4 | If there are several possible answers, output the smallest one. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-7/ZFnQkq9RmMiyE6qtq 7 | 8 | function absoluteValuesSumMinimization(num) { 9 | return nums[Math.ceil(nums.length/2)-1]; 10 | } 11 | 12 | 13 | exports.absoluteValuesSumMinimization = absoluteValuesSumMinimization; -------------------------------------------------------------------------------- /intro/32-absoluteValuesSumMinimization/absoluteValuesSumMinimization.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/32-absoluteValuesSumMinimization/absoluteValuesSumMinimization.spec.js -------------------------------------------------------------------------------- /intro/33-stringsRearrangement/stringsRearrangement.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* Q: Given an array of equal-length strings, you'd like to know if it's possible to rearrange the order of the elements in such a way that each consecutive pair of strings differ by exactly one character. 4 | Return true if it's possible, and false if not. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-7/PTWhv2oWqd6p4AHB9 7 | 8 | function stringsRearrangement(num) { 9 | const foo = (d, inputArray) => { 10 | if (d === inputArray.length) { 11 | for (let i = 0; i < inputArray.length - 1; i++) { 12 | let c = 0; 13 | for (let j = 0; j < inputArray[i].length; j++) { 14 | if (inputArray[i][j] !== inputArray[i + 1][j]) c++; 15 | } 16 | if (c !== 1) return false; 17 | } 18 | return true; 19 | } 20 | for (let i = d; i < inputArray.length; i++) { 21 | [inputArray[d], inputArray[i]] = [inputArray[i], inputArray[d]]; 22 | if (foo(d + 1, inputArray)) return true; 23 | [inputArray[d], inputArray[i]] = [inputArray[i], inputArray[d]]; 24 | } 25 | return false; 26 | }; 27 | return foo(0, inputArray); 28 | } 29 | 30 | 31 | exports.stringsRearrangement = stringsRearrangement; -------------------------------------------------------------------------------- /intro/33-stringsRearrangement/stringsRearrangement.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/33-stringsRearrangement/stringsRearrangement.spec.js -------------------------------------------------------------------------------- /intro/34-extractEachKth/extractEachKth.js: -------------------------------------------------------------------------------- 1 | /* Q: Given array of integers, remove each kth element from it. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-8/3AgqcKrxbwFhd3Z3R 4 | 5 | function extractEachKth(inputArray, k) { 6 | return inputArray.filter((a, i)=>(i+1)%k !== 0) 7 | } 8 | 9 | 10 | exports.extractEachKth = extractEachKth; -------------------------------------------------------------------------------- /intro/34-extractEachKth/extractEachKth.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/34-extractEachKth/extractEachKth.spec.js -------------------------------------------------------------------------------- /intro/35-firstDigit/firstDigit.js: -------------------------------------------------------------------------------- 1 | /* Q: Find the leftmost digit that occurs in a given string. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-8/rRGGbTtwZe2mA8Wov 4 | 5 | function firstDigit(inputArray, k) { 6 | let i = 0; 7 | let num; 8 | while (parseInt(inputString[i]) != 0 && !parseInt(inputString[i])) { 9 | i += 1; 10 | } 11 | num = inputString[i]; 12 | return num; 13 | } 14 | 15 | 16 | exports.firstDigit = firstDigit; -------------------------------------------------------------------------------- /intro/35-firstDigit/firstDigit.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/35-firstDigit/firstDigit.spec.js -------------------------------------------------------------------------------- /intro/36-differentSymbolsNaive/differentSymbolsNaive.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a string, find the number of different characters in it. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-8/8N7p3MqzGQg5vFJfZ 4 | 5 | function differentSymbolsNaive(inputArray, k) { 6 | return (new Set(s.split(""))).size 7 | } 8 | 9 | 10 | exports.differentSymbolsNaive = differentSymbolsNaive; -------------------------------------------------------------------------------- /intro/36-differentSymbolsNaive/differentSymbolsNaive.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/36-differentSymbolsNaive/differentSymbolsNaive.spec.js -------------------------------------------------------------------------------- /intro/37-arrayMaxConsecutiveSum/arrayMaxConsecutiveSum.js: -------------------------------------------------------------------------------- 1 | 2 | /* Q: Given array of integers, find the maximal possible sum of some of its k consecutive elements. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/intro/level-8/Rqvw3daffNE7sT7d5 5 | 6 | function arrayMaxConsecutiveSum(inputArray, k) { 7 | let i = 0, highestSum = 0; 8 | while ( i + k <= inputArray.length) { 9 | let iterSum = 0, j = i; 10 | for(j; j < k+i; j++) { 11 | iterSum += inputArray[j] 12 | } 13 | highestSum = iterSum > highestSum ? iterSum : highestSum 14 | i += 1; 15 | } 16 | return highestSum; 17 | } 18 | 19 | 20 | exports.arrayMaxConsecutiveSum = arrayMaxConsecutiveSum; -------------------------------------------------------------------------------- /intro/37-arrayMaxConsecutiveSum/arrayMaxConsecutiveSum.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/37-arrayMaxConsecutiveSum/arrayMaxConsecutiveSum.spec.js -------------------------------------------------------------------------------- /intro/38-growingPlant/growingPlant.js: -------------------------------------------------------------------------------- 1 | 2 | /* Q: Caring for a plant can be hard work, but since you tend to it regularly, you have a plant that grows 3 | consistently. Each day, its height increases by a fixed amount represented by the integer upSpeed. 4 | But due to lack of sunlight, the plant decreases in height every night, by an amount represented by downSpeed. 5 | 6 | Since you grew the plant from a seed, it started at height 0 initially. Given an integer desiredHeight, 7 | your task is to find how many days it'll take for the plant to reach this height. */ 8 | 9 | // URL : https://app.codesignal.com/arcade/intro/level-9/xHvruDnQCx7mYom3T 10 | 11 | function growingPlant(upSpeed, downSpeed, desiredHeight) { 12 | let heightGrown = 0, days = 0; 13 | while (heightGrown != desiredHeight) { 14 | days += 1; 15 | heightGrown += upSpeed; 16 | if (heightGrown >= desiredHeight) break; 17 | heightGrown -= downSpeed; 18 | } 19 | return days; 20 | } 21 | 22 | exports.growingPlant = growingPlant; -------------------------------------------------------------------------------- /intro/38-growingPlant/growingPlant.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/38-growingPlant/growingPlant.spec.js -------------------------------------------------------------------------------- /intro/39-knapSackLight/knapSackLight.js: -------------------------------------------------------------------------------- 1 | 2 | /* Q: You found two items in a treasure chest! The first item weighs weight1 and is worth value1, 3 | and the second item weighs weight2 and is worth value2. What is the total maximum value of the 4 | items you can take with you, assuming that your max weight capacity is maxW and you can't come 5 | back for the items later? 6 | 7 | Note that there are only two items and you can't bring more than one item of each type, 8 | i.e. you can't take two first items or two second items. */ 9 | 10 | // URL : https://app.codesignal.com/arcade/intro/level-9/r9azLYp2BDZPyzaG2 11 | 12 | function knapSackLight(value1, weight1, value2, weight2, maxW) { 13 | if (weight1+weight2 <= maxW) { 14 | return value1+value2; 15 | } else if (maxW >= weight2 && maxW >= weight1 ) { 16 | return value1 > value2 ? value1 : value2; 17 | } 18 | else if (maxW < weight2 && maxW < weight1 ) { 19 | return 0 20 | } 21 | else { 22 | return maxW >= weight2 ? value2 : value1; 23 | } 24 | } 25 | 26 | 27 | exports.knapSackLight = knapSackLight; -------------------------------------------------------------------------------- /intro/39-knapSackLight/knapSackLight.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/39-knapSackLight/knapSackLight.spec.js -------------------------------------------------------------------------------- /intro/40-longestDigitsPrefix/longestDigitsPrefix.js: -------------------------------------------------------------------------------- 1 | 2 | /* Q: Given a string, output its longest prefix which contains only digits. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/intro/level-9/AACpNbZANCkhHWNs3 5 | 6 | 7 | function longestDigitsPrefix(inputString) { 8 | function intConverter(s){ 9 | parsedInt = parseInt(inputString).toString(); 10 | return s[0] == '0' ? '0' + parsedInt : parsedInt; 11 | } 12 | return isNaN(parseInt(inputString)) == true || inputString.trimLeft() != inputString ? "" : intConverter(inputString) 13 | } 14 | 15 | 16 | 17 | exports.longestDigitsPrefix = longestDigitsPrefix; -------------------------------------------------------------------------------- /intro/40-longestDigitsPrefix/longestDigitsPrefix.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/40-longestDigitsPrefix/longestDigitsPrefix.spec.js -------------------------------------------------------------------------------- /intro/41-digitDegree/digitDegree.js: -------------------------------------------------------------------------------- 1 | 2 | /* Q: Let's define digit degree of some positive integer as the number of times we need to replace this 3 | number with the sum of its digits until we get to a one digit number. 4 | 5 | Given an integer, find its digit degree. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/intro/level-9/hoLtYWbjdrD2PF6yo 8 | 9 | 10 | function digitDegree(n) { 11 | if (n < 10) { 12 | return 0 13 | } else { 14 | let digitsSum = n, degree = 0; 15 | do { 16 | digitsSum = digitsSum.toString().split('').reduce((a,b) => parseInt(a) + parseInt(b), 0) 17 | degree += 1 18 | } while (digitsSum > 9) 19 | return degree 20 | } 21 | } 22 | 23 | 24 | 25 | 26 | exports.digitDegree = digitDegree; 27 | 28 | 29 | -------------------------------------------------------------------------------- /intro/41-digitDegree/digitDegree.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/41-digitDegree/digitDegree.spec.js -------------------------------------------------------------------------------- /intro/42-bishopAndPawn/bishopAndPawn.js: -------------------------------------------------------------------------------- 1 | 2 | /* Q: Given the positions of a white bishop and a black pawn on the standard chess board, 3 | determine whether the bishop can capture the pawn in one move. 4 | 5 | The bishop has no restrictions in distance for each move, but is limited to diagonal movement. 6 | Check out the example below to see how it can move: */ 7 | 8 | // URL : https://app.codesignal.com/arcade/intro/level-9/6M57rMTFB9MeDeSWo 9 | 10 | 11 | function bishopAndPawn(bishop, pawn) { 12 | return Math.abs(bishop[0].charCodeAt(0)-pawn[0].charCodeAt(0)) === Math.abs(bishop[1]-pawn[1]) 13 | } 14 | 15 | exports.bishopAndPawn = bishopAndPawn; 16 | -------------------------------------------------------------------------------- /intro/42-bishopAndPawn/bishopAndPawn.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/42-bishopAndPawn/bishopAndPawn.spec.js -------------------------------------------------------------------------------- /intro/43-isBeautifulString/isBeautifulString.js: -------------------------------------------------------------------------------- 1 | /* Q: A string is said to be beautiful if each letter in the string appears at most as many times as 2 | the previous letter in the alphabet within the string; ie: b occurs no more times than a; c occurs 3 | no more times than b; etc. Note that letter a has no previous letter. 4 | 5 | Given a string, check whether it is beautiful. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/intro/level-10/PHSQhLEw3K2CmhhXE 8 | 9 | 10 | function isBeautifulString(inputString) { 11 | var inputString = inputString.split('').sort(); 12 | var letters = []; 13 | for(let chr of inputString) if(letters[chr]) letters[chr]++; else letters[chr] = 1; 14 | var code = 'a'.charCodeAt(0); //97 15 | var idx = 0; 16 | var counter = letters.a; 17 | for(let chr in letters){ 18 | if(chr.charCodeAt(0) != code+idx) return false; // from a to z 19 | if(counter < letters[chr]) return false; 20 | idx++; 21 | counter = letters[chr]; 22 | } 23 | return true; 24 | } 25 | 26 | 27 | exports.isBeautifulString = isBeautifulString; 28 | -------------------------------------------------------------------------------- /intro/44-findEmailDomain/findEmailDomain.js: -------------------------------------------------------------------------------- 1 | /* Q: An email address such as "John.Smith@example.com" is made up of a local part ("John.Smith"), 2 | an "@" symbol, then a domain part ("example.com"). 3 | 4 | The domain name part of an email address may only consist of letters, digits, hyphens and dots. 5 | The local part, however, also allows a lot of different special characters. 6 | Here you can look at several examples of correct and incorrect email addresses. 7 | 8 | Given a valid email address, find its domain part. */ 9 | 10 | // URL : https://app.codesignal.com/arcade/intro/level-10/TXFLopNcCNbJLQivP 11 | 12 | 13 | function findEmailDomain(address) { 14 | return address.split('@').pop() 15 | } 16 | 17 | exports.findEmailDomain = findEmailDomain; 18 | -------------------------------------------------------------------------------- /intro/45-buildPalindrome/buildPalindrome.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a string, find the shortest possible string which can be achieved by adding 2 | characters to the end of initial string to make it a palindrome. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/intro/level-10/ppZ9zSufpjyzAsSEx 5 | 6 | 7 | function buildPalindrome(address) { 8 | return address.split('@').pop() 9 | } 10 | 11 | exports.buildPalindrome = buildPalindrome; 12 | 13 | 14 | -------------------------------------------------------------------------------- /intro/46-electionWinners/electionWinners.js: -------------------------------------------------------------------------------- 1 | /* Q: Given an array of the numbers of votes given to each of the candidates so far, and an integer k equal to the number of voters who haven't cast their vote yet, 2 | find the number of candidates who still have a chance to win the election. 3 | 4 | The winner of the election must secure strictly more votes than any other candidate. If two or more candidates receive the same (maximum) number of votes, 5 | assume there is no winner at all. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/intro/level-10/8RiRRM3yvbuAd3MNg 8 | 9 | 10 | function electionWinners(v, k) { 11 | let max = Math.max(...v); 12 | return k || v.indexOf(max) != v.lastIndexOf(max) ? v.filter(n => n + k > max).length : 1 13 | } 14 | 15 | 16 | exports.electionWinners = electionWinners; -------------------------------------------------------------------------------- /intro/47-isMAC48Address/isMAC48Address.js: -------------------------------------------------------------------------------- 1 | /* Q: A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. 2 | 3 | The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB). 4 | Your task is to check by given string inputString whether it corresponds to MAC-48 address or not. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-10/HJ2thsvjL25iCvvdm 7 | 8 | 9 | function isMAC48Address(inputString) { 10 | return /^([A-F\d]{2}-){5}[A-F\d]{2}$/.test(inputString) 11 | } 12 | 13 | 14 | exports.isMAC48Address = isMAC48Address; -------------------------------------------------------------------------------- /intro/48-isDigit/isDigit.js: -------------------------------------------------------------------------------- 1 | /* Q: Determine if the given character is a digit or not. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-11/pwRLrkrNpnsbgMndb 4 | 5 | 6 | 7 | function isDigit(symbol) { 8 | return isNaN(parseInt(symbol)) ? false : true 9 | } 10 | 11 | exports.isDigit = isDigit; -------------------------------------------------------------------------------- /intro/49-lineEncoding/lineEncoding.js: -------------------------------------------------------------------------------- 1 | /* Q: A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. 2 | 3 | The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB). 4 | Your task is to check by given string inputString whether it corresponds to MAC-48 address or not. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-10/HJ2thsvjL25iCvvdm 7 | 8 | 9 | 10 | function lineEncoding(s) { 11 | return s.replace(/(.)\1+/g, chars => chars.length + chars[0]); 12 | } 13 | 14 | exports.lineEncoding = lineEncoding; -------------------------------------------------------------------------------- /intro/50-chessKnight/chessKnight.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform. 2 | The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically 3 | and one square horizontally away from it. The complete move therefore looks like the letter L. 4 | Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-11/pwRLrkrNpnsbgMndb 7 | 8 | 9 | 10 | function chessKnight(cell) { 11 | let n = Number(cell[1]); 12 | let l = cell[0].charCodeAt() - 96; 13 | return (8 - n >= 2 && l + 1 <= 8) + (8 - n >= 1 && l + 2 <= 8) + (n - 1 >= 1 && l + 2 <= 8) + (n - 2 >= 1 && l + 1 <= 8) + (n - 2 >= 1 && l - 1 >= 1) + (n - 1 >= 1 && l - 2 >= 1) + (n + 1 <= 8 && l - 2 >= 1) + (n + 2 <= 8 && l - 1 >= 1); 14 | } 15 | 16 | 17 | exports.chessKnight = chessKnight; -------------------------------------------------------------------------------- /intro/51-deleteDigit/deleteDigit.js: -------------------------------------------------------------------------------- 1 | /* Q: Given some integer, find the maximal number you can obtain by deleting exactly one digit of the given number. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-11/vpfeqDwGZSzYNm2uX 4 | 5 | 6 | 7 | function deleteDigit(n) { 8 | let possibleNumbersSum = [], inp = n.toString() 9 | for(i=0; i v.length > 1 && v.length > a.length ? v : a, ''); 9 | } 10 | 11 | 12 | 13 | exports.longestWord = longestWord; 14 | -------------------------------------------------------------------------------- /intro/52-longestWord/longestWord.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/52-longestWord/longestWord.spec.js -------------------------------------------------------------------------------- /intro/53-validTime/validTime.js: -------------------------------------------------------------------------------- 1 | /* Q: Check if the given string is a correct time representation of the 24-hour clock. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-12/ywMyCTspqGXPWRZx5 4 | 5 | function validTime(time) { 6 | if (time == "24:00") return false 7 | let arr = time.split(':').map(x=>parseInt(x)) 8 | return arr[0] < 24 && arr[0] >= 0 && arr[1] < 60 && arr[1] >= 0 9 | } 10 | 11 | exports.validTime = validTime; 12 | -------------------------------------------------------------------------------- /intro/53-validTime/validTime.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/53-validTime/validTime.spec.js -------------------------------------------------------------------------------- /intro/54-sumUpNumbers/sumUpNumbers.js: -------------------------------------------------------------------------------- 1 | /* Q: Check if the given string is a correct time representation of the 24-hour clock. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-12/ywMyCTspqGXPWRZx5 4 | 5 | function sumUpNumbers(inputString) { 6 | return inputString.match(/[0-9]+/g) != null ? inputString.match(/[0-9]+/g).map(x=>parseInt(x)).reduce((a,b) => a + b, 0) : 0 7 | } 8 | 9 | exports.sumUpNumbers = sumUpNumbers; 10 | -------------------------------------------------------------------------------- /intro/54-sumUpNumbers/sumUpNumbers.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/54-sumUpNumbers/sumUpNumbers.spec.js -------------------------------------------------------------------------------- /intro/55-differentSquares/differentSqares.js: -------------------------------------------------------------------------------- 1 | /* Q: Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-12/ywMyCTspqGXPWRZx5 4 | 5 | function differentSquares(matrix) { 6 | let s = []; 7 | for (var y = 0; y < matrix.length - 1; y++) { 8 | for (var x = 0; x < matrix[0].length - 1; x++) { 9 | s.push("" + matrix[y][x] + matrix[y][x + 1] + matrix[y + 1][x] + matrix[y + 1][x + 1]); 10 | } 11 | } 12 | return new Set(s).size; 13 | } 14 | 15 | 16 | exports.differentSquares = differentSquares; 17 | -------------------------------------------------------------------------------- /intro/55-differentSquares/differentSquares.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/55-differentSquares/differentSquares.spec.js -------------------------------------------------------------------------------- /intro/56-digitsProduct/digitsProduct.js: -------------------------------------------------------------------------------- 1 | /* Q: Given an integer product, find the smallest positive (i.e. greater than 0) integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/intro/level-12/NJJhENpgheFRQbPRA 4 | 5 | function digitsProduct(product) { 6 | for(var i = 1; i <= 3999; i++){ 7 | let smallestNum = i.toString().split('').reduce((a,b) => a*Number(b), 1); 8 | if(smallestNum === product) return i; 9 | } 10 | return -1; 11 | } 12 | 13 | 14 | 15 | exports.digitsProduct = digitsProduct; 16 | -------------------------------------------------------------------------------- /intro/56-digitsProduct/digitsProduct.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/56-digitsProduct/digitsProduct.spec.js -------------------------------------------------------------------------------- /intro/57-fileNaming/fileNaming.js: -------------------------------------------------------------------------------- 1 | /* Q: You are given an array of strings names representing filenames. The array is sorted in order of file creation, such that names[i] represents the name of a 2 | file created before names[i+1] and after names[i-1] (assume 0-based indexing). Because all files must have unique names, files created later with the same 3 | name as a file created earlier should have an additional (k) suffix in their names, where k is the smallest positive integer (starting from 1) that does not appear in previous file names. 4 | 5 | Your task is to iterate through all elements of names (from left to right) and update all filenames based on the above. Return an array of proper filenames. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/intro/level-12/sqZ9qDTFHXBNrQeLC 8 | 9 | function fileNaming(names) { 10 | let ni = '', counter = 1; 11 | for (var i = 0; i <= names.length; i++) { 12 | n = names.slice(0, i); 13 | ni = names[i]; 14 | while (n.includes(names[i])) { 15 | names[i] = ni + '(' + counter.toString() + ')'; 16 | counter++; 17 | } 18 | counter = 1; 19 | } 20 | return names; 21 | } 22 | 23 | 24 | 25 | 26 | exports.fileNaming = fileNaming; 27 | -------------------------------------------------------------------------------- /intro/57-fileNaming/fileNaming.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/57-fileNaming/fileNaming.spec.js -------------------------------------------------------------------------------- /intro/58-messageFromBinaryCode/messageFromBinaryCode.js: -------------------------------------------------------------------------------- 1 | /* Q: You are taking part in an Escape Room challenge designed specifically for programmers. In your efforts to find a clue, you've found a binary code written on the wall behind a vase, 2 | and realized that it must be an encrypted message. After some thought, your first guess is that each consecutive 8 bits of the code stand for the character with the corresponding extended ASCII code. 3 | 4 | Assuming that your hunch is correct, decode the message. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/intro/level-12/sCpwzJCyBy2tDSxKW 7 | 8 | function fileNaming(code) { 9 | let decodedString = "" 10 | for (i=0; i 0; xy -= 2) { 13 | for (var xr = 0; xr < xy; xr++) { 14 | s[round][xr + round] = i++; 15 | } 16 | for (var yd = round + 1; yd < xy + round; yd++) { 17 | s[yd][xy - 1 + round] = i++; 18 | } 19 | for (var xl = xy - 2 + round; xl >= round; xl--) { 20 | s[xy - 1 + round][xl] = i++; 21 | } 22 | for (var yu = xy - 2 + round; yu > round; yu--) { 23 | s[yu][round] = i++; 24 | } 25 | round++; 26 | } 27 | return s; 28 | } 29 | 30 | 31 | exports.spiralNumbers = spiralNumbers; 32 | -------------------------------------------------------------------------------- /intro/59-spiralNumbers/spiralNumbers.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/59-spiralNumbers/spiralNumbers.spec.js -------------------------------------------------------------------------------- /intro/60-sudoku/sudoku.js: -------------------------------------------------------------------------------- 1 | /* Q: Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with digits so that each column, each row, and each of the nine 3 × 3 sub-grids that compose the grid contains all of the digits from 1 to 9. 2 | 3 | This algorithm should check if the given grid of numbers represents a correct solution to Sudoku. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/intro/level-12/tQgasP8b62JBeirMS 6 | 7 | function sudoku(grid) { 8 | let sg = []; 9 | for (var i = 0; i < 9; i += 3) { 10 | for (var j = 0; j < 9; j += 3) { 11 | sg.push([grid[i][j], grid[i][j + 1], grid[i][j + 2], 12 | grid[i + 1][j], grid[i + 1][j + 1], grid[i + 1][j + 2], 13 | grid[i + 2][j], grid[i + 2][j + 1], grid[i + 2][j + 2] 14 | ]); 15 | } 16 | } 17 | return grid.concat(sg, [...grid.map((v, i) => v.map((v1, j) => grid[j][i]))]).filter(v => v.sort().join('') != '123456789').length === 0; 18 | 19 | } 20 | 21 | exports.sudoku = sudoku; 22 | -------------------------------------------------------------------------------- /intro/60-sudoku/sudoku.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/intro/60-sudoku/sudoku.spec.js -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "codesignal-solutions", 3 | "version": "1.0.0", 4 | "description": "Solutions for problems on code signal", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "mocha spec.js" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/sed-23/codesignal-solutions.git" 12 | }, 13 | "author": "sed", 14 | "license": "ISC", 15 | "bugs": { 16 | "url": "https://github.com/sed-23/codesignal-solutions/issues" 17 | }, 18 | "homepage": "https://github.com/sed-23/codesignal-solutions#readme" 19 | } 20 | -------------------------------------------------------------------------------- /the_core/01-addTwoDigits/addTwoDigits.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given a two-digit integer n. Return the sum of its digits. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/wAGdN6FMPkx7WBq66 4 | 5 | function addTwoDigits(n) { 6 | return (n / 10 | 0) + n % 10; 7 | } 8 | 9 | exports.addTwoDigits = addTwoDigits; 10 | -------------------------------------------------------------------------------- /the_core/01-addTwoDigits/addTwoDigits.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/the_core/01-addTwoDigits/addTwoDigits.spec.js -------------------------------------------------------------------------------- /the_core/02-largestNumber/largestNumber.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an integer n, return the largest number that contains exactly n digits. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/SZB5XypsMokGusDhX 4 | 5 | function largestNumber(n) { 6 | return 10 ** n - 1 7 | } 8 | 9 | exports.largestNumber = largestNumber; 10 | -------------------------------------------------------------------------------- /the_core/02-largestNumber/largestNumber.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/the_core/02-largestNumber/largestNumber.spec.js -------------------------------------------------------------------------------- /the_core/03-candies/candies.js: -------------------------------------------------------------------------------- 1 | /* Question : n children have got m pieces of candy. They want to eat as much candy as they can, but each child must eat exactly the same amount of candy as any other child. 2 | Determine how many pieces of candy will be eaten by all the children together. Individual pieces of candy cannot be split. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/DdNKFA3XCX6XN7bNz 5 | 6 | function candies(n, m) { 7 | return m - m % n; 8 | } 9 | 10 | exports.candies = candies; 11 | -------------------------------------------------------------------------------- /the_core/03-candies/candies.spec.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sed-23/codesignal-solutions/93448255db56dc406ac337eddd2dc1eba0ccfedb/the_core/03-candies/candies.spec.js -------------------------------------------------------------------------------- /the_core/04-seatsInTheater/seatsInTheater.js: -------------------------------------------------------------------------------- 1 | /* Question : Your friend advised you to see a new performance in the most popular theater in the city. He knows a lot about art and his advice is usually good, but not this time: 2 | the performance turned out to be awfully dull. It's so bad you want to sneak out, which is quite simple, especially since the exit is located right behind your row to the left. 3 | All you need to do is climb over your seat and make your way to the exit. 4 | 5 | The main problem is your shyness: you're afraid that you'll end up blocking the view (even if only for a couple of seconds) of all the people who sit behind you and in your 6 | column or the columns to your left. To gain some courage, you decide to calculate the number of such people and see if you can possibly make it to the exit without disturbing too many people. 7 | 8 | Given the total number of rows and columns in the theater (nRows and nCols, respectively), and the row and column you're sitting in, return the number of people who sit strictly 9 | behind you and in your column or to the left, assuming all seats are occupied. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/bszFiQAog96G9CXKg 12 | 13 | function seatsInTheater(nCols, nRows, col, row) { 14 | return (nCols - (col - 1)) * (nRows - row); 15 | } 16 | 17 | exports.seatsInTheater = seatsInTheater; 18 | -------------------------------------------------------------------------------- /the_core/05-maxMultiple/maxMultiple.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a divisor and a bound, find the largest integer N such that: 2 | N is divisible by divisor. 3 | N is less than or equal to bound. 4 | N is greater than 0. 5 | It is guaranteed that such a number exists. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/HEsmEacHr2s9wahjr 8 | 9 | 10 | function maxMultiple(divisor, bound) { 11 | return bound - (bound % divisor); 12 | } 13 | 14 | exports.maxMultiple = maxMultiple; 15 | -------------------------------------------------------------------------------- /the_core/06-circleOfNumbers/circleOfNumbers.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider integer numbers from 0 to n - 1 written down along the circle in such a way that the distance between any two neighboring numbers is equal (note that 0 and n - 1 are neighboring, too). 2 | Given n and firstNumber, find the number which is written in the radially opposite position to firstNumber. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/vExYvcGnFsEYSt8nQ 5 | 6 | 7 | function circleOfNumbers(divisor, bound) { 8 | return bound - (bound % divisor); 9 | } 10 | -------------------------------------------------------------------------------- /the_core/07-lateTime/lateTime.js: -------------------------------------------------------------------------------- 1 | /* Question : One night you go for a ride on your motorcycle. At 00:00 you start your engine, and the built-in timer automatically begins counting the length of your ride, in minutes. Off you go to explore the neighborhood. 2 | When you finally decide to head back, you realize there's a chance the bridges on your route home are up, leaving you stranded! Unfortunately, you don't have your watch on you and don't know what time it is. 3 | All you know thanks to the bike's timer is that n minutes have passed since 00:00. 4 | Using the bike's timer, calculate the current time. Return an answer as the sum of digits that the digital timer in the format hh:mm would show. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/aiKck9MwwAKyF8D4L 7 | 8 | 9 | function lateTime(n) { 10 | h = ((n / 60) | 0) % 24 11 | m = n % 60 12 | return ((h / 10) | 0) + h % 10 + ((m / 10) | 0) + m % 10 13 | } 14 | -------------------------------------------------------------------------------- /the_core/08-phoneCall/phoneCall.js: -------------------------------------------------------------------------------- 1 | /* Question : Some phone usage rate may be described as follows: first minute of a call costs min1 cents, each minute from the 2nd up to 10th (inclusive) costs min2_10 cents 2 | each minute after 10th costs min11 cents. You have s cents on your account before the call. What is the duration of the longest call (in minutes rounded down to the nearest integer) you can have? */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/intro-gates/mZAucMXhNMmT7JWta 5 | 6 | 7 | function phoneCall(min1, min2_10, min11, s) { 8 | return bound - (bound % divisor); 9 | } 10 | -------------------------------------------------------------------------------- /the_core/09-reachNewLevel/reachNewLevel.js: -------------------------------------------------------------------------------- 1 | /* Question : You are playing an RPG game. Currently your experience points (XP) total is equal to experience. To reach the next level your XP should be at least at threshold. 2 | If you kill the monster in front of you, you will gain more experience points in the amount of the reward. 3 | Given values experience, threshold and reward, check if you reach the next level after killing the monster. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/m9wjpkCjgofg7gs8N 6 | 7 | 8 | function reachNewLevel(experience, threshold, reward) { 9 | return experience+reward>=threshold 10 | } 11 | -------------------------------------------------------------------------------- /the_core/10-knapsackLight/knapsackLight.js: -------------------------------------------------------------------------------- 1 | /* Question : You found two items in a treasure chest! The first item weighs weight1 and is worth value1, and the second item weighs weight2 and is worth value2. 2 | What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can't come back for the items later? 3 | 4 | Note that there are only two items and you can't bring more than one item of each type, i.e. you can't take two first items or two second items. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/r9azLYp2BDZPyzaG2 7 | 8 | 9 | function knsapscakLight(value1, weight1, value2, weight2, maxW) { 10 | return Math.max( 11 | maxW >= weight1 && value1, 12 | maxW >= weight2 && value2, 13 | maxW >= weight1 + weight2 && value1 + value2 14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /the_core/100-reverseOnDiagnosis/reverseOnDiagnosis.js: -------------------------------------------------------------------------------- 1 | /* Question : The longest diagonals of a square matrix are defined as follows: 2 | 3 | the first longest diagonal goes from the top left corner to the bottom right one; 4 | the second longest diagonal goes from the top right corner to the bottom left one. 5 | Given a square matrix, your task is to reverse the order of elements on both of its longest diagonals. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/Akspcu9ewiYapWkrp 8 | 9 | 10 | function reverseOnDiagnosis(matrix) { 11 | for (let i = 0, j = matrix.length - 1; i < matrix.length / 2; i++, j--) { 12 | [matrix[i][i], matrix[j][j]] = [matrix[j][j], matrix[i][i]]; 13 | [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]]; 14 | } 15 | return matrix 16 | } -------------------------------------------------------------------------------- /the_core/101-swapDiagnosis/swapDiagnosis.js: -------------------------------------------------------------------------------- 1 | /* Question : The longest diagonals of a square matrix are defined as follows: 2 | 3 | the first longest diagonal goes from the top left corner to the bottom right one; 4 | the second longest diagonal goes from the top right corner to the bottom left one. 5 | Given a square matrix, your task is to swap its longest diagonals by exchanging their elements at the corresponding positions. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/kfwTN8pdx9uP8bcHS 8 | 9 | 10 | function swapDiagnosis(matrix) { 11 | let {length : len} = matrix; 12 | for (let i = 0; i < len; i++){ 13 | [matrix[i][i], matrix[i][len-i-1]] = [matrix[i][len-i-1], matrix[i][i]]; 14 | } 15 | return matrix; 16 | } -------------------------------------------------------------------------------- /the_core/102-crossingSum/crossingSum.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a rectangular matrix and integers a and b, consider the union of the ath row and the bth (both 0-based) column of the matrix 2 | (i.e. all cells that belong either to the ath row or to the bth column, or to both). Return sum of all elements of that union. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/Nh48Nqxb2zGx2NvYK 5 | 6 | 7 | function crossingSum(matrix, a, b) { 8 | return matrix[a].reduce((x,y)=>x+y) + matrix.reduce((x,y)=>x+y[b],0) - matrix[a][b] 9 | } -------------------------------------------------------------------------------- /the_core/103-drawRectangle/drawRectangle.js: -------------------------------------------------------------------------------- 1 | /* Question : You are implementing a command-line version of the Paint app. Since the command line doesn't support colors, you are using different characters to represent pixels. 2 | Your current goal is to support rectangle x1 y1 x2 y2 operation, which draws a rectangle that has an upper left corner at (x1, y1) and a lower right corner at (x2, y2). 3 | Here the x-axis points from left to right, and the y-axis points from top to bottom. 4 | 5 | Given the initial canvas state and the array that represents the coordinates of the two corners, return the canvas state after the operation is applied. 6 | For the details about how rectangles are painted, see the example. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/uFQEiM4trARdm2z46 9 | 10 | 11 | function drawRectangle(canvas, rectangle) { 12 | for (var i = rectangle[0] + 1; i < rectangle[2]; i++) { 13 | canvas[rectangle[1]][i] = canvas[rectangle[3]][i] = '-'; 14 | } 15 | for (var i = rectangle[1] + 1; i < rectangle[3]; i++) { 16 | canvas[i][rectangle[0]] = canvas[i][rectangle[2]] = '|'; 17 | } 18 | canvas[rectangle[1]][rectangle[0]] = 19 | canvas[rectangle[3]][rectangle[0]] = 20 | canvas[rectangle[1]][rectangle[2]] = 21 | canvas[rectangle[3]][rectangle[2]] = '*'; 22 | return canvas; 23 | } -------------------------------------------------------------------------------- /the_core/104-volleyballPositions/volleyballPositinos.js: -------------------------------------------------------------------------------- 1 | /* Question : You are watching a volleyball tournament, but you missed the beginning of the very first game of your favorite team. 2 | Now you're curious about how the coach arranged the players on the field at the start of the game. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/fmYdsYcGfaTu4yTQt 5 | 6 | 7 | function volleyballPositions(formation, k) { 8 | function rotate() { 9 | let holder = formation[3][2]; 10 | formation[3][2] = formation[2][1]; 11 | formation[2][1] = formation[3][0]; 12 | formation[3][0] = formation[1][0]; 13 | formation[1][0] = formation[0][1]; 14 | formation[0][1] = formation[1][2]; 15 | formation[1][2] = holder; 16 | } 17 | 18 | k = k % 6; 19 | 20 | for (let i = 1; i <= k; i++) { 21 | rotate(); 22 | } 23 | 24 | return formation; 25 | } 26 | -------------------------------------------------------------------------------- /the_core/105-starRotation/starRotation.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider a (2k+1) × (2k+1) square subarray of an integer integers matrix. Let's call the union of the square's two longest diagonals, middle 2 | column and middle row a star. Given the coordinates of the star's center in the matrix and its width, rotate it 45 · t degrees clockwise preserving 3 | position of all matrix elements that do not belong to the star. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/A5meC5REAcDfHeuFf 6 | 7 | 8 | function starRotation(a, width, center, t) { 9 | for (let k = 0; k < t%8; k++){ 10 | let startX = center[0] - (width-1)/2, 11 | startY = center[1] - (width-1)/2, 12 | midX = center[0], 13 | midY = center[1], 14 | endX = center[0] + (width-1)/2, 15 | endY = center[1] + (width-1)/2; 16 | for (let i = 0; i < (width-1)/2; i++){ 17 | let tem = a[startX][startY]; 18 | a[startX][startY] = a[midX][startY]; 19 | a[midX][startY] = a[endX][startY]; 20 | a[endX][startY] = a[endX][midY]; 21 | a[endX][midY] = a[endX][endY]; 22 | a[endX][endY] = a[midX][endY]; 23 | a[midX][endY] = a[startX][endY]; 24 | a[startX][endY] = a[startX][midY]; 25 | a[startX][midY] = tem; 26 | startX++; 27 | startY++; 28 | endX--; 29 | endY--; 30 | } 31 | } 32 | return a; 33 | } 34 | -------------------------------------------------------------------------------- /the_core/106-sudoku/sudoku.js: -------------------------------------------------------------------------------- 1 | /* Question : Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with digits so that each column, each row, and each of the nine 3 × 3 sub-grids that compose 2 | the grid contains all of the digits from 1 to 9. This algorithm should check if the given grid of numbers represents a correct solution to Sudoku. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/waterfall-of-integration/tQgasP8b62JBeirMS 5 | 6 | 7 | function sudoku(grid) { 8 | for (let i = 0; i < 9; i++) 9 | for (let j = 0; j < 9; j++) 10 | if (!check(grid, i, j)) 11 | return false; 12 | return true; 13 | } 14 | function check(grid, x, y){ 15 | for (let i = 0; i < 9; i++){ 16 | if (i!=y&&grid[x][y]==grid[x][i]) 17 | return false; 18 | if (i!=x&&grid[x][y]==grid[i][y]) 19 | return false; 20 | } 21 | let x1 = x - x%3, 22 | y1 = y - y%3; 23 | for (let i = x1; i < x1+3; i++) 24 | for (let j = y1; j < y1+3; j++) 25 | if (i!=x||j!=y){ 26 | if (grid[i][j]==grid[x][y]) 27 | return false; 28 | } 29 | return true; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /the_core/107-minesweeper/minesweeper.js: -------------------------------------------------------------------------------- 1 | /* Question : In the popular Minesweeper game you have a board with some mines and those cells that don't contain a mine have a number in it that indicates the total 2 | number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a Minesweeper game setup. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/waterfall-of-integration/ZMR5n7vJbexnLrgaM 5 | 6 | 7 | function minesweeper(matrix) { 8 | let res = []; 9 | const isValid = ((matrix, x, y) =>x>=0&&x=0&&y false) 15 | 16 | for(let line=0; line < matrix.length; line++) { 17 | 18 | let prevItem = false 19 | 20 | for(let col=0; col< matrix[line].length; col++) { 21 | if(matrix[line][col]) { 22 | counter += 4 - prevItem * 2 - prevLine[col] * 2 23 | } 24 | prevItem = matrix[line][col] 25 | } 26 | 27 | prevLine = matrix[line] 28 | } 29 | 30 | return counter 31 | } 32 | -------------------------------------------------------------------------------- /the_core/111-gravitation/gravitation.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given a vertical box divided into equal columns. Someone dropped several stones from its top through the columns. Stones are falling straight down at a constant speed 2 | (equal for all stones) while possible (i.e. while they haven't reached the ground or they are not blocked by another motionless stone). Given the state of the box at 3 | some moment in time, find out which columns become motionless first. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/waterfall-of-integration/hqrYesGKEaKQnv7Sv 6 | 7 | 8 | function graviatation(rows) { 9 | result = []; 10 | minStep = rows.length; 11 | 12 | for (i=0; i=0; j--) { 16 | if (rows[j].charAt(i) == '#') { 17 | step = finish - j; 18 | finish--; 19 | } 20 | } 21 | if (step == minStep) { 22 | result.push(i); 23 | } 24 | if (step < minStep) { 25 | minStep = step; 26 | result = new Array; 27 | result.push(i); 28 | } 29 | } 30 | 31 | return result; 32 | } -------------------------------------------------------------------------------- /the_core/112-isInformationConsistent/isInformationConsistent.js: -------------------------------------------------------------------------------- 1 | /* Question : Court is in session. We got a group of witnesses who have all taken an oath to tell the truth. The prosecutor is pointing at the defendants one by one and asking 2 | each witnesses a simple question - "guilty or not?". The witnesses are allowed to respond in one of the following three ways: 3 | 4 | I am sure he/she is guilty. 5 | I am sure he/she is innocent. 6 | I have no idea. 7 | The prosecutor has a hunch that one of the witnesses might not be telling the truth so she decides to cross-check all of their testimonies and see if the information 8 | gathered is consistent, i.e. there are no two witnesses A and B and a defendant C such that A says C is guilty while B says C is innocent. */ 9 | 10 | // URL : https://app.codesignal.com/arcade/code-arcade/waterfall-of-integration/jkuhbNn7AdeCC7z7R 11 | 12 | 13 | function isInformationConsistent(evidences) { 14 | for (let i = 0; i < evidences[0].length; i++) { 15 | let defendent = []; 16 | for (let j = 0; j < evidences.length; j++) { 17 | defendent.push(evidences[j][i]); 18 | } 19 | if (defendent.includes(1) && defendent.includes(-1)){ 20 | return false; 21 | } 22 | } 23 | return true; 24 | } 25 | -------------------------------------------------------------------------------- /the_core/114-shuffledArray/shuffledArray.js: -------------------------------------------------------------------------------- 1 | /* Question : A noob programmer was given two simple tasks: sum and sort the elements of the given array 2 | a = [a1, a2, ..., an]. He started with summing and did it easily, but decided to store the sum he found in some 3 | random position of the original array which was a bad idea. Now he needs to cope with the second task, 4 | sorting the original array a, and it's giving him trouble since he modified it. 5 | 6 | Given the array shuffled, consisting of elements a1, a2, ..., an, a1 + a2 + ... + an in random order, return the sorted array of original elements a1, a2, ..., an. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/s4BEFMcpLdGbjX9KX 9 | 10 | 11 | function shuffledArray(shuffled) { 12 | const sumValue = shuffled.reduce((a,b) => a+b)/2; 13 | const index = shuffled.indexOf(sumValue); 14 | const newArray = shuffled.slice() 15 | newArray.splice(index,1) 16 | return newArray.sort((a,b) => a - b) 17 | } -------------------------------------------------------------------------------- /the_core/115-sortByHeight/sortByHeight.js: -------------------------------------------------------------------------------- 1 | /* Question : Some people are standing in a row in a park. There are trees between them which cannot be moved. 2 | Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall! */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/D6qmdBL2NYz49XHwM 5 | 6 | 7 | function polygonPerimeter(a) { 8 | var sorted = a.filter(h => h != -1).sort((a,b) => a-b) 9 | 10 | var j = 0 11 | 12 | return a.map((h, i) => h != -1 ? sorted[j++] : h) 13 | } 14 | -------------------------------------------------------------------------------- /the_core/116-sortByLength/sortByLength.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an array of strings, sort them in the order of increasing lengths. If two strings have the same length, their relative order must be the same as in the initial array. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/QQB7f8ouAqY6jf7xi 4 | 5 | 6 | function sortByLength(inputArray) { 7 | let indexes = inputArray.map((_, i) => i); 8 | indexes.sort((ia, ib) => inputArray[ia].length - inputArray[ib].length || ia - ib); 9 | return indexes.map(i => inputArray[i]); 10 | } 11 | -------------------------------------------------------------------------------- /the_core/117-boxesPacking/boxesPacking.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given n rectangular boxes, the ith box has the length lengthi, the width widthi and the height heighti. Your task is to check if it 2 | is possible to pack all boxes into one so that inside each box there is no more than one another box (which, in turn, can contain at most 3 | one another box, and so on). More formally, your task is to check whether there is such sequence of n different numbers pi (1 ≤ pi ≤ n) 4 | that for each 1 ≤ i < n the box number pi can be put into the box number pi+1. 5 | 6 | A box can be put into another box if all sides of the first one are less than the respective ones of the second one. 7 | You can rotate each box as you wish, i.e. you can swap its length, width and height if necessary. */ 8 | 9 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/9y4wLpcqnNozn92tG 10 | 11 | 12 | function boxesPacking(l, w, h) { 13 | a = l.map((j,i)=>[j,w[i],h[i]].sort((x,y)=>x-y)).sort((x,y)=>x[0]-y[0]) 14 | return [...Array(3).keys()].map(i=>a.map(j=>j[i])).every(i=>[...new Set(i)].sort((x,y)=>x-y).toString()==i.toString()) 15 | } 16 | -------------------------------------------------------------------------------- /the_core/118-maximumSum/maximumSum.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given an array of integers a. A range sum query is defined by a pair of non-negative integers l and r (l <= r). 2 | The output to a range sum query on the given array a is the sum of all the elements of a that have indices from l to r, inclusive. 3 | 4 | You have the array a and a list of range sum queries q. Find an algorithm that can rearrange the array a in such a way that the 5 | total sum of all of the query outputs is maximized, and return this total sum. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/64koZSDqndwYxFZj6 8 | 9 | 10 | function maximumSum(a, q) { 11 | a.sort((b, c) => b - c); 12 | let counts = new Array(a.length).fill(0); 13 | 14 | for (let tuple of q) { 15 | for (let i = tuple[0]; i <= tuple[1]; i++) { 16 | counts[i]++; 17 | } 18 | } 19 | 20 | counts.sort((b, c) => b - c); 21 | 22 | return a.reduce((sum, x, i) => { 23 | return sum + x * counts[i] 24 | }, 0); 25 | } 26 | -------------------------------------------------------------------------------- /the_core/119-rowsRearranging/rowsRearranging.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a rectangular matrix of integers, check if it is possible to rearrange its rows in such a way that all 2 | its columns become strictly increasing sequences (read from top to bottom). */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/vuXQuYFReJPe6hHAf 5 | 6 | 7 | function rowsRearranging(matrix) { 8 | let sorted = matrix.sort((a, b) => a[0] - b[0]); 9 | for (let i = 0; i < sorted.length - 1; i++) { 10 | for (let j = 0; j < sorted[i].length; j++) { 11 | if (sorted[i][j] >= sorted[i + 1][j]) { 12 | return false; 13 | } 14 | } 15 | } 16 | return true; 17 | } 18 | -------------------------------------------------------------------------------- /the_core/12-isInfiniteProcess/isInfiniteProcess.js: -------------------------------------------------------------------------------- 1 | /* Question : Given integers a and b, determine whether the following pseudocode results in an infinite loop 2 | while a is not equal to b do 3 | increase a by 1 4 | decrease b by 1 5 | Assume that the program is executed on a virtual machine which can store arbitrary long numbers and execute forever. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/aFF9HDm2Rsti9j5kc 8 | 9 | 10 | function extraNumber(a, b) { 11 | return a > b || a % 2 != b % 2; 12 | } 13 | -------------------------------------------------------------------------------- /the_core/120-digitDifferenceSort/digitDifferenceSort.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an array of integers, sort its elements by the difference of their largest and smallest digits. In the case of a tie, that with the larger index in the array should come first. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/2SFFWqkhkqC7mMBse 4 | 5 | 6 | function digitDifferenceSort(a) { 7 | const arr = a.map((elm, i) => ({i:i, v:Math.max(...elm+'') - Math.min(...elm+'')})) 8 | 9 | return arr.sort((x,y)=> x.v - y.v || y.i - x.i).map(elm => a[elm.i]) 10 | } 11 | -------------------------------------------------------------------------------- /the_core/121-uniqueDigitProducts/uniqueDigitProducts.js: -------------------------------------------------------------------------------- 1 | /* Question : Let's call product(x) the product of x's digits. Given an array of integers a, calculate product(x) for each x in a, and return the number of distinct results you get. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/sorting-outpost/oY6FASrCMEqkxwcAC 4 | 5 | 6 | function uniqueDigitProduct(a) { 7 | return new Set(a.map(elm => [...`${elm}`].reduce((a,b) => a * b, 1))).size 8 | } 9 | -------------------------------------------------------------------------------- /the_core/122-bishopAndPawn/bishopAndPawn.js: -------------------------------------------------------------------------------- 1 | /* Question : Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move. 2 | 3 | The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move: */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/chess-tavern/6M57rMTFB9MeDeSWo 6 | 7 | 8 | function bishopAndPawn(bishop, pawn) { 9 | return Math.abs(bishop.charCodeAt(0)-pawn.charCodeAt(0))==Math.abs(Number(pawn[1])-Number(bishop[1])) 10 | } 11 | 12 | -------------------------------------------------------------------------------- /the_core/123-chessKnightMoves/chessKnightMoves.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform. 2 | 3 | The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square 4 | horizontally away from it. The complete move therefore looks like the letter L. Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/chess-tavern/zqDuSLMHhAknqnLtA 7 | 8 | 9 | function chessKnightMoves(cell) { 10 | cell = [(cell.codePointAt(0) - 96), Number(cell[1])]; 11 | let a = (cell[1] + 1 > 8) + (cell[1] + 2 > 8), 12 | b = (cell[0] + 1 > 8) + (cell[0] + 2 > 8), 13 | c = (cell[1] - 1 < 1) + (cell[1] - 2 < 1), 14 | d = (cell[0] - 1 < 1) + (cell[0] - 2 < 1); 15 | let sum = a + b + c + d; 16 | sum += sum ? sum == 1 ? 1 : 2 : 0; 17 | return 8 - sum; 18 | } 19 | -------------------------------------------------------------------------------- /the_core/124-bishopDiagonal/bishopDiagonal.js: -------------------------------------------------------------------------------- 1 | /* Question : In the Land Of Chess, bishops don't really like each other. In fact, when two bishops happen to stand on the same diagonal, they immediately rush towards the opposite ends of that same diagonal. 2 | 3 | Given the initial positions (in chess notation) of two bishops, bishop1 and bishop2, calculate their future positions. Keep in mind that bishops won't move unless they see each other along the same diagonal. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/chess-tavern/wGLCfzpdcA2o9kSpD 6 | 7 | 8 | function bishopDiagonal(bishop1, bishop2) { 9 | let pos = x => [x[0].charCodeAt(0) - 'a'.charCodeAt(0) + 1, parseInt(x[1])] 10 | let word = (x,y) => `${String.fromCharCode(x+'a'.charCodeAt(0) - 1)}${y}` 11 | let btwn27 = x => 2 <= x && x <= 7; 12 | console.log(pos(bishop1), pos(bishop2)) 13 | let [c, c1] = [pos(bishop1), pos(bishop2)].sort(([x,y],[x1,y1])=> x - x1); 14 | let [dx,dy] = [c[0]-c1[0],c[1] - c1[1]]; 15 | let [x,y] = c, [x1,y1] = c1; 16 | if( Math.abs(dx) != Math.abs(dy)) return [bishop1,bishop2].sort(); 17 | if (dy < 0){ 18 | for( ; btwn27(x) && btwn27(y) ;) x -= 1, y -=1; 19 | for( ; btwn27(x1) && btwn27(y1) ;) x1 += 1, y1 +=1; 20 | }else{ 21 | for( ; btwn27(x) && btwn27(y) ;) x -= 1, y +=1; 22 | for( ; btwn27(x1) && btwn27(y1) ;) x1 += 1, y1 -=1; 23 | } 24 | return [word(x,y),word(x1,y1)].sort(); 25 | } 26 | -------------------------------------------------------------------------------- /the_core/125-whoseTurn/whoseTurn.js: -------------------------------------------------------------------------------- 1 | /* Question : Imagine a standard chess board with only two white and two black knights placed in their standard starting positions: the white knights on b1 and g1; the black knights on b8 and g8. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/chess-tavern/SJRNgqggTaktuCJGj 4 | 5 | 6 | function whoseTurn(p) { 7 | let pieces = p.split(';') 8 | let places = pieces.map(e => { 9 | return (e.charCodeAt(0) - 96 + Number(e[1])) % 2 === 0 ? false : true 10 | }) 11 | 12 | return (places[0] ^ places[1]) === (places[2] ^ places[3]) 13 | } 14 | -------------------------------------------------------------------------------- /the_core/126-chessBishopDream/chessBishopDream.js: -------------------------------------------------------------------------------- 1 | /* Question : In ChessLand there is a small but proud chess bishop with a recurring dream. In the dream the bishop finds itself on an n × m chessboard with mirrors along each edge, and it is not 2 | a bishop but a ray of light. This ray of light moves only along diagonals (the bishop can't imagine any other types of moves even in its dreams), it never stops, and once it 3 | reaches an edge or a corner of the chessboard it reflects from it and moves on. 4 | 5 | Given the initial position and the direction of the ray, find its position after k steps where a step means either moving from one cell to the neighboring one or reflecting from a corner of the board. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/chess-tavern/FfjPkYvo9ah6wgXem 8 | 9 | 10 | function chessBishopDream(boardSize, initPosition, initDirection, k) { 11 | return [0,1].map(i => { 12 | 13 | const mod = boardSize[i] * 2; 14 | const mid = (mod-1) / 2; 15 | const mad = initPosition[i] + initDirection[i] * k; 16 | 17 | return mid - Math.abs(mid - ((mad%mod) + mod) % mod) 18 | }) 19 | } 20 | -------------------------------------------------------------------------------- /the_core/127-chessTriangle/chessTriangle.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider a bishop, a knight and a rook on an n × m chessboard. They are said to form a triangle if each piece attacks exactly one other piece and is attacked by exactly one piece. 2 | Calculate the number of ways to choose positions of the pieces to form a triangle. 3 | 4 | Note that the bishop attacks pieces sharing the common diagonal with it; the rook attacks in horizontal and vertical directions; and, finally, the knight 5 | attacks squares which are two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from its position. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/chess-tavern/NhRZQrrMqeWYL9L9Z 8 | 9 | 10 | function chessTriangle(n, m) { 11 | let a, b; 12 | if(m1 && b>2)*8*a1*b2 + (a>2 && b>2)*(8*a2*b1 + 16*a2*b2) + (a>1 && b>3)*8*a1*b3 + (a>2 && b>3)*8*a2*b3 + (a>3)*(8*a3*b1 + 8*a3*b2); 16 | 17 | } -------------------------------------------------------------------------------- /the_core/13-arthimeticExpression/arthimeticExpression.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider an arithmetic expression of the form a#b=c. Check whether it is possible to replace # with one of the four signs: +, -, * or / to obtain a correct expression. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/QrCSNQWhnQoaK9KgK 4 | 5 | 6 | function arthimeticExpression(a, b, c) { 7 | return a+b==c || a-b==c || a*b==c || a/b==c 8 | } 9 | -------------------------------------------------------------------------------- /the_core/130-validTime/validTimie.js: -------------------------------------------------------------------------------- 1 | /* Question : Check if the given string is a correct time representation of the 24-hour clock. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/time-river/ywMyCTspqGXPWRZx5 4 | 5 | 6 | function validTime(time) { 7 | return time.split(":")[0]<24&&time.split(":")[1]<60 8 | } -------------------------------------------------------------------------------- /the_core/131-videoPart/videoPart.js: -------------------------------------------------------------------------------- 1 | /* Question : You have been watching a video for some time. Knowing the total video duration find out what portion of the video you have already watched. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/time-river/DKjM5qLz5ccK2ukhH 4 | 5 | 6 | function videoPart(part, total) { 7 | a = part.split(':').map(x => Number(x)) 8 | b = total.split(':').map(x => Number(x)) 9 | x = a[0] * 3600 + a[1] * 60 + a[2] 10 | y = b[0] * 3600 + b[1] * 60 + b[2] 11 | a = x 12 | b = y 13 | while (y > 0) { 14 | tg = x % y 15 | x = y 16 | y = tg 17 | } 18 | return [a / x, b / x] 19 | } 20 | -------------------------------------------------------------------------------- /the_core/132-dayOfWeek/dayOfWeek.js: -------------------------------------------------------------------------------- 1 | /* Question : Whenever you decide to celebrate your birthday you always do this your favorite café, which is quite popular and as such usually very crowded. This year you got lucky: 2 | when you and your friend enter the café you're surprised to see that it's almost empty. The waiter lets slip that there are always very few people on this day of the week. 3 | 4 | You enjoyed having the café all to yourself, and are now curious about the next time you'll be this lucky. Given the current birthdayDate, determine the number of years until it will fall on the same day of the week. 5 | 6 | For your convenience, here is the list of months lengths (from January to December, respectively): 7 | 8 | Months lengths: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. 9 | Please, note that in leap years February has 29 days. If your birthday is on the 29th of February, you celebrate it once in four years. Otherwise you birthday is celebrated each year. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/time-river/ywMyCTspqGXPWRZx5 12 | 13 | 14 | function dayOfWeek(birthdayDate) { 15 | var bd = new Date(birthdayDate); 16 | var dat = bd.getDay() 17 | var day = bd.getDate(); 18 | var mt = bd.getMonth(); 19 | var nextYear = bd.getFullYear() + 1; 20 | for (var i = 0; i < 100; i++){ 21 | var newDay = new Date(nextYear, mt, day).getDay(); 22 | var newDate = new Date(nextYear, mt, day).getDate(); 23 | 24 | if (dat == newDay && newDate == day){ 25 | break; 26 | } 27 | console.log(newDate); 28 | nextYear++; 29 | } 30 | return i+1; 31 | } 32 | -------------------------------------------------------------------------------- /the_core/133-curiousClock/curiousClock.js: -------------------------------------------------------------------------------- 1 | /* Question : Benjamin recently bought a digital clock at a magic trick shop. The seller never told Ben what was so special about it, but mentioned that one day Benjamin would be faced with a surprise. 2 | 3 | Indeed, the clock did surprise Benjamin: without warning, at someTime the clock suddenly started going in the opposite direction! Unfortunately, 4 | Benjamin has an important meeting very soon, and knows that at leavingTime he should leave the house so as to not be late. Ben spent all his money on the clock, 5 | so has to figure out what time his clock will show when it's time to leave. 6 | 7 | Given the someTime at which the clock started to go backwards, find out what time will be shown on the curious clock at leavingTime. 8 | 9 | For your convenience, here is the list of months lengths (from January to December, respectively): 10 | 11 | Months lengths: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. 12 | Please, note that in leap years February has 29 days. */ 13 | 14 | // URL : https://app.codesignal.com/arcade/code-arcade/time-river/ekhR5y6QuHjxWk36W 15 | 16 | 17 | function curiousClock(someTime, leavingTime) { 18 | let timeLeave = new Date(leavingTime), 19 | timeSome = new Date(someTime); 20 | let time = new Date(timeSome-(timeLeave-timeSome)); 21 | return time.toJSON().slice(0, 16).replace(/T/, ' '); 22 | } 23 | -------------------------------------------------------------------------------- /the_core/135-regularMonths/regularMonths.js: -------------------------------------------------------------------------------- 1 | /* Question : In an effort to be more innovative, your boss introduced a strange new tradition: the first day of every month you're allowed to work from home. 2 | You like this rule when the day falls on a Monday, because any excuse to skip rush hour traffic is great! 3 | 4 | You and your colleagues have started calling these months regular months. Since you're a fan of working from home, you decide to find out how far away the nearest regular month is, given that the currMonth has just started. 5 | 6 | For your convenience, here is a list of month lengths (from January to December, respectively): 7 | 8 | Month lengths: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. 9 | Please, note that in leap years February has 29 days. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/time-river/36z952jJdatJnFXGC 12 | 13 | 14 | function regularMonths(currMonth) { 15 | currMonth = currMonth.split('-') 16 | let date = new Date(`${currMonth[0]}-01-${currMonth[1]}`) 17 | date.setMonth(date.getMonth()+1) 18 | while(date.getDay() !== 1) { 19 | date.setMonth(date.getMonth()+1) 20 | } 21 | date = date.toISOString().split('-') 22 | return `${date[1]}-${date[0]}` 23 | } 24 | -------------------------------------------------------------------------------- /the_core/136-missedClasses/missedClasses.js: -------------------------------------------------------------------------------- 1 | /* Question : Your Math teacher takes education very seriously, and hates it when a class is missed or canceled for any reason. He even made up the following rule: 2 | if a class is missed because of a holiday, the teacher will compensate for it with a makeup class after school. 3 | 4 | You're given an array, daysOfTheWeek, with the weekdays on which your teacher's classes are scheduled, and holidays, representing the dates of the holidays 5 | throughout the academic year (from 1st of September in year to 31st of May in year + 1). How many times will you be forced to stay after school for a makeup class because of holiday conflicts in the current academic year? 6 | 7 | For your convenience, here is the list of month lengths (from January to December, respectively): 8 | 9 | Month lengths: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. 10 | Please note that in leap years February has 29 days. */ 11 | 12 | // URL : https://app.codesignal.com/arcade/code-arcade/time-river/WBjidxs6TBgJqp2RG 13 | 14 | 15 | function missedClasses(year, daysOfTheWeek, holidays) { 16 | daysOfTheWeek = daysOfTheWeek.map(d => d===7?0:d) 17 | let result = 0 18 | holidays.forEach(h => { 19 | let newH = h.split('-') 20 | if(Number(newH[0])>=8){ 21 | let date = new Date(`${h}-${year}`) 22 | if(daysOfTheWeek.some(d => d === date.getDay())) result++ 23 | } else { 24 | let date = new Date(`${h}-${year + 1}`) 25 | if(daysOfTheWeek.some(d => d === date.getDay())) result++ 26 | } 27 | }) 28 | 29 | return result 30 | } 31 | 32 | -------------------------------------------------------------------------------- /the_core/137-holiday/holiday.js: -------------------------------------------------------------------------------- 1 | /* Question : John Doe likes holidays very much, and he was very happy to hear that his country's government decided to introduce yet another one. 2 | He heard that the new holiday will be celebrated each year on the xth week of month, on weekDay. 3 | 4 | Your task is to return the day of month on which the holiday will be celebrated in the year yearNumber. 5 | 6 | For your convenience, here are the lists of months names and lengths and the list of days of the week names. 7 | 8 | Months: "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December". 9 | Months lengths: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. 10 | Days of the week: "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday". 11 | Please, note that in leap years February has 29 days. */ 12 | 13 | // URL : https://app.codesignal.com/arcade/code-arcade/time-river/4JypHBf7kQc3GjhRF 14 | 15 | 16 | function holiday(x, weekDay, month, yearNumber) { 17 | const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] 18 | const days = ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] 19 | let m = months.findIndex(x => x === month) 20 | let day = days.findIndex(x => x === weekDay) 21 | let date = new Date(yearNumber, m , 1) 22 | let count = 0 23 | 24 | while(count < x && date.getMonth() === m) { 25 | if(date.getDay() === day){ 26 | count++ 27 | if(count === x)break 28 | } 29 | date.setDate(date.getDate()+1) 30 | } 31 | return date.getMonth() === m? date.getDate():-1 32 | } -------------------------------------------------------------------------------- /the_core/138-isSentenceCorrect/isSentenceCorrect.js: -------------------------------------------------------------------------------- 1 | /* Question : A sentence is considered correct if: 2 | 3 | it starts with a capital letter; 4 | it ends with a full stop, question mark or exclamation point ('.', '?' or '!'); 5 | full stops, question marks and exclamation points don't appear anywhere else in the sentence. 6 | Given a sentence, return true if it is correct and false otherwise. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/mj4qdJqZknbkHNzhK 9 | 10 | 11 | function isSentenceCorrect(sentence) { 12 | var re = /^[A-Z][^.?!]*[.?!]$/; 13 | return re.test(sentence); 14 | } -------------------------------------------------------------------------------- /the_core/139-replaceAllDigitsRegEx/replaceAllDigitsRegEx.js: -------------------------------------------------------------------------------- 1 | /* Question : Implement a function that replaces each digit in the given string with a '#' character. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/YhqzFvdnHMffQA22q 4 | 5 | 6 | function replaceAllDigitsRegEx(input) { 7 | return input.replace(/\d/g,"#") ; 8 | } 9 | -------------------------------------------------------------------------------- /the_core/14-tennisSet/tennisSet.js: -------------------------------------------------------------------------------- 1 | /* Question : In tennis, the winner of a set is based on how many games each player wins. The first player to win 6 games is declared the winner unless their opponent had already won 5 games, 2 | in which case the set continues until one of the players has won 7 games. 3 | Given two integers score1 and score2, your task is to determine if it is possible for a tennis set to be finished with a final score of score1 : score2. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/7jaup9HprdJno2diw 6 | 7 | 8 | function tennisSet(score1, score2) { 9 | var max = Math.max(score1, score2), 10 | min = Math.min(score1, score2); 11 | return (max == 6 && min < 5) || (max == 7 && min >= 5 && min <=6); 12 | } 13 | -------------------------------------------------------------------------------- /the_core/140-swapAdjacentWords/swapAdjacentWords.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given a string consisting of words separated by whitespace characters, 2 | where the words consist only of English letters. Your task is to swap pairs of 3 | consecutive words and return the result. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/AMx2WqCoq2PEcJTEp 6 | 7 | 8 | function swapAdjacentWords(s) { 9 | return s.replace(/(\w+) (\w+)/g, "$2 $1"); 10 | } -------------------------------------------------------------------------------- /the_core/141-nthNumber/nthNumber.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given a string s of characters that contains at least n numbers (here, a number is defined as 2 | a consecutive series of digits, where any character immediately to the left and right of the series 3 | are not digits). The numbers may contain leading zeros, but it is guaranteed that each number has at 4 | least one non-zero digit in it. 5 | 6 | Your task is to find the nth number and return it as a string without leading zeros. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/Rqtm4Yv8GhHYXJYPY 9 | 10 | 11 | function nthNumber(s, n) { 12 | var re = new RegExp(`(?:0*(\\d+)\\D*){${n}}`); 13 | return re.exec(s)[1]; 14 | } -------------------------------------------------------------------------------- /the_core/142-isSubsequence/isSubsequence.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a string s, determine if it is a subsequence of a given string t. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/E6eYu8dsfwch2My27 4 | 5 | 6 | function isSubsequence(t, s) { 7 | var pattern = ""; 8 | for (var i = 0; i < s.length; i++) { 9 | pattern += "["+s[i]+"].*" ; 10 | } 11 | var re = new RegExp(pattern); 12 | return re.test(t); 13 | } -------------------------------------------------------------------------------- /the_core/143-eyeRhyme/eyeRhyme.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a string s, determine if it is a subsequence of a given string t. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/tsMpGZTEgq6D6uvaA 4 | 5 | 6 | function eyeRhyme(t, s) { 7 | var pattern = ""; 8 | for (var i = 0; i < s.length; i++) { 9 | pattern += "["+s[i]+"].*" ; 10 | } 11 | var re = new RegExp(pattern); 12 | return re.test(t); 13 | } -------------------------------------------------------------------------------- /the_core/144-programTranslation/programTranslation.js: -------------------------------------------------------------------------------- 1 | /* Question : As an avid user of CodeSignal, you find it frustrating that there are no debugging and recovery tasks in your favorite language, PHP. 2 | You decide to help the platform by translating solutions in JavaScript into PHP. You quickly discover that this approach is quite convenient: 3 | sometimes all you have to do is substitute the function arguments by adding the $ sign in front of them. At first you do this manually, 4 | but soon realize that it won't get you far enough. 5 | 6 | Now you need to implement a function that, given a code written in JavaScript and its args, adds a $ sign in front of each args[i] (unless 7 | there is already a dollar sign present). 8 | 9 | Given a code in JavaScript and its args, return the almost-PHP solution. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/WwsFwv42dzLJJFmAE 12 | 13 | 14 | function programTranslation(code, args) { 15 | var argumentVariants = args.join('|'); 16 | var re = new RegExp("(\\W)\\$?("+argumentVariants+")(?=\\W)", "g"); 17 | var sub = "$1$$$2"; 18 | return code.replace(re, sub); 19 | } 20 | -------------------------------------------------------------------------------- /the_core/145-repetitionEncryption/repetitionEncryption.js: -------------------------------------------------------------------------------- 1 | /* Question : Jane just got a letter from her friend and realized that something's wrong: some words in the letter are written twice in a row. 2 | The thing is, she and her friend devised an ingenious cypher, the key to which is the number of pairs of repeated words in the encoded text. 3 | The cases of the words don't matter. 4 | 5 | Formally, a word is a substring of letter consisting of English letters, such that characters to the left of the leftmost letter and to the 6 | right of the rightmost letter are not letters. 7 | 8 | For obvious reasons, Jane can't tell you how the encryption works, but she needs your help with calculating the number of pairs of consecutive equal words. 9 | Write a function that, given a letter, returns this number. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/regular-hell/jyaMHzCG4SGoEjASE 12 | 13 | 14 | function repetitionEncryption(letter) { 15 | var pattern = /([A-Z]+)[^A-Z]+\1\b/ig; 16 | var matches = letter.match(pattern); 17 | if (matches) { 18 | return matches.length; 19 | } 20 | else { 21 | return 0; 22 | } 23 | } -------------------------------------------------------------------------------- /the_core/147-LRCAndSubRip/LRCAndSubRip.js: -------------------------------------------------------------------------------- 1 | /* Question : During your most recent trip to Codelandia you decided to buy a brand new CodePlayer, a music player that (allegedly) can work with any possible media format. 2 | As it turns out, this isn't true: the player can't read lyrics written in the LRC format. It can, however, read the SubRip format, so now you want to translate 3 | all the lyrics you have from LRC to SubRip. 4 | 5 | Since you are a pro programmer (no noob would ever get to Codelandia!), you're happy to implement a function that, given lrcLyrics and songLength, returns the 6 | lyrics in SubRip format. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/secret-archives/oAwCH6ecrzA4ARb6d 9 | 10 | 11 | function LRCAndSubRip(lrcLyrics, songLength) { 12 | timeConverter = t => { 13 | [,m,s,x] = t.match(/(\d\d):(\d\d).(\d\d)/) 14 | h = (m - m % 60) / 60 15 | m = m % 60 16 | console.log([h,m,s,x]) 17 | return ('00'+h).slice(-2) + ':' + 18 | ('00'+m).slice(-2) + ':' + 19 | ('00'+s).slice(-2) + ',' + x + '0' 20 | } 21 | lrcLyrics = lrcLyrics.map(x => /\[(.+)\] ?(.*)/g.exec(x)) 22 | .map(x => ({time: timeConverter(x[1]), text: x[2]})) 23 | var subRip = [], i; 24 | for (i = 0; i < lrcLyrics.length; ++i) { 25 | t1 = lrcLyrics[i].time 26 | t2 = lrcLyrics[i+1] ? lrcLyrics[i+1].time : songLength + ',000' 27 | if (i > 0) subRip.push('') 28 | subRip.push(''+(i+1)) 29 | subRip.push(t1 + ' --> ' + t2) 30 | subRip.push(lrcLyrics[i].text) 31 | } 32 | return subRip 33 | } -------------------------------------------------------------------------------- /the_core/148-HTMLTable/HTMLTable.js: -------------------------------------------------------------------------------- 1 | /* Question : HTML tables allow web developers to arrange data into rows and columns of cells. They are created using the tag. Its content consists of one or 2 | more rows denoted by the tag. Further, the content of each row comprises one or more cells denoted by the (.+?)<\/tr>/g 16 | matchCell = /
tag, and content within the tags 3 | is what site visitors see in the table. For this task assume that tags have no attributes in contrast to real world HTML. 4 | 5 | Some tables contain the tag. This tag defines header cells, which shouldn't be counted as regular cells. 6 | 7 | You are given a rectangular HTML table. Extract the content of the cell with coordinates (row, column). 8 | 9 | If you are not familiar with HTML, check out this note. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/secret-archives/mnELCFheQvkbcytcz 12 | 13 | 14 | function HTMLTable(table, row, column) { 15 | matchRow = /
(.+?)<\/td>/g 17 | for (r = i = 0; i <= row ; ++i) 18 | r = matchRow.exec(table) 19 | for (c = i = 0; r && i <= column; ++i) 20 | c = matchCell.exec(r[1]) 21 | return c ? c[1] : "No such cell" 22 | } 23 | -------------------------------------------------------------------------------- /the_core/149-chessNotation/chessNotation.js: -------------------------------------------------------------------------------- 1 | /* Question : John has always had trouble remembering chess game positions. To help himself with remembering, he decided to store game positions in strings. He came up with the following position notation: 2 | 3 | The notation is built for the current game position row by row from top to bottom, with '/' separating each row notation; 4 | Within each row, the contents of each square are described from the leftmost column to the rightmost; 5 | Each piece is identified by a single letter taken from the standard English names ('P' = pawn, 'N' = knight, 'B' = bishop, 'R' = rook, 'Q' = queen, 'K' = king); 6 | White pieces are designated using upper-case letters ("PNBRQK") while black pieces use lowercase ("pnbrqk"); 7 | Empty squares are noted using digits 1 through 8 (the number of empty squares from the last piece); 8 | Empty lines are noted as "8". 9 | For example, for the initial position (shown in the picture below) the notation will look like this: 10 | 11 | "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR" */ 12 | 13 | // URL : https://app.codesignal.com/arcade/code-arcade/secret-archives/qSvgj5FdyeuxTN9qJ 14 | 15 | 16 | function chessNotation(letter) { 17 | var pattern = /([A-Z]+)[^A-Z]+\1\b/ig; 18 | var matches = letter.match(pattern); 19 | if (matches) { 20 | return matches.length; 21 | } 22 | else { 23 | return 0; 24 | } 25 | } -------------------------------------------------------------------------------- /the_core/15-willYou/willYou.js: -------------------------------------------------------------------------------- 1 | /* Question : Once Mary heard a famous song, and a line from it stuck in her head. That line was "Will you still love me when I'm no longer young and beautiful?". 2 | Mary believes that a person is loved if and only if he/she is both young and beautiful, but this is quite a depressing thought, so she wants to put her belief to the test. 3 | 4 | Knowing whether a person is young, beautiful and loved, find out if they contradict Mary's belief. 5 | 6 | A person contradicts Mary's belief if one of the following statements is true: 7 | 8 | they are young and beautiful but not loved; 9 | they are loved but not young or not beautiful. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/sgDWKCFQHHi5D3Szj 12 | 13 | 14 | function extraNumber(young, beautiful, loved) { 15 | return (young && beautiful) != loved; 16 | } 17 | -------------------------------------------------------------------------------- /the_core/151-firstOperationalCharacter/firstOperationalCharacter.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a string which represents a valid arithmetic expression, find the index of the character in the given expression corresponding to the arithmetic operation which 2 | needs to be computed first. 3 | 4 | Note that several operations of the same type with equal priority are computed from left to right. 5 | 6 | See the explanation of the third example for more details about the operations priority in this problem. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/secret-archives/r8LM3RsxeGFXpr8Bj 9 | 10 | 11 | function firstOperationalCharacter(expr) { 12 | const mulIn = expr.match(/\([^()]*\d+ *\* *\d+[^()]*\)/) 13 | , sumIn = expr.match(/\([^()]*\d+ *\+ *\d+[^()]*\)/) 14 | , mul = expr.match(/\d+ *\* *\d+/) 15 | , sum = expr.match(/\d+ *\+ *\d+/); 16 | 17 | if(mulIn) return mulIn.index + mulIn[0].indexOf('*'); 18 | if(sumIn) return sumIn.index + sumIn[0].indexOf('+'); 19 | if(mul) return mul.index + mul[0].indexOf('*'); 20 | if(sum) return sum.index + sum[0].indexOf('+'); 21 | } 22 | -------------------------------------------------------------------------------- /the_core/152-countElements/countElements.js: -------------------------------------------------------------------------------- 1 | /* Question : You've been invited to a job interview at a famous company that tests programming challenges. To evaluate your coding skills, they have asked you to parse a 2 | given problem's input given as an inputString string, and count the number of primitive type elements within it. 3 | 4 | The inputString can be either a primitive type variable or an array (possibly multidimensional) that contains elements of the primitive types. 5 | A primitive type variable can be: 6 | 7 | an integer number; 8 | a string, which is surrounded by " characters (note that it may contain any character except "); 9 | a boolean, which is either true or false. 10 | Return the total number of primitive type elements inside inputString. */ 11 | 12 | // URL : https://app.codesignal.com/arcade/code-arcade/secret-archives/SFmoZujtxtwzqJhuB 13 | 14 | 15 | function countElements(inputString) { 16 | return (inputString.match(/".*?"|-?\d+|true|false/g)||[]).length 17 | } 18 | -------------------------------------------------------------------------------- /the_core/153-treeBottom/treeBottom.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given a recursive notation of a binary tree: each node of a tree is represented as a set of three elements: 2 | 3 | value of the node; 4 | left subtree; 5 | right subtree. 6 | So, a tree can be written as (value left_subtree right_subtree). It is guaranteed that 1 ≤ value ≤ 109. If a node doesn't exist 7 | then it is represented as an empty set: (). For example, here is a representation of a tree in the given picture: 8 | 9 | (2 (7 (2 () ()) (6 (5 () ()) (11 () ()))) (5 () (9 (4 () ()) ()))) 10 | 11 | 12 | Your task is to obtain a list of nodes, that are the most distant from the tree root, in the order from left to right. 13 | 14 | In the notation of a node its value and subtrees are separated by exactly one space character. 15 | */ 16 | 17 | // URL : https://app.codesignal.com/arcade/code-arcade/secret-archives/ptyXoxtZfrPSNRe5m 18 | 19 | 20 | function treeBottom(tree) { 21 | var d = 0, l = 0; 22 | return tree.match(/\(|\)|\d+/g).reduce((r, c) => { 23 | if (c == '(') ++d 24 | else if (c == ')') --d 25 | else if (l == d) r.push(c|0) 26 | else if (l < d) { 27 | r = [c|0] 28 | l = d 29 | } 30 | return r 31 | }, []) 32 | } 33 | -------------------------------------------------------------------------------- /the_core/154-befunge/befunge.js: -------------------------------------------------------------------------------- 1 | /* Question : .... */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/secret-archives/W59RqZTbGo2vwNSsc 4 | 5 | 6 | function befunge(program) { 7 | var stack = [], out = '', dir = '>', i = 0, j = 0, v, k = 0, s = 1 8 | n = program.length, m = program[0].length, str = 0; 9 | while (((v = program[i][j]) !== '@' || str) && 10 | k++ < 100000 && out.length < 100) { 11 | //if (k < 1000) console.log([v,i,j,out,stack.slice(-5),dir]) 12 | if (v == '"') { 13 | str = 1 - str 14 | } 15 | if (str) { 16 | if (v != '"') stack.push(v.charCodeAt(0)) 17 | if (dir == '^') i = (n + i - 1) % n 18 | if (dir == 'v') i = (n + i + 1) % n 19 | if (dir == '<') j = (m + j - 1) % m 20 | if (dir == '>') j = (m + j + 1) % m 21 | continue 22 | } 23 | if (!stack.length) stack = [0,0] 24 | if ('<>v^'.indexOf(v) > -1) dir = v 25 | if (v == '_') dir = stack.pop() | 0 ? '<' : '>' 26 | if (v == '|') dir = stack.pop() | 0 ? '^' : 'v' 27 | s = v == '#' ? 2 : 1 28 | if (dir == '^') i = (n + i - s) % n 29 | if (dir == 'v') i = (n + i + s) % n 30 | if (dir == '<') j = (m + j - s) % m 31 | if (dir == '>') j = (m + j + s) % m 32 | if ('+-*/%'.indexOf(v) > -1) { 33 | a = stack.pop() 34 | b = stack.pop() 35 | stack.push(eval(b + v + a) | 0) 36 | } 37 | if (v == '!') stack.push(stack.pop() ? 0 : 1) 38 | if (v == '`') stack.push(stack.pop() < stack.pop() ? 1 : 0) 39 | if (v == ':') stack.push(stack.slice(-1)[0]) 40 | if (v == '\\') stack = stack.concat([stack.pop(), stack.pop()]) 41 | if (v == '$') stack.pop() 42 | if (v == '.') out += stack.pop() + ' ' 43 | if (v == ',') out += String.fromCharCode(stack.pop()) 44 | if (v.match(/\d/)) stack.push(v) 45 | } 46 | return out 47 | } 48 | -------------------------------------------------------------------------------- /the_core/156-game2048/game2048.js: -------------------------------------------------------------------------------- 1 | /* Question : ... */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/cliffs-of-pain/J8sBSYmWuWaNg6iXd 4 | 5 | 6 | function game2048(grid, dir) { 7 | if(dir === 'L' || dir === 'R') return grid; 8 | return grid.map((_, i) => grid.map((_, j) => grid[3-j][i])); 9 | } 10 | 11 | 12 | function move(grid, dir) { 13 | const reg = /\b(\d+) \1\b/g; 14 | const replacer = (m, p) => p*2; 15 | const arr = [0,0,0,0]; 16 | 17 | if(dir === 'L' || dir === 'D') return grid.map((row, i) => ( 18 | row.filter(Boolean) 19 | .join` ` 20 | .replace(reg, replacer) 21 | .split` ` 22 | .map(Number) 23 | .concat(arr) 24 | .slice(0,4) 25 | )); 26 | 27 | return grid.map((row, i) => ( 28 | arr.concat(row.filter(Boolean) 29 | .reverse() 30 | .join` ` 31 | .replace(reg, replacer) 32 | .split` ` 33 | .map(Number) 34 | .reverse()) 35 | .slice(-4) 36 | )); 37 | } 38 | 39 | 40 | function reverseRotate(grid, dir) { 41 | if(dir === 'L' || dir === 'R') return grid; 42 | return grid.map((_, i) => grid.map((_, j) => grid[j][3-i])); 43 | } 44 | -------------------------------------------------------------------------------- /the_core/157-snakeGame/snakeGame.js: -------------------------------------------------------------------------------- 1 | /* Question : Your task is to imitate a turn-based variation of the popular "Snake" game. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/cliffs-of-pain/P2ECpmqBqtm4jmRXC 4 | 5 | 6 | function snakeGame(gameBoard, commands) { 7 | let dir, snake=[], dirs={'^':[-1,0,'v','<','>'], 'v':[1,0,'^','>','<'], '<':[0,-1,'>','v','^'], '>':[0,1,'<','^','v']}; 8 | out=(i,j)=>(i<0 || j<0 || i>=gameBoard.length || j>=gameBoard[0].length); 9 | move=(i,j)=>(out(i,j) || gameBoard[i][j]!='.') ? 0 : snake.unshift([i,j,dir]); 10 | addSeg=(i,j,d)=>(out(i,j) || gameBoard[i][j]!='*') ? 0 : snake.push([i,j,d]); 11 | getSnake=(i,j,d)=>{ 12 | let n = snake.length; 13 | Object.keys(dirs).map(x=>x==d ? 0 : addSeg(i+dirs[x][0], j+dirs[x][1], dirs[x][2])); 14 | if (snake.length!=n) getSnake(...snake[n]); 15 | } 16 | 17 | gameBoard.map((x,i)=>x.map((y,j)=>(y=='.'||y=='*') ? 0 : snake.push([i,j,dir=gameBoard[i][j]]))); // get snake head 18 | getSnake(...snake[0]); // push snake to an array 19 | 20 | for (let i=0; igameBoard[x[0]][x[1]]='X'); 27 | return gameBoard; 28 | } else gameBoard[snake[0][0]][snake[0][1]]='*'; 29 | } else dir = commands[i]=='L' ? dirs[dir][3] : dirs[dir][4]; 30 | } 31 | snake.map((x,i)=>gameBoard[x[0]][x[1]] = i ? '*' : dir); // if completed commands, draw final move and return 32 | return gameBoard; 33 | } 34 | -------------------------------------------------------------------------------- /the_core/159-pyraminxPuzzle/pyraminxPuzzle.js: -------------------------------------------------------------------------------- 1 | /* Question : ... */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/cliffs-of-pain/PouBk693gQvXaCbPK 4 | 5 | 6 | function pyraminxPuzzle(faceColors, moves) { 7 | let p = faceColors.map(x=>new Array(9).fill(x)), f = {u:[0,2,3], b:[1,3,2], l:[2,0,1], r:[3,1,0]}; 8 | swap=(i,j,a,b)=>[p[a[0]][j], p[a[b]][i]] = [p[a[b]][i], p[a[0]][j]]; 9 | move=(m)=>{ 10 | let c = m[0].toLowerCase(), d = [4,8].map((x,i)=>swap(x, 0, f[c], i+1)); 11 | if (c==m[0]) [6,3,5,7,1,6].map((x,i)=>swap(x, (i%2 ? i+1 : i+2)/2, f[c], i%2+1)); 12 | if (m.length>1) move(m[0]); // rotate again if clockwise 13 | } 14 | moves.reverse().map(x=>move(x)); 15 | return p; 16 | } 17 | -------------------------------------------------------------------------------- /the_core/16-metroCard/metroCard.js: -------------------------------------------------------------------------------- 1 | /* Question : You just bought a public transit card that allows you to ride the Metro for a certain number of days. 2 | Here is how it works: upon first receiving the card, the system allocates you a 31-day pass, which equals the number of days in January. 3 | The second time you pay for the card, your pass is extended by 28 days, i.e. the number of days in February (note that leap years are not considered), and so on. 4 | The 13th time you extend the pass, you get 31 days again. 5 | 6 | You just ran out of days on the card, and unfortunately you've forgotten how many times your pass has been extended so far. However, you do remember 7 | the number of days you were able to ride the Metro during this most recent month. Figure out the number of days by which your pass will now be extended, 8 | and return all the options as an array sorted in increasing order. */ 9 | 10 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/J7PQDxpWqhx7HrvBZ 11 | 12 | 13 | function metroCard(lastNumberOfDays) { 14 | var result = { 15 | 30: [31], 16 | 28: [31], 17 | 31: [28, 30, 31] 18 | }; 19 | return result[lastNumberOfDays]; 20 | } 21 | -------------------------------------------------------------------------------- /the_core/161-fractal/fractal.js: -------------------------------------------------------------------------------- 1 | /* Question : ... */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/cliffs-of-pain/7g9K4ZqrmE6yad5P7 4 | 5 | 6 | function linesGame(n) { 7 | A = "-BF+AFA+FB-" 8 | B = "+AF-BFB-FA+" 9 | c = "A" 10 | for (i = 0; i < n; i++) 11 | c = c.replace(/A|B/g, c => ({A:A, B:B})[c]) 12 | c = c.replace(/A|B/g, "") 13 | if (n % 2 == 0) { 14 | c = [...c].reverse().join``.replace(/\+|\-/g, c => c == "+" ? "-" : "+") 15 | k = 1 16 | } else { 17 | k = 0 18 | } 19 | 20 | T = Array(2 ** n).fill().map(v => Array(2 ** n * 2 - 1).fill(' ')) 21 | d = [[1,0], [0,1], [-1,0], [0, -1]] 22 | n = 0 23 | y = x = p = 0 24 | for (i of c) { 25 | if (i == 'F') { 26 | if (k == 0) { 27 | y += d[k][0] 28 | x += d[k][1] 29 | T[y][x] = '|' 30 | } else if (k == 1 || k == 3) { 31 | if (p == k) 32 | T[y][x] = '_' 33 | y += d[k][0] 34 | x += d[k][1] 35 | T[y][x] = '_' 36 | y += d[k][0] 37 | x += d[k][1] 38 | } else { 39 | T[y][x] = '|' 40 | y += d[k][0] 41 | x += d[k][1] 42 | } 43 | p = k 44 | } else if (i == '+') { 45 | k = (k + 4 - 1) % 4 46 | } else { 47 | k = (k + 1) % 4 48 | } 49 | } 50 | return T 51 | } 52 | -------------------------------------------------------------------------------- /the_core/17-killKthBit/killKthBit.js: -------------------------------------------------------------------------------- 1 | /* Question : Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. 2 | In order to stop the Mad Coder evil genius you need to decipher the encrypted message he sent to his minions. 3 | The message contains several numbers that, when typed into a supercomputer, will launch a missile into the sky blocking out the sun, and making all the people on Earth grumpy and sad. 4 | 5 | You figured out that some numbers have a modified single digit in their binary representation. More specifically, in the given number n the kth bit 6 | from the right was initially set to 0, but its current value might be different. It's now up to you to write a function that will change the kth bit of n back to 0. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/corner-of-0s-and-1s/b5z4P2r2CGCtf8HCR 9 | 10 | 11 | function killKthBit(n, k) { 12 | return n & ~(1 << k - 1); 13 | } 14 | -------------------------------------------------------------------------------- /the_core/18-arrayPacking/arrayPacking.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given an array of up to four non-negative integers, each less than 256. 2 | 3 | Your task is to pack these integers into one number M in the following way: 4 | 5 | The first element of the array occupies the first 8 bits of M; 6 | The second element occupies next 8 bits, and so on. 7 | Return the obtained integer M. 8 | 9 | Note: the phrase "first bits of M" refers to the least significant bits of M - the right-most bits of an integer. For further clarification see the following example. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/corner-of-0s-and-1s/KeMqde6oqfF5wBXxf 12 | 13 | 14 | function arrayPacking(a) { 15 | return a.reduce((value, byte, i) => value + byte * Math.pow(256, i)); 16 | } 17 | -------------------------------------------------------------------------------- /the_core/19-rangeBitCount/rangeBitCount.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given two numbers a and b where 0 ≤ a ≤ b. Imagine you construct an array of all the integers from a to b inclusive. 2 | You need to count the number of 1s in the binary representations of all the numbers in the array. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/corner-of-0s-and-1s/eC2Zxu5H5SnuKxvPT 5 | 6 | 7 | function rangeBitCount(a, b) { 8 | var packed = ""; 9 | while(a <= b){ 10 | packed += a.toString(2); 11 | a++; 12 | } 13 | return packed.split('1').length-1; 14 | } 15 | -------------------------------------------------------------------------------- /the_core/20-mirrorBits/mirrorBits.js: -------------------------------------------------------------------------------- 1 | /* Question : Reverse the order of the bits in a given integer. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/at-the-crossroads/sgDWKCFQHHi5D3Szj 4 | 5 | 6 | function mirrorBits(a) { 7 | return parseInt([...a.toString(2)].reverse().join(''), 2); 8 | } 9 | -------------------------------------------------------------------------------- /the_core/21-secondRightMostZeroBit/secondRightMostZeroBit.js: -------------------------------------------------------------------------------- 1 | /* Question : Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. 2 | Presented with the integer n, find the 0-based position of the second rightmost zero bit in its binary representation (it is guaranteed that such a bit exists), counting from right to left. 3 | 4 | Return the value of 2position_of_the_found_bit. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/corner-of-0s-and-1s/9nSj6DgqLDsBePJha 7 | 8 | function secondRightMostZeroBit(n) { 9 | return Math.pow(2,n.toString(2).split('').reverse().join("").split("0", 2).join("0").length); 10 | } 11 | -------------------------------------------------------------------------------- /the_core/22-swapAdjacentBit/swapAdjacentBit.js: -------------------------------------------------------------------------------- 1 | /* Question : You're given an arbitrary 32-bit integer n. Take its binary representation, split bits into it in pairs (bit number 0 and 1, bit number 2 and 3, etc.) 2 | and swap bits in each pair. Then return the result as a decimal number. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/corner-of-0s-and-1s/dShYZZT4WmvpmfpgB 5 | 6 | 7 | function swapAdjacentBits(n) { 8 | return ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1); 9 | } 10 | -------------------------------------------------------------------------------- /the_core/23-differentRightmostBit/differentRightMostBit.js: -------------------------------------------------------------------------------- 1 | /* Question : You're given two integers, n and m. Find position of the rightmost bit in which they differ in their binary representations (it is guaranteed that such a bit exists), counting from right to left. 2 | 3 | Return the value of 2position_of_the_found_bit (0-based). */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/corner-of-0s-and-1s/whz5JzszYTdXW6aNA 6 | 7 | 8 | function differentRightMostBit(n, m) { 9 | return (n^m) & -(n^m); 10 | } 11 | -------------------------------------------------------------------------------- /the_core/24-equalPairOfBits/equalPairOfBits.js: -------------------------------------------------------------------------------- 1 | /* Question : You're given two integers, n and m. Find position of the rightmost pair of equal bits in their binary representations (it is guaranteed that such a pair exists), counting from right to left. 2 | 3 | Return the value of 2position_of_the_found_pair (0-based). */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/corner-of-0s-and-1s/6SLJChm9N3fEgr2R7 6 | 7 | 8 | function equalPairOfBits(n, m) { 9 | return ~(n ^ m) & -(~(n ^ m)); 10 | } 11 | -------------------------------------------------------------------------------- /the_core/25-leastFactorial/leastFactorial.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an integer n, find the minimal k such that 2 | 3 | k = m! (where m! = 1 * 2 * ... * m) for some integer m; 4 | k >= n. 5 | In other words, find the smallest factorial which is not less than n. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/7BFPq6TpsNjzgcpXy 8 | 9 | 10 | function leastFactorial(n) { 11 | var k = 1; 12 | for (var i = 2; k < n; i++) 13 | k *= i; 14 | return k; 15 | } 16 | -------------------------------------------------------------------------------- /the_core/26-countSumOfTwoRepresentations2/countSumOfTwoRepresentations2.js: -------------------------------------------------------------------------------- 1 | /* Question : Given integers n, l and r, find the number of ways to represent n as a sum of two integers A and B such that l ≤ A ≤ B ≤ r. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/hBw5BJiZ4LmXcy92u 4 | 5 | 6 | function countSumOfTwoRepresentations2(n, l, r) { 7 | return Math.max(Math.min(Math.floor(n / 2) - l, r - Math.ceil(n / 2)) + 1, 0); 8 | } 9 | -------------------------------------------------------------------------------- /the_core/27-magicWell/magicWell.js: -------------------------------------------------------------------------------- 1 | /* Question : You are standing at a magical well. It has two positive integers written on it: a and b. Each time you cast a magic marble into the well, 2 | it gives you a * b dollars and then both a and b increase by 1. You have n magic marbles. How much money will you make? */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/LbuWRHnMoJH9SAo4o 5 | 6 | 7 | function leastFactorial(a, b, n) { 8 | return n != 0 ? a * b + solution(++a, ++b, --n) : 0; 9 | } 10 | -------------------------------------------------------------------------------- /the_core/28-lineUp/lineUp.js: -------------------------------------------------------------------------------- 1 | /* Question : To prepare his students for an upcoming game, the sports coach decides to try some new training drills. To begin with, he lines them up and starts 2 | with the following warm-up exercise: when the coach says 'L', he instructs the students to turn to the left. Alternatively, when he says 'R', 3 | they should turn to the right. Finally, when the coach says 'A', the students should turn around. 4 | 5 | Unfortunately some students (not all of them, but at least one) can't tell left from right, meaning they always turn right when they hear 'L' and 6 | left when they hear 'R'. The coach wants to know how many times the students end up facing the same direction. 7 | 8 | Given the list of commands the coach has given, count the number of such commands after which the students will be facing the same direction. */ 9 | 10 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/8rqs3BLpdKePhouQM 11 | 12 | 13 | function lineUp(commands) { 14 | var result = 0, 15 | same = true; 16 | for (var i = 0; i < commands.length; i++) { 17 | var command = commands[i]; 18 | if (command == 'L' || command == 'R') { 19 | same = !same; 20 | } 21 | if (same) result++; 22 | } 23 | return result; 24 | } 25 | -------------------------------------------------------------------------------- /the_core/29-additionWithoutCarrying/additionWithoutCarrying.js: -------------------------------------------------------------------------------- 1 | /* Question : A little child is studying arithmetic. They have just learned how to add two integers, written one below another, column by column. But the child always forgets about the important part - carrying. 2 | 3 | Given two integers, your task is to find the result that the child will get. 4 | 5 | Note: The child had learned from this site, so feel free to check it out too if you are not familiar with column addition. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/xzeZqCQjpfDJuN72S 8 | 9 | 10 | function additionWithoutCarrying(param1, param2) { 11 | var result = 0, 12 | num = 1; 13 | while (param1 + param2 > 0) { 14 | num *= 10; 15 | result += (param1 + param2) % num; 16 | param1 -= param1 % num; 17 | param2 -= param2 % num; 18 | } 19 | return result; 20 | } 21 | -------------------------------------------------------------------------------- /the_core/30-appleBoxes/appleBoxes.js: -------------------------------------------------------------------------------- 1 | /* Question : You have k apple boxes full of apples. Each square box of size m contains m × m apples. You just noticed two interesting properties about the boxes: 2 | 3 | The smallest box is size 1, the next one is size 2,..., all the way up to size k. 4 | Boxes that have an odd size contain only yellow apples. Boxes that have an even size contain only red apples. 5 | Your task is to calculate the difference between the number of red apples and the number of yellow apples. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/scG8AFsPuqQGx8Qjf 8 | 9 | 10 | function leastFactorial(k) { 11 | return k * (k + 1) / (k % 2 ? -2 : 2); 12 | } 13 | -------------------------------------------------------------------------------- /the_core/31-increaseNumberRoundness/increaseNumberRoundness.js: -------------------------------------------------------------------------------- 1 | /* Question : Define an integer's roundness as the number of trailing zeroes in it. 2 | 3 | Given an integer n, check if it's possible to increase n's roundness by swapping some pair of its digits. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/KLbRMcWhaZi3dvYH5 6 | 7 | function increaseNumberRoundness(n) { 8 | return /0[1-9]/.test(n); 9 | } 10 | -------------------------------------------------------------------------------- /the_core/32-Rounders/rounders.js: -------------------------------------------------------------------------------- 1 | /* Question : We want to turn the given integer into a number that has only one non-zero digit using a tail rounding approach. This means that at each step we take the last non 0 2 | digit of the number and round it to 0 or to 10. If it's less than 5 we round it to 0 if it's larger than or equal to 5 we round it to 10 (rounding to 10 means increasing the next significant digit by 1). 3 | The process stops immediately once there is only one non-zero digit left. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/H5PP5MXvYvWXxTytH 6 | 7 | 8 | function leastFactorial(value) { 9 | var r = 0 10 | while (value > 10) { 11 | value = Math.round(value/10) 12 | r++ 13 | } 14 | return value * Math.pow(10,r) 15 | } -------------------------------------------------------------------------------- /the_core/33-candles/candles.js: -------------------------------------------------------------------------------- 1 | /* Question : Imagine a white rectangular grid of n rows and m columns divided into two parts by a diagonal line running from the upper left to the lower right corner. Now let's paint the grid in two colors according to the following rules: 2 | 3 | A cell is painted black if it has at least one point in common with the diagonal; 4 | Otherwise, a cell is painted white. 5 | Count the number of cells painted black. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/RcK4vupi8sFhakjnh 8 | 9 | 10 | function candles(n, m) { 11 | var gcd = (a, b) => b == 0 ? a : gcd(b, a % b); 12 | return n + m + gcd(n, m) - 2; 13 | } 14 | -------------------------------------------------------------------------------- /the_core/34-countBlackCells/countBlackCells.js: -------------------------------------------------------------------------------- 1 | /* Question : You have k apple boxes full of apples. Each square box of size m contains m × m apples. You just noticed two interesting properties about the boxes: 2 | 3 | The smallest box is size 1, the next one is size 2,..., all the way up to size k. 4 | Boxes that have an odd size contain only yellow apples. Boxes that have an even size contain only red apples. 5 | Your task is to calculate the difference between the number of red apples and the number of yellow apples. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/loop-tunnel/scG8AFsPuqQGx8Qjf 8 | 9 | 10 | function countBlackCells(k) { 11 | return k * (k + 1) / (k % 2 ? -2 : 2); 12 | } 13 | -------------------------------------------------------------------------------- /the_core/35-createArray/createArray.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an integer size, return array of length size filled with 1s. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/list-forest-edge/gmZFbpR9cirL3Jpf2 4 | 5 | 6 | function createArray(size) { 7 | return Array(size).fill(1); 8 | } 9 | -------------------------------------------------------------------------------- /the_core/36-arrayReplace/arrayReplace.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/list-forest-edge/mCkmbxdMsMTjBc3Bm 4 | 5 | 6 | function arrayReplace(inputArray, elemToReplace, substitutionElem) { 7 | return inputArray.map(i=> i==elemToReplace ? substitutionElem : i) 8 | } 9 | -------------------------------------------------------------------------------- /the_core/37-firstReverseTry/firstReverseTry.js: -------------------------------------------------------------------------------- 1 | /* Question : Reversing an array can be a tough task, especially for a novice programmer. Mary just started coding, so she would like to start with something 2 | basic at first. Instead of reversing the array entirely, she wants to swap just its first and last elements. 3 | 4 | Given an array arr, swap its first and last elements and return the resulting array. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/list-forest-edge/ND8nghbndTNKPP4Tb 7 | 8 | 9 | function firstReverseTry(arr) { 10 | [arr[0], arr[arr.length-1]] = [arr[arr.length-1], arr[0]]; 11 | return arr[0] === undefined ? [] : arr; 12 | } 13 | -------------------------------------------------------------------------------- /the_core/38-concatanateArrays/concatanateArrays.js: -------------------------------------------------------------------------------- 1 | /* Question : Given two arrays of integers a and b, obtain the array formed by the elements of a followed by the elements of b. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/list-forest-edge/vPJB7T28fyCeh2Ljn 4 | 5 | 6 | function concatanateArrays(a, b) { 7 | return a.concat(b) 8 | } 9 | -------------------------------------------------------------------------------- /the_core/39-removeArrayPart/removeArrayPart.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an integer size, return array of length size filled with 1s. */ 2 | 3 | // URL : Remove a part of a given array between given 0-based indexes l and r (inclusive). 4 | 5 | 6 | function removeArrayPart(inputArray, l, r) { 7 | return inputArray.slice(0,l).concat(inputArray.slice(r+1)) 8 | } 9 | -------------------------------------------------------------------------------- /the_core/40-isSmooth/isSmooth.js: -------------------------------------------------------------------------------- 1 | /* Question : We define the middle of the array arr as follows: 2 | 3 | if arr contains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; 4 | if arr contains an even number of elements, its middle is the sum of the two elements whose index numbers when counting from the beginning and from the end of the array differ by one. 5 | An array is called smooth if its first and its last elements are equal to one another and to the middle. Given an array arr, determine if it is smooth or not. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/list-forest-edge/3LmZafR9wMCWpdgra 8 | 9 | 10 | function isSmooth(arr) { 11 | l = arr.length-1; 12 | return arr[0]==arr[l] && arr[0] == arr[Math.floor(l/2)] + (l%2?arr[Math.ceil(l/2)]:0); 13 | } 14 | -------------------------------------------------------------------------------- /the_core/41-replaceMiddle/replaceMiddle.js: -------------------------------------------------------------------------------- 1 | /* Question : We define the middle of the array arr as follows: 2 | 3 | if arr contains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; 4 | if arr contains an even number of elements, its middle is the sum of the two elements whose index numbers when counting from the beginning and from the end of the array differ by one. 5 | Given array arr, your task is to find its middle, and, if it consists of two elements, replace those elements with the value of middle. Return the resulting array as the answer. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/list-forest-edge/APD5T5CybxTtfkdjL 8 | 9 | 10 | function replaceMiddle(arr) { 11 | l = arr.length - 1; 12 | if (l%2) { 13 | arr[Math.floor(l/2)] += arr[Math.ceil(l/2)]; 14 | arr.splice(Math.ceil(l/2),1); 15 | } 16 | return arr; 17 | } 18 | -------------------------------------------------------------------------------- /the_core/42-makeArrayConsecutive2/makeArrayConsecutive2.js: -------------------------------------------------------------------------------- 1 | /* Question : Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to 2 | largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/list-forest-edge/bq2XnSr5kbHqpHGJC 5 | 6 | 7 | function makeArrayConsecutive2(statues) { 8 | return Math.max(...statues) - Math.min(...statues) - statues.length + 1; 9 | } 10 | -------------------------------------------------------------------------------- /the_core/43-isPower/isPower.js: -------------------------------------------------------------------------------- 1 | /* Question : Determine if the given number is a power of some non-negative integer. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/labyrinth-of-nested-loops/yBFfNv5fTqhcacZ7w 4 | 5 | 6 | function isPower(n) { 7 | if (n == 1) return true; 8 | for (i = 2; i <= Math.sqrt(n); i++) { 9 | for (j = 2; Math.pow(i, j) < n; j++); 10 | if (Math.pow(i, j) == n) return true; 11 | } 12 | return false; 13 | } 14 | -------------------------------------------------------------------------------- /the_core/44-isSumOfConsecutive2/isSumOfConsecutive2.js: -------------------------------------------------------------------------------- 1 | /* Question : Find the number of ways to express n as sum of some (at least two) consecutive positive integers. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/labyrinth-of-nested-loops/EQSjA5PRfyHueeNkj 4 | 5 | 6 | function isSumOfConsecutive2(n) { 7 | c = 0 8 | for (i=1; in) {break}}} 14 | return c 15 | } 16 | -------------------------------------------------------------------------------- /the_core/45-squareDigitsSequence/squareDigitsSequence.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider a sequence of numbers a0, a1, ..., an, in which an element is equal to the sum of squared digits of the previous element. The sequence ends once an element that has already been in the sequence appears again. 2 | 3 | Given the first element a0, find the length of the sequence. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/labyrinth-of-nested-loops/MvX84CA5HN6GKqv7R 6 | 7 | 8 | function squareDigitsSequence(a0) { 9 | let used = new Set(); 10 | 11 | while (!used.has(a0)) { 12 | used.add(a0); 13 | a0 = a0.toString() 14 | .split('') 15 | .map(x => parseInt(x) ** 2) 16 | .reduce((a, b) => a + b) 17 | } 18 | 19 | return used.size + 1; 20 | } 21 | -------------------------------------------------------------------------------- /the_core/46-pagesNumberingWithInk/pagesNumberingWithInk.js: -------------------------------------------------------------------------------- 1 | /* Question : You work in a company that prints and publishes books. You are responsible for designing the page numbering mechanism in the printer. You know how many digits a printer can print with the leftover ink. Now you want to write a function to determine what the last page of the book is that you can number given the current page and numberOfDigits left. A page is considered numbered if it has the full number printed on it (e.g. if we are working with page 102 but have ink only for two digits then this page will not be considered numbered). 2 | 3 | It's guaranteed that you can number the current page, and that you can't number the last one in the book. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/labyrinth-of-nested-loops/pdw3izd7SpMTBJqSy 6 | 7 | 8 | function pagesNumberingWithInk(current, numberOfDigits) { 9 | while (numberOfDigits >= current.toString().length) { 10 | numberOfDigits -= current.toString().length; 11 | current++; 12 | } 13 | return current - 1; 14 | } 15 | -------------------------------------------------------------------------------- /the_core/47-comfortableNumbers/comfortableNumbers.js: -------------------------------------------------------------------------------- 1 | /* Question : Let's say that number a feels comfortable with number b if a ≠ b and b lies in the segment [a - s(a), a + s(a)], where s(x) is the sum of x's digits. 2 | 3 | How many pairs (a, b) are there, such that a < b, both a and b lie on the segment [l, r], and each number feels comfortable with the other (so a feels comfortable with b and b feels comfortable with a)? */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/labyrinth-of-nested-loops/pNfGgNk46YZ4c4RW5 6 | 7 | 8 | function comfortableNumbers(l, r) { 9 | let comfortableNumberOfPairs = 0; 10 | function sumOfDigits(a) { 11 | return a.toString().split('').reduce((a, b) => parseInt(a) + parseInt(b), 0) 12 | } 13 | function isComfortable(n,m) { 14 | const sumOfDigitsN = sumOfDigits(n), sumOfDigitsM = sumOfDigits(m); 15 | return m >= (n - sumOfDigitsN) && m <= (n + sumOfDigitsN) && n >= (m - sumOfDigitsM) 16 | && n <= (m + sumOfDigitsM) ? 1 : 0 17 | } 18 | for (i=l; i 0) 23 | w = [] 24 | 25 | m = 0 26 | x = d.map(x => 0) 27 | 28 | 29 | for(i=1; i<=n; i++) { 30 | 31 | c[d[i]]++ 32 | w[i]=0 33 | 34 | for(j=d[i]+1; j m) { 39 | m = w[i] 40 | } 41 | 42 | x[w[i]]++ 43 | } 44 | 45 | return [m, x[m]] 46 | } 47 | -------------------------------------------------------------------------------- /the_core/49-rectangleRotation/rectangleRotation.js: -------------------------------------------------------------------------------- 1 | /* Question : A rectangle with sides equal to even integers a and b is drawn on the Cartesian plane. Its center (the intersection point of its diagonals) coincides with the point (0, 0), but the sides of the rectangle are not parallel to the axes; instead, they are forming 45 degree angles with the axes. 2 | 3 | How many points with integer coordinates are located inside the given rectangle (including on its sides)? */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/labyrinth-of-nested-loops/tuKA5f3zpzkKKejJx 6 | 7 | 8 | function rectangleRotation(a, b) { 9 | var pointsA = Math.floor(Math.sqrt(a * a / 2)), 10 | pointsB = Math.floor(Math.sqrt(b * b / 2)); 11 | return (pointsA * pointsB + Math.floor((pointsA + pointsB) / 2)) * 2 + 1; 12 | } 13 | -------------------------------------------------------------------------------- /the_core/51-encloseInBrackets/encloseInBrackets.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a string, enclose it in round brackets. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/K2ieDm98sPDzzMepz 4 | 5 | 6 | function encloseInBrackets(s) { 7 | return `(${s})` 8 | } 9 | -------------------------------------------------------------------------------- /the_core/52-properNounCorrection/properNounCorrection.js: -------------------------------------------------------------------------------- 1 | /* Question : Proper nouns always begin with a capital letter, followed by small letters. 2 | 3 | Correct a given proper noun so that it fits this statement. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/2nSEQ8CGoddTJtnbo 6 | 7 | 8 | function properNounCorrection(noun) { 9 | return noun[0].toUpperCase() + noun.slice(1).toLowerCase() 10 | } 11 | -------------------------------------------------------------------------------- /the_core/53-isTandemRepeat/isTandemRepeat.js: -------------------------------------------------------------------------------- 1 | /* Question : Determine whether the given string can be obtained by one concatenation of some string to itself. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/2SDWWyHY9Xw5CpphY 4 | 5 | 6 | function isTandemRepeat(inputString) { 7 | s = inputString.slice(0, Math.floor(inputString.length / 2)) 8 | if (s + s === inputString) return true 9 | return false 10 | } 11 | -------------------------------------------------------------------------------- /the_core/54-isCaseInsensitivePallindrome/crosswordFormations.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/G9wj2j6zaWwFWsise 4 | 5 | 6 | function isCaseInsensitivePallindrome(inputString) { 7 | r = inputString.split('').reverse().join(''); 8 | return inputString.toLowerCase() == r.toLowerCase(); 9 | } 10 | -------------------------------------------------------------------------------- /the_core/55-findEmailDomain/findEmailDomain.js: -------------------------------------------------------------------------------- 1 | /* Question : An email address such as "John.Smith@example.com" is made up of a local part ("John.Smith"), an "@" symbol, then a domain part ("example.com"). 2 | 3 | The domain name part of an email address may only consist of letters, digits, hyphens and dots. The local part, however, also allows a lot of different special characters. 4 | Here you can look at several examples of correct and incorrect email addresses. 5 | 6 | Given a valid email address, find its domain part. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/TXFLopNcCNbJLQivP 9 | 10 | 11 | function findEmailDomain(address) { 12 | return address.split('@').pop(); 13 | } 14 | -------------------------------------------------------------------------------- /the_core/56-HTMLEndTagByStartTag/HTMLEndTagByStartTag.js: -------------------------------------------------------------------------------- 1 | /* Question : You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it. 2 | 3 | Given the starting HTML tag, find the appropriate end tag which your editor should propose. 4 | 5 | If you are not familiar with HTML, consult with this note. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/MX94DWTrwQw2gLrTi 8 | 9 | 10 | function HTMLEndTagByStartTag(startTag) { 11 | return ``; 12 | } 13 | -------------------------------------------------------------------------------- /the_core/57-isMacAddress/isMacAddress.js: -------------------------------------------------------------------------------- 1 | /* Question : A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. 2 | 3 | The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB). 4 | 5 | Your task is to check by given string inputString whether it corresponds to MAC-48 address or not. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/HJ2thsvjL25iCvvdm 8 | 9 | 10 | function isMacAddress(inputString) { 11 | return /([0-9A-F][0-9A-F]-){5}([0-9A-F][0-9A-F])$/.test(inputString) 12 | } 13 | -------------------------------------------------------------------------------- /the_core/58-isUnstablePair/isUnstablePair.js: -------------------------------------------------------------------------------- 1 | /* Question : Some file managers sort filenames taking into account case of the letters, others compare strings as if all of the letters are of the same case. That may lead to different ways of filename ordering. 2 | Call two filenames an unstable pair if their ordering depends on the case. 3 | To compare two filenames a and b, find the first position i at which a[i] ≠ b[i]. If a[i] < b[i], then a < b. Otherwise a > b. If such position doesn't exist, the shorter string goes first. 4 | Given two filenames, check whether they form an unstable pair. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/book-market/Ky2mjgmxnWLi6KNPp 7 | 8 | 9 | function isUnstablePair(filename1, filename2) { 10 | return (filename1 < filename2) != (filename1.toLowerCase() < filename2.toLowerCase()); 11 | } 12 | -------------------------------------------------------------------------------- /the_core/59-stringsConcentration/stringsConcentration.js: -------------------------------------------------------------------------------- 1 | /* Question : Given two strings a and b, both consisting only of lowercase English letters, your task is to calculate how many strings equal 2 | to a can be constructed using only letters from the string b? Each letter can be used only once and in one string only. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/mirror-lake/chW9F8bCgxYJBcgj3 5 | 6 | 7 | function stringsConcentration(a, b) { 8 | let count = 0; 9 | while(true){ 10 | for(let x of a){ 11 | if(b.indexOf(x) < 0) 12 | return count; 13 | b = b.replace(x,""); 14 | } 15 | count ++; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /the_core/60-isSubstitutionCipher/isSubstitutionCipher.js: -------------------------------------------------------------------------------- 1 | /* Question : A ciphertext alphabet is obtained from the plaintext alphabet by means of rearranging some characters. For example "bacdef...xyz" will be a simple ciphertext alphabet where a and b are rearranged. 2 | 3 | A substitution cipher is a method of encoding where each letter of the plaintext alphabet is replaced with the corresponding (i.e. having the same index) letter of some ciphertext alphabet. 4 | 5 | Given two strings, check whether it is possible to obtain them from each other using some (possibly, different) substitution ciphers. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/mirror-lake/rNrF4v5etMdFNKD3s 8 | 9 | 10 | function isSubstitutionCipher(string1, string2) { 11 | for (let i = 0; i < string1.length; i++) { 12 | let firstInx1 = string1.indexOf(string1[i]); 13 | let firstInx2 = string2.indexOf(string2[i]); 14 | if ((string2[firstInx1] !== string2[i]) || (string1[firstInx2] !== string1[i])) return false; 15 | } 16 | return true; 17 | } 18 | -------------------------------------------------------------------------------- /the_core/61-createAnagram/createAnagram.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given two strings s and t of the same length, consisting of uppercase English letters. Your task is to find the minimum number of "replacement operations" needed to get 2 | some anagram of the string t from the string s. A replacement operation is performed by picking exactly one character from the string s and replacing it by some other character. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/mirror-lake/BsShkFDfbkWxozmMN 5 | 6 | 7 | function createAnagram(s, t) { 8 | for(let x of s){ 9 | t = t.replace(x,""); 10 | } 11 | return t.length; 12 | } -------------------------------------------------------------------------------- /the_core/62-constructSquare/constructSquare.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a string consisting of lowercase English letters, find the largest square number which can be obtained by reordering the string's characters and replacing them with any digits you need 2 | (leading zeros are not allowed) where same characters always map to the same digits and different characters always map to different digits. 3 | 4 | If there is no solution, return -1. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/mirror-lake/rNrF4v5etMdFNKD3s 7 | 8 | 9 | function constructSquare(s) { 10 | const fn = val => 11 | Object.values([...val].reduce((pre, val) => (pre[val] = -~pre[val], pre), {})).sort().join(``); 12 | for (let i = (10 ** s.length) ** 0.5 ^ 0; i > 2; i--) { 13 | if (`${i ** 2}`.length === s.length && fn(`${i ** 2}`) === fn(s)) return i ** 2; 14 | } 15 | return -1; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /the_core/63-numbersGrouping/numbersGrouping.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given an array of integers that you want distribute between several groups. The first group should contain numbers from 1 to 104, the second should contain those from 104 + 1 to 2 * 104, ..., the 100th one should contain numbers from 99 * 104 + 1 to 106 and so on. 2 | 3 | All the numbers will then be written down in groups to the text file in such a way that: 4 | 5 | the groups go one after another; 6 | each non-empty group has a header which occupies one line; 7 | each number in a group occupies one line. 8 | Calculate how many lines the resulting text file will have. */ 9 | 10 | // URL : https://app.codesignal.com/arcade/code-arcade/mirror-lake/kGeuCkJNbqczCCqgg 11 | 12 | 13 | function numbersGrouping(a) { 14 | return a.length + new Set(a.map(x=>Math.ceil(x/10000))).size 15 | } 16 | -------------------------------------------------------------------------------- /the_core/64-differentSquares/differentSquares.js: -------------------------------------------------------------------------------- 1 | /* Question : A ciphertext alphabet is obtained from the plaintext alphabet by means of rearranging some characters. For example "bacdef...xyz" will be a simple ciphertext alphabet where a and b are rearranged. 2 | 3 | A substitution cipher is a method of encoding where each letter of the plaintext alphabet is replaced with the corresponding (i.e. having the same index) letter of some ciphertext alphabet. 4 | 5 | Given two strings, check whether it is possible to obtain them from each other using some (possibly, different) substitution ciphers. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/mirror-lake/fQpfgxiY6aGiGHLtv 8 | 9 | 10 | function differentSquares(matrix) { 11 | s = new Set(); 12 | 13 | for(i=0; i=999?18:n>=9?9:n 12 | } 13 | -------------------------------------------------------------------------------- /the_core/66-numberOfClans/numberOfClans.js: -------------------------------------------------------------------------------- 1 | /* Question : Let's call two integers A and B friends if each integer from the array divisors is either a divisor 2 | of both A and B or neither A nor B. If two integers are friends, they are said to be in the same 3 | clan. How many clans are the integers from 1 to k, inclusive, broken into? */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/mirror-lake/BLbGNY3kEcvKjBCFC 6 | 7 | 8 | function numberOfClans(divisors) { 9 | let mySet = new Set(); 10 | for(let i=1; i<=k; i+=1) { 11 | mySet.add((divisors.map(elm=> (i%elm) === 0 ? 0 : 1)).toString()) 12 | } 13 | return mySet.size 14 | } 15 | -------------------------------------------------------------------------------- /the_core/67-houseNumbersSum/houseNumbersSum.js: -------------------------------------------------------------------------------- 1 | /* Question : A boy is walking a long way from school to his home. To make the walk more fun he decides to add up 2 | all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses 3 | have numbers written on them, and on top of that the boy is regularly taking turns to change streets, 4 | so the numbers don't appear to him in any particular order. 5 | 6 | At some point during the walk the boy encounters a house with number 0 written on it, which surprises 7 | him so much that he stops adding numbers to his total right after seeing that house. 8 | 9 | For the given sequence of houses determine the sum that the boy will get. It is guaranteed that there 10 | will always be at least one 0 house on the path. */ 11 | 12 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/3QMXNwGfvLMoQwed7 13 | 14 | 15 | function houseNumbersSum(inputArray) { 16 | return inputArray.slice(0,inputArray.indexOf(0)).reduce((a,b) => a+b,0) 17 | } 18 | -------------------------------------------------------------------------------- /the_core/68-allLongestStrings/allLongestStrings.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an array of strings, return another array containing all of its longest strings. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/fzsCQGYbxaEcTr2bL 4 | 5 | 6 | function allLongestStrings(inputArray) { 7 | l=Math.max(...inputArray.map(x=>x.length)) 8 | return inputArray.filter(x=>x.length==l) 9 | 10 | } 11 | -------------------------------------------------------------------------------- /the_core/69-houseOfCats/houseOfCats.js: -------------------------------------------------------------------------------- 1 | /* Question : There are some people and cats in a house. You are given the number of legs they have all together. 2 | Your task is to return an array containing every possible number of people that could be in the 3 | house sorted in ascending order. It's guaranteed that each person has 2 legs and each cat has 4 4 | legs. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/RaWLwT2eb96hp4N5Z 7 | 8 | 9 | function houseOfCats(n) { 10 | return [...Array((legs/2)+1).keys()].filter(i=>(legs-2*i)%4==0) 11 | } 12 | -------------------------------------------------------------------------------- /the_core/70-alphabetSequence/alphabetSequence.js: -------------------------------------------------------------------------------- 1 | /* Question : Check whether the given string is a subsequence of the plaintext alphabet. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/Z9opBsx5fX6XfQJdt 4 | 5 | 6 | function alphabetSequence(s) { 7 | return s == [...new Set(s)].sort().join('') 8 | } 9 | -------------------------------------------------------------------------------- /the_core/71-minimumNumberOfcoins/minimumNumberOfcoins.js: -------------------------------------------------------------------------------- 1 | /* Question : You find yourself in Bananaland trying to buy a banana. You are super rich so you have an unlimited supply of banana-coins, but you are trying to use as few coins as possible. 2 | 3 | The coin values available in Bananaland are stored in a sorted array coins. coins[0] = 1, and for each i (0 < i < coins.length) coins[i] is divisible by coins[i - 1]. 4 | Find the minimal number of banana-coins you'll have to spend to buy a banana given the banana's price. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/sGwCfM5FzX7LhLcdk 7 | 8 | 9 | function minimumNumberOfCoins(coins, price) { 10 | for(var i = coins.length-1, count = 0; i >= 0; i--){ 11 | count += parseInt(price/coins[i]) 12 | price = price % coins[i] 13 | } 14 | return count; 15 | } 16 | -------------------------------------------------------------------------------- /the_core/72-addBorder/addBorder.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a rectangular matrix of characters, add a border of asterisks(*) to it. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/ZCD7NQnED724bJtjN 4 | 5 | 6 | function addBorder(picture) { 7 | return [x='*'.repeat(picture[0].length+2)].concat(picture.map(d=>'*'+d+'*'),x) 8 | } 9 | -------------------------------------------------------------------------------- /the_core/73-switchLights/switchLights.js: -------------------------------------------------------------------------------- 1 | /* Question : N candles are placed in a row, some of them are initially lit. For each candle from the 1st to the Nth the following algorithm is applied: if the observed candle is lit 2 | then states of this candle and all candles before it are changed to the opposite. Which candles will remain lit after applying the algorithm to all candles in the order they are placed in the line? */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/x3ix7CY93z2bwKDtG 5 | 6 | 7 | function switchLights(a) { 8 | let num = a.reduce((a,b)=> a+b,0) 9 | return a.map(elm => { 10 | if(elm === 1) num -=1 11 | return num%2 12 | }) 13 | } 14 | -------------------------------------------------------------------------------- /the_core/74-timedReading/timedReading.js: -------------------------------------------------------------------------------- 1 | /* Question : Timed Reading is an educational tool used in many schools to improve and advance reading skills. A young elementary student has just finished his very first timed reading exercise. 2 | Unfortunately he's not a very good reader yet, so whenever he encountered a word longer than maxLength, he simply skipped it and read on. 3 | 4 | Help the teacher figure out how many words the boy has read by calculating the number of words in the text he has read, no longer than maxLength. 5 | Formally, a word is a substring consisting of English letters, such that characters to the left of the leftmost letter and to the right of the rightmost letter are not letters. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/mJr7vgtN4X4ecL7ZA 8 | 9 | 10 | function timedReading(maxLength, text) { 11 | return (text.match(/\w+/g) || []).filter(elm => elm.length <= maxLength).length 12 | 13 | } 14 | -------------------------------------------------------------------------------- /the_core/75-electionsWinner/electionsWinner.js: -------------------------------------------------------------------------------- 1 | /* Question : Elections are in progress! 2 | 3 | Given an array of the numbers of votes given to each of the candidates so far, and an integer k equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election. 4 | 5 | The winner of the election must secure strictly more votes than any other candidate. If two or more candidates receive the same (maximum) number of votes, assume there is no winner at all. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/8RiRRM3yvbuAd3MNg 8 | 9 | 10 | function electionsWinner(votes, k) { 11 | m = Math.max(...votes) 12 | return k>0?votes.map(i=>i+k>m).reduce((x,y)=>x+y):votes.length-votes.filter(i=>i!=m).length==1?1:0 13 | 14 | } -------------------------------------------------------------------------------- /the_core/76-integerToStringOfFixedLength/integerToStringOfFixedLength.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a positive integer number and a certain length, we need to modify the given number to have a specified length. We are allowed to do that either by cutting out 2 | leading digits (if the number needs to be shortened) or by adding 0s in front of the original number. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/kvGfZZxGyjNbD7yxv 5 | 6 | 7 | function integerToStringOfFixedLength(number, width) { 8 | return `${number}`.padStart(width, '0').slice(-width) 9 | } -------------------------------------------------------------------------------- /the_core/77-areSimilar/areSimilar.js: -------------------------------------------------------------------------------- 1 | /* Question : Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays. 2 | Given two arrays a and b, check whether they are similar. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/xYXfzQmnhBvEKJwXP 5 | 6 | 7 | function areSimilar(a, b) { 8 | t=0 9 | i=0 10 | for(x in a) 11 | if(a[x]^b[x]) 12 | ++i, 13 | t^=a[x]^b[x] 14 | 15 | 16 | if(i==2||i==0)return !t 17 | return false 18 | } -------------------------------------------------------------------------------- /the_core/78-adaNumber/adaNumber.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider two following representations of a non-negative integer: 2 | 3 | A simple decimal integer, constructed of a non-empty sequence of digits from 0 to 9; 4 | An integer with at least one digit in a base from 2 to 16 (inclusive), enclosed between # characters, and preceded by the base, which can only be a number between 2 and 16 in the first representation. For digits from 10 to 15 characters a, b, ..., f and A, B, ..., F are used. 5 | Additionally, both representations may contain underscore (_) characters; they are used only as separators for improving legibility of numbers and can be ignored while processing a number. 6 | 7 | Your task is to determine whether the given string is a valid integer representation. 8 | 9 | Note: this is how integer numbers are represented in the programming language Ada. */ 10 | 11 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/Ghe6HWhFft8h6fR49 12 | 13 | 14 | function adaNumber(line) { 15 | line = line.replace(/_/g, ``); 16 | if (line.match(/^\d+$/)) return true; 17 | const num = line.match(/^(\d{1,2})#([0-9a-f]+)#$/i); 18 | return num ? [...num[2]].every(v => !isNaN(parseInt(v, num[1]))) && num[1] >= 2 && num[1] <= 16 : false; 19 | } 20 | -------------------------------------------------------------------------------- /the_core/79-threeSplit/threeSplit.js: -------------------------------------------------------------------------------- 1 | /* Question : You have a long strip of paper with integers written on it in a single line from left to right. You wish to cut the paper into exactly three pieces such that each piece contains at least one integer 2 | and the sum of the integers in each piece is the same. You cannot cut through a number, i.e. each initial number will unambiguously belong to one of the pieces after cutting. How many ways can you do it? 3 | 4 | It is guaranteed that the sum of all elements in the array is divisible by 3. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/well-of-integration/QmK8kHTyKqh8xDoZk 7 | 8 | 9 | function threeSplit(a) { 10 | l = [...Array(a.length).keys()].map(i=>a.slice(0,i+1).reduce((x,y)=>x+y)) 11 | b = Math.floor(l.slice(-1)[0]/3) 12 | r = [...Array(a.length-2).keys()].filter(i=>l[i]==b) 13 | return r.map(i=>l.slice(i+1,-1).filter(j=>j==2*b).length).reduce((x,y)=>x+y,0) 14 | } 15 | -------------------------------------------------------------------------------- /the_core/80-characterParity/characterParity.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a character, check if it represents an odd digit, an even digit or not a digit at all. */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/QKnGhkoi4wKr6xY9b 4 | 5 | 6 | function characterParity(symbol) { 7 | if (symbol >= '0' && symbol <= '9') { 8 | return symbol % 2 == 0 ? 'even' : 'odd'; 9 | } 10 | return 'not a digit'; 11 | 12 | } -------------------------------------------------------------------------------- /the_core/81-reflectString/reflectString.js: -------------------------------------------------------------------------------- 1 | /* Question : Define an alphabet reflection as follows: a turns into z, b turns into y, c turns into x, ..., n turns into m, m turns into n, ..., z turns into a. 2 | 3 | Define a string reflection as the result of applying the alphabet reflection to each of its characters. 4 | 5 | Reflect the given string. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/8nAgfjhDvKCpxwGWF 8 | 9 | 10 | function reflectString(inputString) { 11 | return inputString.split("").map(x => String.fromCharCode(219-x.charCodeAt(0))).join("") 12 | } -------------------------------------------------------------------------------- /the_core/82-newNumeralSystem/newNumeralSystem.js: -------------------------------------------------------------------------------- 1 | /* Question : Your Informatics teacher at school likes coming up with new ways to help you understand the material. When you started studying numeral systems, 2 | he introduced his own numeral system, which he's convinced will help clarify things. His numeral system has base 26, and its digits are represented by English capital letters - A for 0, B for 1, and so on. 3 | 4 | The teacher assigned you the following numeral system exercise: given a one-digit number, you should find all unordered pairs of one-digit numbers whose values add up to the number. */ 5 | 6 | // URL : https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/ngQTG9kra7GE9pnnK 7 | 8 | 9 | function newNumeralSystem(number) { 10 | n = number.charCodeAt(0) 11 | r = [] 12 | for(i=65; i<=n-i+65; i++) { 13 | r.push(String.fromCharCode(i) + " + " + String.fromCharCode(n-i+65)) 14 | } 15 | return r 16 | } 17 | -------------------------------------------------------------------------------- /the_core/83-cipher26/cipher26.js: -------------------------------------------------------------------------------- 1 | /* Question : You've intercepted an encrypted message, and you are really curious about its contents. You were able to find out that the message initially 2 | contained only lowercase English letters, and was encrypted with the following cipher: 3 | 4 | Let all letters from 'a' to 'z' correspond to the numbers from 0 to 25, respectively. 5 | The number corresponding to the ith letter of the encrypted message is then equal to the sum of numbers corresponding to the first i letters of the initial unencrypted message modulo 26. 6 | Now that you know how the message was encrypted, implement the algorithm to decipher it. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/JeDDnToFtitiiWDZn 9 | 10 | 11 | function cipher26(message) { 12 | sum = 0 13 | a = "a".charCodeAt(0) 14 | return message.split("").map(x => { 15 | charCode = ( (x.charCodeAt(0) - a) - sum +26 ) % 26 16 | sum = (sum + charCode) % 26 17 | return String.fromCharCode(charCode + a ) 18 | }).join("") 19 | } -------------------------------------------------------------------------------- /the_core/84-stolenLunch/stolenLunch.js: -------------------------------------------------------------------------------- 1 | /* Question : When you recently visited your little nephew, he told you a sad story: there's a bully at school who steals his lunch every day, and locks it away in his locker. 2 | He also leaves a note with a strange, coded message. Your nephew gave you one of the notes in hope that you can decipher it for him. And you did: it looks like 3 | all the digits in it are replaced with letters and vice versa. Digit 0 is replaced with 'a', 1 is replaced with 'b' and so on, with digit 9 replaced by 'j'. 4 | 5 | The note is different every day, so you decide to write a function that will decipher it for your nephew on an ongoing basis. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/M97sbwRp3tGy8uAb8 8 | 9 | 10 | function stolenLunch(note) { 11 | return note.split("").map(s => { 12 | n = s.charCodeAt(0) 13 | if(n <= "9".charCodeAt(0) && n >= "0".charCodeAt(0)) 14 | return String.fromCharCode(n - "0".charCodeAt(0) + "a".charCodeAt(0)) 15 | if(n <= "j".charCodeAt(0) && n >= "a".charCodeAt(0)) 16 | return String.fromCharCode(n - "a".charCodeAt(0) + "0".charCodeAt(0)) 17 | return s 18 | }).join("") 19 | } -------------------------------------------------------------------------------- /the_core/85-higherVersion/higherVersion.js: -------------------------------------------------------------------------------- 1 | /* Question : Given two version strings composed of several non-negative decimal fields separated by periods ("."), both strings contain equal number of numeric fields. 2 | Return true if the first version is higher than the second version and false otherwise. 3 | 4 | The syntax follows the regular semver ordering rules: 5 | 6 | 1.0.5 < 1.1.0 < 1.1.5 < 1.1.10 < 1.2.0 < 1.2.2 7 | < 1.2.10 < 1.10.2 < 2.0.0 < 10.0.0 8 | There are no leading zeros in any of the numeric fields, i.e. you do not have to handle inputs like 100.020.003 (it would instead be given as 100.20.3). */ 9 | 10 | // URL : https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/vsKRjYKv4SCjzJc8r 11 | 12 | 13 | function higherVersion(ver1, ver2) { 14 | let ver1c = ver1.split('.').map(Number); 15 | let ver2c = ver2.split('.').map(Number); 16 | for(let i in ver1c) { 17 | if (ver2c[i]ver1c[i]) 20 | return false; 21 | } 22 | return false; 23 | 24 | } -------------------------------------------------------------------------------- /the_core/86-decipher/decipher.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider the following ciphering algorithm: 2 | 3 | For each character replace it with its code. 4 | Concatenate all of the obtained numbers. 5 | Given a ciphered string, return the initial one if it is known that it consists only of lowercase letters. 6 | 7 | Note: here the character's code means its decimal ASCII code, the numerical representation of a character used by most modern programming languages. */ 8 | 9 | // URL : https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/dB9drnfWzpiWznESA 10 | 11 | 12 | function decipher(cipher) { 13 | return String.fromCharCode(...cipher.match(/1..|../g)) 14 | } 15 | -------------------------------------------------------------------------------- /the_core/88-arrayConversion/arrayConversion.js: -------------------------------------------------------------------------------- 1 | /* Question : Given an array of 2k integers (for some integer k), perform the following operations until the array contains only one element: 2 | 3 | On the 1st, 3rd, 5th, etc. iterations (1-based) replace each pair of consecutive elements with their sum; 4 | On the 2nd, 4th, 6th, etc. iterations replace each pair of consecutive elements with their product. 5 | After the algorithm has finished, there will be a single element left in the array. Return that element. 6 | 7 | Example 8 | 9 | For inputArray = [1, 2, 3, 4, 5, 6, 7, 8], the output should be 10 | solution(inputArray) = 186. 11 | 12 | We have [1, 2, 3, 4, 5, 6, 7, 8] -> [3, 7, 11, 15] -> [21, 165] -> [186], so the answer is 186. */ 13 | 14 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/dwA8RtDF86WucuoaQ 15 | 16 | 17 | function arrayConversion(inputArray) { 18 | let count = 1 19 | while (inputArray.length > 1) { 20 | let result = [] 21 | for (i = 0; i < inputArray.length; i++) { 22 | result.push((count % 2) ? inputArray[i] + inputArray[++i] : inputArray[i] * inputArray[++i]) 23 | } 24 | inputArray = result 25 | count++ 26 | } 27 | return inputArray[0] 28 | 29 | } 30 | -------------------------------------------------------------------------------- /the_core/89-arrayPreviousLess/arrayPreviousLess.js: -------------------------------------------------------------------------------- 1 | /* Question : Given array of integers, for each position i, search among the previous positions for the last (from the left) position that contains a smaller value. 2 | Store this value at position i in the answer. If no such value can be found, store -1 instead. */ 3 | 4 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/MQg7s3dKrP4caN42A 5 | 6 | 7 | function arrayPreviousLess(items) { 8 | return items.map((a, i) => { 9 | for (let j = i - 1; j >= 0; j--) { 10 | if (items[j] < a) { return items[j]; } 11 | } 12 | return -1; 13 | }); 14 | } -------------------------------------------------------------------------------- /the_core/90-pariOfShoes/pairOfShoes.js: -------------------------------------------------------------------------------- 1 | /* Question : Yesterday you found some shoes in the back of your closet. Each shoe is described by two values: 2 | 3 | type indicates if it's a left or a right shoe; 4 | size is the size of the shoe. 5 | Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of an equal size. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/picP24ieQnuqR4kxJ 8 | 9 | 10 | function pairOfShoes(shoes) { 11 | while (shoes.length > 1) { 12 | for (let i = 1; i < shoes.length; i++) { 13 | if (shoes[0][1] === shoes[i][1] && shoes[0][0] !== shoes[i][0]) { 14 | shoes.splice(i, 1); 15 | shoes.shift(); 16 | break; 17 | } 18 | if (i === shoes.length - 1) return false; 19 | } 20 | } 21 | return shoes.length < 1; 22 | } -------------------------------------------------------------------------------- /the_core/91-combs/combs.js: -------------------------------------------------------------------------------- 1 | /* Question : Miss X has only two combs in her possession, both of which are old and miss a tooth or two. She also has many purses of different length, in which she carries the combs. The only way they fit is horizontally and without overlapping. 2 | Given teeth' positions on both combs, find the minimum length of the purse she needs to take them with her. 3 | 4 | It is guaranteed that there is at least one tooth at each end of the comb. 5 | It is also guaranteed that the total length of two strings is smaller than 32. 6 | Note, that the combs can not be rotated/reversed. */ 7 | 8 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/6ceKutpnCs4LzBKgf 9 | 10 | 11 | function combs(comb1, comb2) { 12 | let f = (c1, c2) => { 13 | while ([...c2].some((x, i) => x == c1[i] && x == '*')) c2 = '.' + c2 14 | return Math.max(c1.length, c2.length) 15 | } 16 | return Math.min(f(comb1, comb2), f(comb2, comb1)) 17 | } -------------------------------------------------------------------------------- /the_core/92-stringsCrossover/stringsCrossover.js: -------------------------------------------------------------------------------- 1 | /* Question : Define crossover operation over two equal-length strings A and B as follows: 2 | 3 | the result of that operation is a string of the same length as the input strings 4 | result[i] is either A[i] or B[i], chosen at random 5 | Given array of strings inputArray and a string result, find for how many pairs of strings from inputArray the result of the crossover operation over them may be equal to result. 6 | 7 | Note that (A, B) and (B, A) are the same pair. Also note that the pair cannot include the same element of the array twice (however, if there are two equal elements in the array, they can form a pair). */ 8 | 9 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/6QDtjNr3WoL5W4Kvo 10 | 11 | 12 | function stringsCrossover(a, s) { 13 | let r = 0 14 | for (let i = 0; i < a.length; i++) 15 | n: for (let j = i + 1; j < a.length; j++) { 16 | for (let k = 0; k < s.length; k++) 17 | if (s[k] !== a[i][k] && s[k] !== a[j][k]) continue n 18 | r++ 19 | } 20 | 21 | return r 22 | } -------------------------------------------------------------------------------- /the_core/93-cyclicStrings/cyclicString.js: -------------------------------------------------------------------------------- 1 | /* Question : You're given a substring s of some cyclic string. What's the length of the smallest possible string that can be concatenated to itself many times to obtain this cyclic string? */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/tKwbrKAQhoCZFqg33 4 | 5 | 6 | function cyclicString(s) { 7 | var length = 1; 8 | while (s.slice(0, length).repeat(s.length).slice(0, s.length) != s) 9 | length++; 10 | return length; 11 | } 12 | -------------------------------------------------------------------------------- /the_core/94-beautifulTexts/beautifulTexts.js: -------------------------------------------------------------------------------- 1 | /* Question : Consider a string containing only letters and whitespaces. It is allowed to replace some (possibly, none) whitespaces with newline symbols to obtain a multiline text. 2 | Call a multiline text beautiful if and only if each of its lines (i.e. substrings delimited by a newline character) contains an equal number of characters (only letters 3 | and whitespaces should be taken into account when counting the total while newline characters shouldn't). Call the length of the line the text width. 4 | 5 | Given a string and some integers l and r (l ≤ r), check if it's possible to obtain a beautiful text from the string with a text width that's within the range [l, r]. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/PSeEALZTxd93zBHS7 8 | 9 | 10 | function beautifulTexts(inputString, l, r) { 11 | for (let i = l; i <= r; i++) { 12 | let regex = new RegExp('^(.{' + i + '}\\s)+.{' + i + '}$'); 13 | if (regex.test(inputString)) return true; 14 | } 15 | return false; 16 | } -------------------------------------------------------------------------------- /the_core/95-runnersMeetings/runnersMeetings.js: -------------------------------------------------------------------------------- 1 | /* Question : Some people run along a straight line in the same direction. They start simultaneously at pairwise distinct positions and run with constant speed (which may differ from person to person). 2 | 3 | If two or more people are at the same point at some moment we call that a meeting. The number of people gathered at the same point is called meeting cardinality. 4 | 5 | For the given starting positions and speeds of runners find the maximum meeting cardinality assuming that people run infinitely long. If there will be no meetings, return -1 instead. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/Hb9Cppx4pCY4d8J5P 8 | 9 | 10 | function runnersMeetings(startPosition, speed) { 11 | let res = 1 12 | 13 | for (let i = 0; i < startPosition.length; i++) { 14 | for (let j = i + 1; j < startPosition.length; j++) { 15 | let distDiff = startPosition[j] - startPosition[i], 16 | speedDiff = speed[i] - speed[j], 17 | cnt = 0 18 | 19 | if(speedDiff == 0 && distDiff != 0) 20 | continue 21 | 22 | for (let k = 0; k < startPosition.length; k++) { 23 | if (startPosition[k] * speedDiff + speed[k] * distDiff == startPosition[i] * speedDiff + speed[i] * distDiff) 24 | cnt++ 25 | } 26 | 27 | if (cnt == 0) 28 | continue 29 | 30 | if (cnt > res) 31 | res = cnt 32 | } 33 | } 34 | if (res < 2) 35 | return -1 36 | return res 37 | } 38 | -------------------------------------------------------------------------------- /the_core/97-fileNaming/fileNaming.js: -------------------------------------------------------------------------------- 1 | /* Question : You are given an array of strings names representing filenames. The array is sorted in order of file creation, such that names[i] represents the name of a file created before names[i+1] 2 | and after names[i-1] (assume 0-based indexing). Because all files must have unique names, files created later with the same name as a file created earlier should have an additional (k) suffix in 3 | their names, where k is the smallest positive integer (starting from 1) that does not appear in previous file names. 4 | 5 | Your task is to iterate through all elements of names (from left to right) and update all filenames based on the above. Return an array of proper filenames. */ 6 | 7 | // URL : https://app.codesignal.com/arcade/code-arcade/spring-of-integration/sqZ9qDTFHXBNrQeLC 8 | 9 | 10 | function fileNaming(names) { 11 | givenNames = new Set() 12 | 13 | return names.map(name => { 14 | newName = name 15 | i=1 16 | while(givenNames.has(newName)) { 17 | newName = name +"("+ i++ +")" 18 | } 19 | givenNames.add(newName) 20 | return newName 21 | }) 22 | } 23 | -------------------------------------------------------------------------------- /the_core/98-extractMaximumColumn/extractMaximumColumn.js: -------------------------------------------------------------------------------- 1 | /* Question : Given a rectangular matrix and an integer column, return an array containing the elements of the columnth column of the given matrix (the leftmost column is the 0th one). */ 2 | 3 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/zwXiykHLor6eKHaLY 4 | 5 | 6 | function extractMaximumColumn(matrix, column) { 7 | return matrix.map(x=> x[column]) 8 | } 9 | -------------------------------------------------------------------------------- /the_core/99-areIsomorphic/areIsomorphic.js: -------------------------------------------------------------------------------- 1 | /* Question : Two two-dimensional arrays are isomorphic if they have the same number of rows and each pair of respective rows contains the same number of elements. 2 | 3 | Given two two-dimensional arrays, check if they are isomorphic. */ 4 | 5 | // URL : https://app.codesignal.com/arcade/code-arcade/list-backwoods/xKYm98etd9JRsTcZY 6 | 7 | 8 | function areIsomorphic(array1, array2) { 9 | return array1.map(i=>i.length).toString()==array2.map(i=>i.length).toString() 10 | } 11 | --------------------------------------------------------------------------------