DEV Community

Cover image for Coding Puzzles: Week of 4/8

Coding Puzzles: Week of 4/8

Ali Spittel on April 08, 2019

I'm bringing back the coding puzzles after a few month hiatus! Every day, I post coding puzzles. These are quick coding challenges that increase i...
Collapse
 
aspittel profile image
Ali Spittel

Tuesday (7 KYU): Find the stray number

codewars.com/kata/57f609022f4d534f...

Collapse
 
laurieontech profile image
Laurie
function stray(arr) {
    return arr.reduce((a, b) => a ^ b)
}
Collapse
 
threeheadedcerb profile image
russ

What is this necromancy?

Thread Thread
 
laurieontech profile image
Laurie • Edited

Haha, bitwise xor. Since it's immutable and commutative it'll reduce down to the stray!

I should add that this only works because it’s an odd number of elements in the array. An even number of matching elements cancel each other out to result in the “stray”.

Thread Thread
 
threeheadedcerb profile image
russ

Oh my, it even works in python!

def stray(arr):
    count = {}
    for index, i in enumerate(arr):
        count[i] = count.setdefault(i, 0) + 1
        if index >= 2 and len(count.keys()) > 1:
            break
    return next(k for k, v in count.items() if v == 1)

from functools import reduce

def intstray(arr: [int]):
    return reduce(lambda x,y: x ^ y, arr)

assert(intstray([1, 1, 2]) == 2)
#nope..!
#assert(intstray([1, 1, 2, 1]) == 2)
assert(intstray([17, 17, 3, 17, 17, 17, 17]) == 3)
assert(intstray([1, 2, 2]) == 1)
assert(stray(["bob", "bob", "bob", "steve", "bob"]) == "steve")
Thread Thread
 
laurieontech profile image
Laurie

This is one of those moments when I wish gifs worked better on Dev. But yay!

Collapse
 
aspittel profile image
Ali Spittel

Wednesday (6 KYU): Implement Syntax Highlighting

codewars.com/kata/roboscript-numbe...

Collapse
 
threeheadedcerb profile image
russ • Edited
import re

def highlight(cmd):
    colour_map = [
        (r'F+', 'pink'),
        (r'L+', 'red'),
        (r'R+', 'green'),
        (r'\d+', 'orange'),
        (r'()+', None),
    ]
    highlighted = []
    while(len(cmd)):
        for regex, colour in colour_map:
            match = re.match(regex, cmd)
            if match:
                idx_start, idx_end = match.span()
                highlighted.append((cmd[idx_start:idx_end], colour))
                cmd = cmd[idx_end:]
                break
        else:
            highlighted.append((cmd[0], None))
            cmd = cmd[1:]
    return ''.join(['<span style="color: {}">{}</span>'.format(colour, string) if colour else string for string, colour in highlighted])
Collapse
 
threeheadedcerb profile image
russ

And now with added re.sub with a callable, which I had no idea was a thing! These coding things are pretty nifty for leaning new tricks I must say!

import re

def highlight(cmd):
    colour_map = [
        (r'F+', 'pink'),
        (r'L+', 'red'),
        (r'R+', 'green'),
        (r'\d+', 'orange'),
        (r'()+', None),
    ]

    def replacer(match : re.Match):
        substr = match.group()
        colour = next((colour for regex, colour in colour_map if re.match(regex, substr)), None)
        return '<span style="color: {}">{}</span>'.format(colour, substr) if colour else substr

    return re.sub(r'(\D)\1*|(\d+)', replacer, cmd)
Collapse
 
laurieontech profile image
Laurie

Oooh, I like this. I was thinking about a dictionary but didn't think about a dictionary with the regex as a key!

Collapse
 
laurieontech profile image
Laurie • Edited

Booo regex

function highlight(code) {
  return code.replace(/(\D)\1+|(\d+|\D)/g, (substr) => {
      var color;
      let testChar = substr.charAt(0); 

      if (testChar === 'F') {
          color = 'pink';
      } else if (testChar === 'L') {
          color = 'red';
      } else if (testChar === 'R') {
          color = 'green';
      } else if (!isNaN(testChar)) {
          color = 'orange';
      } else {
        return substr;
      }
      return '<span style="color: ' + color + '">' + substr + '</span>';   
  })
}
Collapse
 
laurieontech profile image
Laurie • Edited

Quick edit with a dictionary.

function highlight(code) {
  const colorDict = {'F': 'pink', 'L': 'red', 'R':'green'};

  return code.replace(/(\D)\1*|\d+/g, (substr) => {
      let testChar = substr.charAt(0); 

      if (testChar in colorDict) {
        return '<span style="color: ' + colorDict[testChar] + '">' + substr + '</span>';   
      } else if (!isNaN(testChar)) {
        return '<span style="color: orange">' + substr + '</span>';   
      } else {
        return substr;
      }
  })
}
Collapse
 
aspittel profile image
Ali Spittel

Monday (8KYU): How many stairs will Suzuki climb in 20 years?

codewars.com/kata/56fc55cd1f5a93d6...

Collapse
 
laurieontech profile image
Laurie • Edited

Javascript (ES6):

function stairs_in_20(stairs) {
       return stairs.reduce((steps, day) => steps.concat(day)).reduce((sum, count) => sum + count) * 20;
}
Collapse
 
jellebekker profile image
Jelle Bekker

Not a one liner like you guys but C#:

using System;
public class Kata
{
  public static long StairsIn20(int[][] stairs)
  {
    long sum = 0;
    foreach (var weekday in stairs)
        foreach (var steps in weekday)
          sum += steps;

    return sum * 20;
   }           
}
Collapse
 
jellebekker profile image
Jelle Bekker

Okay, I couldn't help myself:

using System;
using System.Linq;

public class Kata
{
  public static long StairsIn20(int[][] stairs)
  {
    return stairs.SelectMany(x => x).Sum() * 20;
  }
}
Collapse
 
mihassan profile image
Md Imrul Hassan
def stairs_in_20(stairs):
    return 20*sum(sum(stairs, []))
Collapse
 
aspittel profile image
Ali Spittel • Edited

My Python solution:

def stairs_in_20(stairs):
      return sum(i for sublist in stairs for i in sublist)  * 20
Collapse
 
aspittel profile image
Ali Spittel

Friday (CodeJam): Foregone Solution

codingcompetitions.withgoogle.com/...

Collapse
 
aspittel profile image
Ali Spittel
n_cases = int(input())
for i in range(1, n_cases + 1):
    check_amount = int(input())
    unfound = True
    fours = [int(i) for i in str(check_amount)]
    others = ["1" if n == 4 else "0" for n in fours]
    n = int(''.join(others))
    print("Case #{}: {} {}".format(i, n, check_amount - n))
Collapse
 
clandau profile image
Courtney

brute force for me so far.

const readline = require('readline');

function foregone() {
    let argumentsArray = [], answerArray = [];
    let linecounter = 0, tests;

    const rl = readline.createInterface({ 
        input: process.stdin,
        output: process.stdout
    });
    rl.on('line', (line) => {
        linecounter++;
        if(linecounter === 1) tests = line;
        else {
            argumentsArray.push(line);
            if(linecounter > tests) rl.close();
        }
    }).on('close', () => {
        for(let i=0; i< argumentsArray.length; i++) {
            answerArray.push(noFours(argumentsArray[i]));
        }
        for(let i=0; i<answerArray.length; i++) {
            console.log(`Case #${i+1}: ${answerArray[i][0]} ${answerArray[i][1]}`)
        }
        process.exit(0);
    });

    function noFours(num) {
        let a = num - 1, b = num - a;
        while(a.toString().indexOf('4') !== -1 || b.toString().indexOf('4') !== -1 && a >= b) {
            a--, b++;
        }
        if(a.toString().indexOf('4') === -1 && b.toString().indexOf('4') === -1) return [a, b];
        else return undefined 
    }
}
Collapse
 
choroba profile image
E. Choroba
#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

use Math::BigInt;

chomp( my $cases = <> );
for my $case (1 .. $cases) {
    chomp( my $n = <> );
    (my $i = $n) =~ tr/4/3/;
    my $j = 'Math::BigInt'->new($n) - 'Math::BigInt'->new($i);
    say "Case #$case: $i $j";
}
Collapse
 
jacobmgevans profile image
Jacob Evans
const stairsIn20 =(s) => [...s].map((ele)=> ele.reduce((ag, nx)=> ag+nx))
.reduce((ag, nx)=> ag+nx) * 20
Collapse
 
aspittel profile image
Ali Spittel

Thursday (5 KYU): Perimeter of squares in a rectangle

codewars.com/kata/559a28007caad2ac...

Collapse
 
choroba profile image
E. Choroba
#!/usr/bin/perl
use warnings;
use strict;

sub perimeters {
    my ($n) = @_;
    my @f = (1, 1);
    my $s = 0;
    for (0 .. $n) {
        $s += $f[0];
        @f = ($f[1], $f[0] + $f[1]);
    }
    return 4 * $s
}

# In a good TDD tradition, I started with these lines:
use Test::More tests => 2;
is perimeters(5), 80;
is perimeters(7), 216;
Collapse
 
clandau profile image
Courtney

TypeScript. Great practice!

export class G964 {
    public static perimeter = (n) => {
      let fibArray : number[] = [0, 1, 1];
      for(let i=3; i<=n+1; i++) {
        fibArray[i] = fibArray[i-1] + fibArray[i-2];
      }
      return fibArray.reduce((a, b) => a + b) * 4;
    }
}
Collapse
 
jacobmgevans profile image
Jacob Evans
const stairsIn20 =(s) => [...s].map((ele)=> ele.reduce((ag, nx)=> ag+nx)).reduce((ag, nx)=> ag+nx) * 20