DEV Community

Cover image for Daily Coding Puzzles - Nov 4th - Nov 9th

Daily Coding Puzzles - Nov 4th - Nov 9th

Ali Spittel on November 09, 2018

Every day on Twitter, I post coding puzzles. These are quick coding challenges that increase in difficulty across the span of the week -- with Mond...
Collapse
 
aspittel profile image
Ali Spittel

Wednesday

Array.diff (6 KYU):

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

CodeWars

Collapse
 
ben profile image
Ben Halpern

Ruby

a - b
Collapse
 
dance2die profile image
Sung M. Kim

Ah, cannot unsee this answer... πŸ˜†

Collapse
 
gartboy profile image
Garrett

Similar effort when done in APL! :)

Collapse
 
aspittel profile image
Ali Spittel

That's amazing!

Thread Thread
 
ben profile image
Ben Halpern

Collapse
 
aspittel profile image
Ali Spittel

Thursday

Scramblies (5 KYU):

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false

CodeWars

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

F#

let scramble str1 str2 =
    let letterLookup = str1 |> Seq.countBy id |> Map.ofSeq
    let requiredCounts = str2 |> Seq.countBy id
    requiredCounts |> Seq.forall (fun (letter, requiredCount) ->
        match letterLookup |> Map.tryFind letter with
        | None -> false // letter missing
        | Some count -> requiredCount <= count
    )

Edit: I had previously posted a version that had ever-so-slightly more performance but was more code. I'm also including that version below since it solves the problem differently.

let scramble str1 str2 =
    let letterPool = str1 |> Seq.sort |> List.ofSeq
    let requiredLetters = str2 |> Seq.sort |> List.ofSeq
    let rec loop requiredLetters letterPool =
        match requiredLetters, letterPool with
        | [], _ -> true // found all
        | _ :: _, [] -> false // pool ran out
        | letter :: _, next :: pool when letter > next ->
            loop requiredLetters pool // skip next in pool
        | letter :: required, next :: pool when letter = next ->
            loop required pool
        | _, _ -> false // letter not available in the pool
    loop requiredLetters letterPool

Here are the tests (console).

    [
        "rkqodlw", "world", true
        "cedewaraaossoqqyt", "codewars", true
        "katas", "steak", false
    ]
    |> List.iter (fun (str1, str2, expected) ->
        let actual = scramble str1 str2
        let e = if expected = actual then "√" else "X"
        printfn "%s %A ==> %b, %b" e (str1, str2) expected actual
    )
    // √ ("rkqodlw", "world") ==> true, true
    // √ ("cedewaraaossoqqyt", "codewars") ==> true, true
    // √ ("katas", "steak") ==> false, false
Collapse
 
aspittel profile image
Ali Spittel

Nice! yeah -- I only sometimes think about the efficiencies of these. They're contrived and we're doing them for fun. Part of me cares, part of me doesn't haha

Thread Thread
 
kspeakman profile image
Kasey Speakman • Edited

I agree. I would have posted a much more expressive version, but you beat me to it! I did find an alternative way of solving the problem that was a little more expressive and nearly the same perf. I updated my post to include it.

Collapse
 
thejessleigh profile image
jess unrein

Go

func Scramble(str1 string, str2 string) (result bool) {
    m := make(map[string]int)

    for _, item := range strings.Split(str1, "") {
        m[item] += 1
    }

    for _, item := range strings.Split(str2, "") {
        if val, ok := m[item]; !ok || val == 0 {
            return false
        } else {
            m[item] -= 1
        }
    }

    return true
}
Collapse
 
jay profile image
Jay

Rust

fn scramble(str1: &str, str2: &str) -> bool {
    if str2.len() > str1.len() {
        return false;
    }
    str2.chars().all(|c| {
        str1.chars().filter(|&ch| ch == c).count() >= str2.chars().filter(|&c2| c2 == c).count()
    })
}
Collapse
 
aspittel profile image
Ali Spittel

Tuesday

Product of Array Items (7 KYU):

Calculate the product of all elements in an array.

CodeWars

Collapse
 
kspeakman profile image
Kasey Speakman

F#

let product arr =
    arr |> Array.reduce (*)

I probably wouldn't define a separate function for this in actual code.

Collapse
 
jreina profile image
Johnny Reina

Does F# require you to name the arr parameter explicitly or can you simply do the following:

let product = Array.reduce (*)

I've been curious about F# for some time but haven't really done a deep dive.

Thread Thread
 
kspeakman profile image
Kasey Speakman

Yes, you can do that in F#. (You probably know this, but for the sake of onlookers) it is called point-free notation. It can be handy for small functions like this. But I noticed when I use it too much, my code can become hard to understand.

Especially for code examples, I rarely use it because it can confuse readers.

Collapse
 
clandau profile image
Courtney

I decided to not use reduce so that I could return early if I hit a zero.

function product(values) {
  if(!values || values.length === 0) return null;
  let prod = values[0];
  for(let i=1; i<values.length; i++) {
    if(values[i] === 0) return 0;
    prod *= values[i];
  }
  return result;
}
Collapse
 
susickypavel profile image
Pavel Susicky

Javascript

function arrayProduct(arr) {
    return arr.reduce((acc, val) => acc * val);
}
Collapse
 
aspittel profile image
Ali Spittel

Friday

The Last Word (CodeJam):

You are the next contestant on this show, and the host has just showed you the string S. What's the winning last word that you should produce?

CodeJam

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

F#

let lastWord s =
    let update (first, word) letter =
        if letter >= first then (letter, string letter + word)
        else                    (first, word + string letter)
    s |> Seq.fold update ('A', "") |> snd

Testing it (console)

    [
        "CAB", "CAB"
        "JAM", "MJA"
        "CODE", "OCDE"
        "ABAAB", "BBAAA"
        "CABCBBABC", "CCCABBBAB"
        "ABCABCABC", "CCCBAABAB"
        "ZXCASDQWE", "ZXCASDQWE"
    ]
    |> List.iter (fun (input, expected) ->
        let actual = lastWord input
        let e = if expected = actual then "√" else "X"
        printfn "%s %s ==> %s, %s" e input expected actual
    )
    // √ CAB ==> CAB, CAB
    // √ JAM ==> MJA, MJA
    // √ CODE ==> OCDE, OCDE
    // √ ABAAB ==> BBAAA, BBAAA
    // √ CABCBBABC ==> CCCABBBAB, CCCABBBAB
    // √ ABCABCABC ==> CCCBAABAB, CCCBAABAB
    // √ ZXCASDQWE ==> ZXCASDQWE, ZXCASDQWE

Collapse
 
aspittel profile image
Ali Spittel

Awesome -- this one (for me) was a lot easier than they made it sound!

Thread Thread
 
kspeakman profile image
Kasey Speakman • Edited

Same here. The hard part was understanding the problem. (It felt very much like "A train leaving SF at 50kph ..." word problems.) But after that the code wasn't so bad.

Thread Thread
 
thejessleigh profile image
jess unrein

I think the possible "gotcha" here is that they do not want a reverse alphabetically sorted string, which, if you're not careful about the requirements, could be what you try to build and have it trip you up.

Collapse
 
jay profile image
Jay

Rust

use std::io::{self, prelude::*};

fn find_last_word(s: &str) -> String {
    s.chars()
        .fold(vec![], |mut last, letter| {
            if let Some(&c) = last.last() {
                if (c as u8) > (letter as u8) {
                    last.insert(0, letter);
                } else {
                    last.push(letter);
                }
            } else {
                last.push(letter);
            }
            last
        }).iter()
        .rev()
        .into_iter()
        .collect()
}

fn main() {
    let stdin = io::stdin();

    for (i, line) in stdin.lock().lines().skip(1).enumerate() {
        if let Ok(text) = line {
            match io::stdout()
                .write(format!("Case #{}: {}\n", i + 1, find_last_word(&text)).as_bytes())
            {
                Ok(_) => (),
                Err(why) => panic!(why),
            }
        }
    }
}

usage: last_word(.exe) < small.in > small.txt

Collapse
 
aspittel profile image
Ali Spittel

Meta!

Collapse
 
thejessleigh profile image
jess unrein

Ooh. I tried to do Advent of Code in Go last year, but AoC was probably too steep a challenge for a language I didn't know at all. This is a much more manageable entrypoint. Thanks for this! πŸ€—

Collapse
 
aspittel profile image
Ali Spittel

For sure! I may try and incorporate those next month! We'll see! Go is so much fun, I should do more with it!

Collapse
 
thejessleigh profile image
jess unrein

Possibly dumb question - what does KYU stand for?

Collapse
 
aspittel profile image
Ali Spittel

That's a great question -- I'm not totally sure, but it's the ranking system CodeWars uses, so I include it -- 8 KYU are the most beginner friendly, 1 KYU takes a really long time.

Collapse
 
jay profile image
Jay

KYU is used for grading the difficulty levels, or degree of proficiency or experience.
Wiki

Collapse
 
aspittel profile image
Ali Spittel

Monday

Number Drills: Blue and red marbles (8 KYU):

You've decided to write a function, guess_blue() to help automatically calculate whether you should guess "blue" or "red". The function should take four arguments.

CodeWars

Collapse
 
thejessleigh profile image
jess unrein • Edited

Go

func Guess(bStart int, rStart int, bGone int, rGone int)(probability float32) {
    var b = bStart - bGone
    var r = rStart - rGone

    probability = float32(b) / float32(r + b)
    return
}
Collapse
 
gypsydave5 profile image
David Wickes • Edited

Common Lisp

(defun guess-blue (blue-in red-in blue-out red-out)
  (let ((blue (- blue-in blue-out))
        (red (- red-in red-out)))
    (/ blue (+ red blue)))

(guess-blue 5 5 2 3)
;; => 3/5

the fun of a language with rationals:

(guess-blue 1 2 0 0)
;; => 1/3
Collapse
 
jay profile image
Jay

Rust

fn guess_blue(blue_start: u32, red_start: u32, blue_pulled: u32, red_pulled: u32) -> f32 {
    let blue = (blue_start - blue_pulled) as f32;
    let red = (red_start - red_pulled) as f32;

    blue / (blue + red)
}
Collapse
 
aspittel profile image
Ali Spittel

Python!

def guess_blue(blue_start, red_start, blue_pulled, red_pulled):
    blue = blue_start - blue_pulled
    red = red_start - red_pulled
    return blue / (red + blue)
Collapse
 
clandau profile image
Courtney
function guessBlue(blueStart, redStart, bluePulled, redPulled) {
  let currentBlue = blueStart - bluePulled;
  let currentRed = redStart - redPulled;
  return currentBlue / (currentBlue + currentRed);
}

Collapse
 
jakedohm_34 profile image
Jake Dohm

JS Solution: Takes two arrays, returns a single array with all of the items from array A, which do not exist in array B.

function diff(a, b){
  return a.filter(item => !b.includes(item))
}
Collapse
 
jakedohm_34 profile image
Jake Dohm

Just realized @thesoreon posted almost the same solution already. Oh well, I guess great minds think alike 😜

Collapse
 
susickypavel profile image
Pavel Susicky

That's nice! When i made this solution i was curious and searched for another approches and found the exact same solution on stack overflow πŸ˜†

Collapse
 
kunvar13 profile image
Kalpesh • Edited

For thos who are looking for solution in C#

using System;
using System.Collections.Generic;

public class Kata
{
public static int[] ArrayDiff(int[] a, int[] b) {

List<int> result = new List<int>(); //Creating empty list to push the elements later

for (int i = 0; i < a.Length; i++) 
{
  int num = 0; //settung num to 0 for each iteration of i

  for(int j = 0; j < b.Length; j++) 
    {

      if(a[i] == b[j]) { num++;}

    }  
  if(num == 0) { 
    result.Add(a[i]);
    }

 }

return result.ToArray(); //ToArray to convert the List in Array.
Enter fullscreen mode Exit fullscreen mode

}
}