re: Daily Coding Puzzles - Nov 4th - Nov 9th VIEW POST

FULL DISCUSSION
 

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

 

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
}
 

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
 

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

 

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

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.

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.

 

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")
 

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

 

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);
});

code of conduct - report abuse