DEV Community

Discussion on: Daily Coding Puzzles - Nov 4th - Nov 9th

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
 
aspittel profile image
Ali Spittel

Python!

def get_last_word(word):
    last_word = word[0]
    for letter in word[1:]:
        if letter >= last_word[0]:
            last_word = letter + last_word
        else:
            last_word = last_word + letter
    return last_word

out_file = open('output.txt', 'w')
case_number = 0

for word in open('A-small-practice (3).in', 'r'):
    if case_number != 0:
        out_file.write("Case #{}: ".format(case_number) + get_last_word(word))
    case_number += 1
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
 
clandau profile image
Courtney

TypeScript

function processLastwordData(input :string) : void {
    const inputArray = input.split('\n');
    let resultStr = "";
    const cases = parseInt(inputArray[0]);
    for(let i=1; i <= cases; i++) {
        resultStr += `Case #${i}: ${lastWord(inputArray[i])}\n`
    }
    process.stdout.write(resultStr);
}

function lastWord(str : string) : string {
    let outStr = str[0];
    for(let i=1; i<str.length; i++) {
        if(str.charCodeAt(i) >= outStr.charCodeAt(0)) outStr = str[i] + outStr;
        else outStr = outStr + str[i];
    }
    return outStr;
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
    processLastwordData(_input);
});

Collapse
 
thejessleigh profile image
jess unrein

Go

func Last(w string) (result []string) {
    l := strings.Split(w, "")
    result = []string{l[0]}

    for _, item := range l[1:] {
        if val := result[0]; item > val {
            result = append([]string{item}, strings.Join(result, ""))
        } else {
            result = append(result, item)
        }
    }
    return
}
Collapse
 
gypsydave5 profile image
David Wickes

Common Lisp

(defun last-word (word)
  (let ((cs (coerce word 'list)))
    (coerce (reduce #'(lambda (word c)
                        (if (char> (first word) c)
                            (append word (list c))
                            (cons c word)))
                    (rest cs)
                    :initial-value (list (first cs)))
            'string)))

Quick little test...

(mapcar #'last-word (list "CAB"
                          "JAM"
                          "CODE"
                          "ABAAB"
                          "CABCBBABC"
                          "ABCABCABC"
                          "ZXCASDQWE"))
;; => ("CAB" "MJA" "OCDE" "BBAAA" "CCCABBBAB" "CCCBAABAB" "ZXCASDQWE")