Codesignal Simple Example
1. Add
Write a function that returns the sum of two numbers.
Example :
- For
param1 = 1
andparam2 = 2
, the output should beadd(param1, param2) = 3
.
Solution :
function add(param, ...otherParams) {
return param + (otherParams.length ? add(...otherParams) : 0);
}
2. CenturyFromYear
Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
Example :
- For
year = 1905
, the output should becenturyFromYear(year) = 20;
- For
year = 1700
, the output should becenturyFromYear(year) = 17
.
Solution :
function centuryFromYear(year) {
return Math.floor((year-1)/100) + 1;
}
3. CheckPalindrome
Given the string, check if it is a palindrome. (A palindrome is a string that reads the same left-to-right and right-to-left.)
Example :
- For
inputString = "aabaa"
, the output should becheckPalindrome(inputString) = true;
- For
inputString = "abac"
, the output should becheckPalindrome(inputString) = false;
- For
inputString = "a"
, the output should becheckPalindrome(inputString) = true.
Solution :
function checkPalindrome(inputString) {
return inputString == inputString.split('').reverse().join('');
}
4. AdjacentElementsProduct
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
Example :
- For
inputArray = [3, 6, -2, -5, 7, 3]
, the output should beadjacentElementsProduct(inputArray) = 21
.
7
and 3
produce the largest product.
Solution :
function adjacentElementsProduct(inputArray) {
var cb = Number.NEGATIVE_INFINITY;
for(var i=0;i<inputArray.length-1;i++){
if(inputArray[i]*inputArray[i+1] > cb){
cb = inputArray[i]*inputArray[i+1];
}
}
return cb;
}
5. ShapeArea
Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n.
A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side.
Example :
- For
n = 2
, the output should beshapeArea(n) = 5;
- For
n = 3
, the output should beshapeArea(n) = 13
.
Solution :
function shapeArea(n) {
return 2*Math.pow(n,2) - 2*n +1;
}