Quotes help make search much faster. Example: "Practice Makes Perfect"

Thursday, December 22, 2016

Codefights def simpleSort(arr)

#sample solution
def simpleSort(arr):

    n = len(arr)

    for i in range(n):
        j = 0
        stop = n - i
        while j < stop - 1:
            if arr[j] > arr[j + 1]:
                temp = arr[j+1]
                arr[j+1] = arr[j]
                arr[j] = temp
            j += 1
    return arr

Codefights def modulus(n)

#sample solution
def modulus(n):
    if isinstance( n, int ) :
        return n % 2
    else:
        return -1

Saturday, December 17, 2016

Codefights isMAC48Address(inputString)

//sample solution
function isMAC48Address(inputString) {
    if(inputString.length!=17){
    return false;
    }
var regex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/;
    //document.writeln(regex.test(inputString));
    return regex.test(inputString);
}

Codefights htmlEndTagByStartTag(startTag)

//sample solution
function htmlEndTagByStartTag(startTag) {
var indexWhiteSpace=startTag.indexOf(" ");
    var indexGreaterThanSign=startTag.indexOf(">");
    if(indexWhiteSpace>-1){
    //document.writeln(indexWhiteSpace,"<br/>");
        //document.writeln(startTag.substr(1,indexWhiteSpace),"<br/>")
    return "</" + startTag.substr(1,indexWhiteSpace-1) + ">";
    } else {
        //document.writeln(indexGreaterThanSign,"<br/>");
    return "</" + startTag.substr(1,indexGreaterThanSign-1) + ">";
    }
}

Codefights isCaseInsensitivePalindrome(inputString)

//sample solution
function isCaseInsensitivePalindrome(inputString) {
    var temp = inputString.toLowerCase();
    var tempReversed = temp.split("").reverse().join("");
    if(temp.localeCompare(tempReversed)==0){
        return true;
    } else {
        return false;
    }
}

Codefights isTandemRepeat(inputString)

//sample solution
function isTandemRepeat(inputString) {
    var temp=inputString.length;
    if(temp%2!=0){
        return false;
    } else {
        var midIndex = temp/2;
        var firstHalf = inputString.slice(0,midIndex);
        var secondHalf = inputString.slice(midIndex,temp);
        if(firstHalf.localeCompare(secondHalf)==0){
            return true;
        } else {
            return false;
        }
    }
}

Codefights properNounCorrection(noun)

//sample solution
function properNounCorrection(noun) {
    var firstLetter = noun.toUpperCase().slice(0,1);
    document.writeln(firstLetter,"<br/>");
    var restOfTheWord = noun.toLowerCase().slice(1,noun.length);
    document.writeln(restOfTheWord,"<br/>");
    return firstLetter+restOfTheWord;
}

Codefights encloseInBrackets(inputString)

//sample solution
function encloseInBrackets(inputString) {
    return "("+inputString+")";
}

Codefights isSumOfConsecutive2(n)

//sample solution

function isSumOfConsecutive2(n) {
    var waysToRepresent = 0;
    for(i=2;i<n;i++){
    var testValue = Math.floor(n/i)-2;
        if(testValue<1){ continue; };
        var total = sumArray(consecutiveArray(testValue,i));
        if(total==n){
        waysToRepresent++;
        } else if(total>n){
        break;
        }
    }
    for(i=2;i<n;i++){
    var testValue = Math.floor(n/i)-1;
        if(testValue<1){ continue; };
        var total = sumArray(consecutiveArray(testValue,i));
        if(total==n){
        waysToRepresent++;
        } else if(total>n){
        break;
        }
    }
    for(i=2;i<n;i++){
    var testValue = Math.floor(n/i);
        if(testValue<1){ continue; };
        var total = sumArray(consecutiveArray(testValue,i));
        if(total==n){
        waysToRepresent++;
        } else if(total>n){
        break;
        }
    }
   
    return waysToRepresent;
}

function consecutiveArray(start,size){
var someArray=[];
    for(i=0;i<size;i++){
    someArray.push(start+i);
    }
    //document.writeln(someArray," total = ");
    return someArray;
}


function sumArray(someArray){
var total=0;
for(i=0; i<someArray.length; i++){
    total=total+someArray[i];
    }
    //document.writeln(total,"<br/>");
    return total;
}

Friday, December 16, 2016

Codefights candles(candlesNumber, makeNew)

//sample solution
function candles(candlesNumber, makeNew) {
    var newCandles=candlesNumber;
    var newlyBurnedCandles=0;
    var leftoverCandles=0;
    var totalBurnedCandles=0;
    while(newCandles>0){
        //burn
        newlyBurnedCandles = newCandles;
        totalBurnedCandles = totalBurnedCandles + newlyBurnedCandles;
        leftoverCandles = leftoverCandles + newlyBurnedCandles;
        //create
        var temp = Math.floor(leftoverCandles/makeNew);
        newCandles = temp;
        leftoverCandles = leftoverCandles % makeNew;
    }
    return totalBurnedCandles;
}

Codefights rounders(value)

//sample solution
function rounders(value) {
var valueArrayed = value.toString().split("").reverse();
    //document.writeln("valueArrayed: ", valueArrayed, "<br/>");
    //document.writeln("valueArrayed length: ", valueArrayed.length, "<br/>");
    for(i=0;i<valueArrayed.length;i++){
    var temp=valueArrayed[i];
        if(temp>=5 && i!=valueArrayed.length-1){
        valueArrayed[i]=0;
            valueArrayed[i+1]++;
        } else if(i!=valueArrayed.length-1){
        valueArrayed[i]=0;
        }
    }
    //document.writeln("valueArrayed: ", valueArrayed, "<br/>");
    return parseInt(valueArrayed.reverse().join(""));
}

Codefights increaseNumberRoundness(n)

//sample solution
function increaseNumberRoundness(n) {
    var nArrayed = n.toString().split("").reverse();
    //document.writeln("nArrayed: ", nArrayed, "<br/>");
    //document.writeln("nArrayed length: ", nArrayed.length, "<br/>");
    var nonZeroPassed=false;
    var returnValue = false;
    for(i=0;i<nArrayed.length;i++){
    var temp = nArrayed[i];
        //document.writeln("temp: ", temp, "<br/>");
        if(parseInt(temp)!=0){
        nonZeroPassed=true;
        }
        if(parseInt(temp)==0 && nonZeroPassed){
        returnValue = true;
        }
    }
    return returnValue;
}

Codefights appleBoxes(k)

//sample solution
function appleBoxes(k) {
    var yellowAppleSum = 0;
    var redAppleSum = 0;
    for(i=1;i<=k;i++){
        if(i%2==0){ //even
            redAppleSum = redAppleSum + (i*i);
        } else { //odd
            if(i>1){
                yellowAppleSum = yellowAppleSum + (i*i);
            } else {
                yellowAppleSum = yellowAppleSum + 1;
            }
        }
    }
    return (redAppleSum - yellowAppleSum);
}

Codefights additionWithoutCarrying(param1, param2)

//sample solution
function additionWithoutCarrying(param1, param2) {
    var param1Array = param1.toString().split("").reverse();
    //document.writeln("param1Array: ", param1Array, "<br/>");
    var param2Array = param2.toString().split("").reverse();
    //document.writeln("param2Array: ", param2Array, "<br/>");
    var arrayToModify = [];
    var otherArray = [];
    if(param1Array.length>=param2Array.length){
    arrayToModify=param1Array;
        otherArray=param2Array;
    } else {
    arrayToModify=param2Array;
        otherArray=param1Array;
    }
    //document.writeln("arrayToModify: ", arrayToModify, "<br/>");
    //document.writeln("otherArray: ", otherArray, "<br/>");
    for(i=0;i<arrayToModify.length;i++){
    if(otherArray[i]){
    var temp=columnSum(parseInt(arrayToModify[i]),parseInt(otherArray[i]));
            //document.writeln("arrayToModify[i] ", arrayToModify[i], "<br/>");
            //document.writeln("otherArray[i] ", otherArray[i], "<br/>");
            //document.writeln("columnSum ", temp, "<br/>");
            arrayToModify[i]=temp;
        }
    }
    //document.writeln("arrayToModify: ", arrayToModify, "<br/>");
    //document.writeln(arrayToModify.reverse().join(""),"<br/>");
    return parseInt(arrayToModify.reverse().join(""));
}

function columnSum(a,b){
if(a+b>=10){
    return (a+b)%10;
    } else {
    return (a+b);
    }
}

Thursday, December 15, 2016

Codefights lineUp(commands);

//sample solution
function lineUp(commands) {
var temp=commands.split("");
    temp.reverse();
    var sum=0;
    var count=0;
    for(i=0;i<commands.length;i++){
    var letter = temp.pop();
    //document.writeln(letter,"<br/>");
        if(letter=='L'){
        sum=sum-1;
        } else if(letter=='R'){
        sum=sum+1;
        } else if(letter=='A'){
        sum=sum+2;
        }
        //document.writeln(sum,"<br/>");
        if(sum%2==0){
        count++;
        }
    }
    return count;
}

Codefights magicalWell(a, b, n)

//sample solution
function magicalWell(a, b, n) {
    var moneyMade=0;
    for(i=0;i<n;i++){
        moneyMade = moneyMade + (a * b);
        a++;
        b++;
    }
    return moneyMade;
}

Codefights countSumOfTwoRepresentations2(n,l,r)

//sample solution
function countSumOfTwoRepresentations2(n, l, r) {
    var count=0;
    for(i=1;i<n;i++){
    var diff = n - i;
        if(i>=l && diff<=r && i<=diff){
            count++;
        }
    }
    return count;
}

Codefights leastFactorial(n)

//sample solution
function leastFactorial(n) {
    var temp = 1;
    for(i=2;i<=n;i++){
        temp = i * temp;
        if(temp>=n){
            break;
        }
    }
    return temp;
}

Codefights makeArrayConsecutive2(sequence)

//sample solution
function makeArrayConsecutive2(sequence) {
    sequence.sort(function(a,b){return a - b}) //for correct number sorting
    //document.writeln("sorted: ", sequence, "<br/>");
    var lowestElement = sequence[0];
    var highestElement = sequence[sequence.length-1];
    var properSequence = [];
    if(highestElement - lowestElement >= 0){
    for(i=lowestElement; i<=highestElement; i++){
    properSequence.push(i);
    }
    } else {
    for(i=lowestElement; i>=highestElement; i--){
    properSequence.push(i);
    }
    }
    //document.writeln("proper: ", properSequence, "<br/>");
    var numberOfHoles = properSequence.length - sequence.length;
    return numberOfHoles;
}

Codefights replaceMiddle(arr)

//sample solution
function replaceMiddle(arr) {
    if(arr.length%2 === 0){
        var middleElementUpperIndex = Math.floor(arr.length/2);
        var middleElementLowerIndex = middleElementUpperIndex - 1;
        var middleElementLower = arr[middleElementLowerIndex];
        var middleElementUpper = arr[middleElementUpperIndex];
        var middleElementSum = middleElementLower + middleElementUpper;
        arr.splice(middleElementLowerIndex,2,middleElementSum);
    }
    return arr;
}

Codefights isSmooth(arr)

//sample solution
function isSmooth(arr) {
    //if array is odd
    //document.writeln(arr.length,"<br/>");
    var firstElement = arr[0];
    var lastElement = arr[arr.length-1];
    if(arr.length%2 === 0){
    //document.writeln("EVEN","<br/>");
        var middleElementUpperIndex = Math.floor(arr.length/2);
        var middleElementLowerIndex = middleElementUpperIndex - 1;
        var middleElementLower = arr[middleElementLowerIndex];
        var middleElementUpper = arr[middleElementUpperIndex];
        var middleElementSum = middleElementLower + middleElementUpper;
        if(firstElement == lastElement && lastElement == middleElementSum){
        return true;
        } else {
        return false;
        }
    } else {
    //document.writeln("ODD","<br/>");
       
        var middleElementIndex = Math.floor(arr.length/2);
        //document.writeln("middle element index is ", middleElementIndex, "<br/>");
        var middleElement = arr[middleElementIndex];
        //document.writeln("middle element is ", middleElement, "<br/>");
        if(firstElement == lastElement && lastElement == middleElement){
        return true;
        } else {
        return false;
        }
    }
   
}

Codefights removeArrayPart(inputArray, l, r)

//sample solution
function removeArrayPart(inputArray, l, r) {
    var testArray = inputArray.slice();
    var testArray2 = inputArray.slice();

    testArray.splice(l); //note that is at L
    return testArray.concat(testArray2.splice(r+1)); //note that is at r + ONE
}

Codefights concatenateArrays(a, b)

//sample solution
function concatenateArrays(a, b) {
    return a.concat(b);
}

Codefights firstReverseTry(arr)

//sample solution
function firstReverseTry(arr) {
    if(arr.length>0){
        var firstElement = arr[0];
        var lastElement = arr[arr.length-1];
        arr[0] = lastElement;
        arr[arr.length-1] = firstElement;
    }  
    return arr;
}

Codefights arrayReplace(inputArray, elemToReplace, substitutionElem)

//sample solution
function arrayReplace(inputArray, elemToReplace, substitutionElem) {
    for(i=0;i<inputArray.length;i++){
        var index = inputArray.indexOf(elemToReplace);
        if (index !== -1) {
            inputArray[index] = substitutionElem;
        }
    }
    return inputArray;
}

Codefights createArray(size)

//sample solution
function createArray(size) {
    var someArray = [];
    for(i=0; i<size; i++){
        someArray.push(1);
    }
    return someArray;
}

Wednesday, December 14, 2016

Codefights newRoadSystem

//sample solution
function newRoadSystem(roadRegister) {
    var outCount=[];
    var inCount=[];
    for(i=0;i<roadRegister.length;i++){
        outCount.push(0);
        inCount.push(0);
    }  
   
    for(i=0;i<roadRegister.length;i++){
        for(j=0;j<roadRegister[i].length;j++){
            //if i=j, you are looking at the city going to itself, so skip
            if(i==j){
                continue;
            } else if(roadRegister[i][j]==true){
                //i is the source city & j is the destination city
                outCount[i]++;
                inCount[j]++;
            }  
        }
    }
    //if by the end of the process, outCount and inCount for each city are equal, ok
    var returnValue=true;
    for(i=0;i<roadRegister.length;i++){
        if(outCount[i]!=inCount[i]){
            returnValue=false;
        }
    }
    return returnValue;
}

Saturday, December 10, 2016

Codefights swapAdjacentBits

//sample solution
//2863311530 is the decimal equivalent of 10101010101010101010101010101010
//1431655765 is the decimal equivalent of 01010101010101010101010101010101

function swapAdjacentBits(n) {
  return ((n & 2863311530) >> 1) | ((n & 1431655765) << 1);
}

Codefights mirrorBits

//sample solution

function reverseBits(a) {
    return a.split("").reverse().join("");
}

function changeToBinary(a){
    return (a >>> 0).toString(2);
}

function changeToDecimal(a){
    return parseInt(a,2);
}

function mirrorBits(a) {
    return changeToDecimal(reverseBits(changeToBinary(a)));
}

Codefights rangeBitCount

//sample solution

function onesCount(x)
{
    var count=0;
    while(x){
    count++;
        x = x & (x - 1);
    }  
    return count;
}

function rangeBitCount(a, b) {
    var sumOfOnesCount = 0;
    for(i=a; i<=b; i++){
        sumOfOnesCount = sumOfOnesCount + onesCount(i);
    }
    return sumOfOnesCount;
}

Codefights arrayPacking

//sample solution
//pad function courtesy of stack overflow
function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

function arrayPacking(a) {
    var someString=""
    for(i=0; i<a.length; i++){
        someString = pad((a[i] >>> 0).toString(2),8) + someString;
    }
    return parseInt(someString,2);
}

Codefights killKthBit

//sample solution
function killKthBit(n, k) {
  return (n & ~(1 << k-1)) >>> 0;
}

Codefights metroCard

// sample solution

function metroCard(lastNumberOfDays) {
    // daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if(lastNumberOfDays == 30){
        return [31];
    } else if (lastNumberOfDays == 31){
        return [28, 30, 31];
    } else {
        return [31];
    }
}

Codefights willYou

//sample solution

function willYou(young, beautiful, loved) {
    if(young == true && beautiful == true && loved == false){
        return true;
    } else if (loved == true && (young == false || beautiful == false)){
        return true;
    } else {
        return false;
    }
}

Codefights tennisSet

//sample solution

function tennisSet(score1, score2) {
    if(score1 > 7 || score2 > 7){
        return false;
    } else if(score1 == 7 && score2 == 7){
        return false;
    }else if(score1 == 7 || score2 == 7){
        if(score1==7 && score2 < 5){
            return false;
        } else if(score2==7 && score1 < 5){
            return false;
        } else {  
            return true;
        }  
    } else if(score1 < 7 || score2 <7){
        if(score1 == 5 && score2 == 5){
            return false;
        } else if(score1 == 6 || score2 == 6){
            if(score1 == 5 || score2 == 5){
                return false;
            } else {
                return true;
            }  
        } else {
            return false;
        }
    }
}

Friday, December 9, 2016

Codefights arithmeticExpression

//sample solution
function arithmeticExpression(A, B, C) {
    if(A+B==C){
        return true;
    } else if(A-B==C){
        return true;
    } else if(A*B==C){
        return true;
    } else if(A/B==C){
        return true;
    } else {
        return false;
    }
}

Codefights isInfiniteProcess

//sample solution
function isInfiniteProcess(a, b) {
    if(a < b){
        if((b-a) % 2 == 0){
            return false;
        } else {
            return true;
        }  
    } else if(a == b){
        return false;
    } else if(a > b){
        return true;
    }
}

Codefights extraNumber

//sample solution
function extraNumber(a, b, c) {
    if(a == b){
        return c;
    } else if (b == c){
        return a;
    } else {
        return b;
    }
}

Codefights knapsackLight

//sample solution
function knapsackLight(value1, weight1, value2, weight2, maxW) {
    // maxW >= weight1 + weight2
    if((weight1+weight2)>maxW && (maxW >= weight1 || maxW >= weight2)){
        if(weight1 > maxW){
            return value2;
        } else if(weight2 > maxW){
            return value1;
        } else if(value1 > value2){
            return value1;
        } else if(value2 > value1) {
            return value2;
        } else {
            // the values are equal, bring heavier weight?
            if(weight1 > weight2){
                return value1;
            } else if(weight2 > weight1){
                return value2;
            } else {
                //weights are equal
                return value1;
            }
        }
    } else if(maxW < weight1 || maxW < weight2){
        return 0;
    }
    else {
        return (value1 + value2);
    }
}

Monday, July 18, 2016

SQL: Table Transformation Lesson 20 Sample Solution

Instructions:
Find the percentage of high elevation airports (elevation >= 2000) by state from the airports table.

In the query, alias the percentage column as percentage_high_elevation_airports.

Sample Solution:
SELECT state, 100.0 * sum(CASE WHEN elevation >= 2000 THEN 1 ELSE 0 END) / count(*)  as percentage_high_elevation_airports FROM airports GROUP BY state;

SQL: Table Transformation Lesson 19 Sample Solution

Instructions:
Find the percentage of flights from Delta by origin (carrier = 'DL')

In the query, alias the column as
percentage_flight_distance_from_delta

Sample Solution:
SELECT origin,
    100.0*(sum(CASE WHEN carrier = 'DL' THEN distance ELSE 0 END)/sum(distance)) as percentage_flight_distance_from_delta FROM flights
GROUP BY origin;

SQL: Table Transformation Lesson 18 Sample Solution

Instructions:
Find both the total flight distance as and flight distance by origin for Delta (carrier = 'DL').

Alias the flight distance as total_flight_distance and the and flight distance by origin as total_delta_flight_distance.

Sample Solution:
SELECT origin, sum(distance) as total_flight_distance, sum(CASE WHEN carrier = 'DL' THEN distance ELSE 0 END) as total_delta_flight_distance
FROM flights
GROUP BY origin;

SQL: Table Transformation Lesson 17 Sample Solution

Instructions:
Write a query to count the number of low elevation airports by state where low elevation is defined as less than 1000 ft.

Be sure to alias the counted airports as count_low_elevation_airports.

Sample Solution:
SELECT state,
    COUNT(
      CASE
      WHEN elevation < 1000 THEN 1
        ELSE NULL
      END) as count_low_elevation_aiports
FROM airports
GROUP BY state;

SQL: Table Transformation Lesson 16 Sample Solution

Instructions:
Modify the case statement's such that when the elevation is less than 250, the elevation_tier column returns 'Low', when between 250 and 1749 it returns 'Medium', and when greater than or equal to 1750 it returns 'High'.

Be sure to alias the conditional statement as elevation_tier, in your query.

Sample Solution:
SELECT
    CASE
        WHEN elevation < 250 THEN 'Low'
        WHEN elevation BETWEEN 250 AND 1749 THEN 'Medium'
        WHEN elevation >= 1750 THEN 'High'
        ELSE 'Unknown'
    END AS elevation_tier
    , COUNT(*)
FROM airports
GROUP BY 1;

SQL: Table Transformation Lesson 15 Sample Solution

Instructions:
Count the number of rows from the flights table, where arr_time is not null and the destination is ATL.

Sample Solution:
SELECT COUNT(*) FROM flights WHERE arr_time IS NOT NULL AND destination = 'ATL';

SQL: Table Transformation Lesson 14 Sample Solution

Instructions:
Count the number of rows in the flights table, representing the total number of flights contained in the table.

Sample Solution:
SELECT COUNT(*) FROM flights;

SQL: Table Transformation Lesson 12 Sample Solution

Instructions:
Select the items in the category column that are in the legacy_products table and not in the new_products table.

Sample Solution:
SELECT category FROM legacy_products
EXCEPT
SELECT category FROM new_products;

SQL: Table Transformation Lesson 11 Sample Solution

Instructions:
Select the items in the category column that are both in the newly acquired new_products table and the legacy_products table.

Sample Solution:
SELECT category FROM new_products
INTERSECT
SELECT category FROM legacy_products;

SQL: Table Transformation Lesson 9 Sample Solution

Instructions:
Select a complete list of brand names from the legacy_products and new_products tables.

Sample Solution:
SELECT brand FROM legacy_products
UNION
SELECT brand FROM new_products;

SQL: Table Transformation Lesson 8 Sample Solution

Instructions:
Select ten rows from the new_products table.

Sample Solution:
SELECT * FROM new_products LIMIT 10;

SQL: Table Transformation Lesson 6 Sample Solution

Instructions:
Write a query to view flights by origin, flight id, and sequence number. Alias the sequence number column as flight_sequence_number.

Sample Solution:
SELECT origin, id,
    (SELECT COUNT(*)
FROM flights f
WHERE f.id < flights.id
AND f.origin=flights.origin) + 1
 AS flight_sequence_number
FROM flights;

SQL: Table Transformation Lesson 5 Sample Solution

Instruction:
Find the id of the flights whose distance is below average for their carrier.

Sample Solution:
SELECT id
FROM flights AS f
WHERE distance < (
 SELECT AVG(distance)
 FROM flights
 WHERE carrier = f.carrier);

SQL: Table Transformation Lesson 4 Sample Solution

Instruction:
Find the average total distance flown by day of week and month.

Sample Solution:
SELECT a.dep_month,
       a.dep_day_of_week,
       AVG(a.flight_distance) AS average_distance
  FROM (
        SELECT dep_month,
              dep_day_of_week,
               dep_date,
               sum(distance) AS flight_distance
          FROM flights
         GROUP BY 1,2,3
       ) a
 GROUP BY 1,2
 ORDER BY 1,2;

Sunday, July 17, 2016

SQL: Table Transformation Lesson 3 Sample Solution

Instruction:
Find flight information about flights where the Federal Aviation Administration region (faa_region) is the Southern region (ASO).

Sample Solution:
SELECT * FROM flights WHERE origin in
(SELECT code FROM airports WHERE faa_region = 'ASO');

SQL: Table Transformation Lesson 2 Sample Solution

Instruction:
Find flight information about flights where the origin elevation is less than 2000 feet.

Sample Solution:
SELECT * FROM flights WHERE origin in
(SELECT code FROM airports WHERE elevation < 2000);

SQL: Table Transformation Lesson 1 Sample Solution

Instruction:
Select ten rows from the flights table.

Sample Solution:
SELECT * FROM flights LIMIT 10;

This is an example of scrolling text using Javascript.

Popular Posts