DEV Community

Discussion on: Daily Coding Puzzles - Nov 11th - Nov 16th

Collapse
 
aspittel profile image
Ali Spittel • Edited

Friday - Cruise Control (Code Jam):

Annie is a bus driver with a high-stress job. She tried to unwind by going on a Caribbean cruise, but that also turned out to be stressful, so she has recently taken up horseback riding...

codejam.withgoogle.com/codejam/con...

Collapse
 
jay profile image
Jay

Rust Solution:

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

fn cruise_control(distance: f64, horses: &[(f64, f64)]) -> f64 {
    let time = horses
        .iter()
        .map(|&(d, s)| (distance - d) / s)
        .fold(f64::NAN, f64::max);
    distance / time
}

fn parse_line(s: &str) -> (f64, f64) {
    let vec: Vec<f64> = s
        .to_string()
        .split_whitespace()
        .map(|c| c.to_string().parse().unwrap())
        .collect();
    (vec[0], vec[1])
}

fn main() -> Result<(), io::Error> {
    let mut buffer = String::new();
    io::stdin().read_to_string(&mut buffer)?;
    let mut buf_lines = buffer.lines();
    let cases: u8 = buf_lines.next().unwrap().parse().unwrap();
    for case in 0..cases {
        let (dist, number) = parse_line(buf_lines.next().unwrap());
        let mut horses_info = buf_lines.clone().take(number as usize);
        let mut horses = vec![];
        for horse in horses_info {
            buf_lines.next();
            horses.push(parse_line(horse));
        }
        match io::stdout()
            .write(format!("Case #{}: {}\n", case + 1, cruise_control(dist, &horses)).as_bytes())
        {
            Ok(_) => (),
            Err(why) => panic!(why),
        }
    }
    Ok(())
}
Collapse
 
choroba profile image
E. Choroba

The Perl solution I submitted back in 2017:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my $test_count = <>;
for my $test_case (1 .. $test_count) {
    my ($destination, $horse_count) = split ' ', <>;
    my $other_max = 0;
    for my $horse (1 .. $horse_count) {
        my ($position, $max_speed) = split ' ', <>;
        my $speed = ($destination - $position) / $max_speed;
        $other_max = $speed if $other_max < $speed;
    }
    say "Case #$test_case: ", $destination / $other_max;
}
Collapse
 
aspittel profile image
Ali Spittel
def clean_input_file(file_name):
    inp = open(file_name)
    inp = inp.read()
    inp = inp.split('\n')
    cases = int(inp[0])
    inp.pop(0)
    inp.pop()
    return inp, cases


def cruise_control(distance, horse):
    return float(distance - horse[0]) / horse[1]


def get_speeds(distance, horses):
    speeds = []
    for horse in horses:
        speeds.append(cruise_control(distance, horse))
    return distance / max(speeds)

input_file, cases = clean_input_file('test.in')
write_file = open('solution.txt', 'w+')

row = 0

for case in range(cases):
    case_info = input_file[row].split(' ')
    speed = int(case_info[0])
    n_horses = int(case_info[1])

    horses = []
    for _ in range(n_horses):
        row += 1
        horse = input_file[row].split(' ')
        horses.append((int(horse[0]), int(horse[1])))
    write_file.write("Case #{}: {}\n".format(case + 1, "{0:.2f}".format(get_speeds(speed, horses))))
    row += 1
Collapse
 
clandau profile image
Courtney

I had to resort to following along with a youtube video of the challenge, but I understand it now, so...learning?

But seriously, tons of new things learned this week, like handling stdin and stdout data, reading test data from a file and writing answers to a file. Glad to have these challenges to follow!

function processData(input) {
    let resultStr = '';
    const inputArray = input.split('\n');
    const cases = parseInt(inputArray.shift());
    for(let i=0; i<cases; i++) {
        resultStr += `Case # ${i+1}: `;
        let me = inputArray.shift().split(' ');
        let destination = parseFloat(me[0]);
        let numHorses = parseInt(me[1]);
        let horses = [];
        for(let j=0; j<numHorses; j++) {
            let horse = inputArray.shift().split(' ');
            horses.push({ velocity: parseFloat(horse[1]), location: parseFloat(horse[0])});
        }
        let sortedHorses = horses.sort((a, b) => b.location-a.location);
        resultStr += `${cruiseControl(destination, sortedHorses)}\n`;
    }
    return process.stdout.write(resultStr);
}

function cruiseControl(dest, horseArry) {
    let B = horseArry[0].location, vB = horseArry[0].velocity;
    for (let i=1; i<horseArry.length; i++) {
        let A = horseArry[i].location, vA = horseArry[i].velocity;
        if(vB === vA) B = A, vB = vA;
        else {
            let x = (vB * A - vA * B) / (vB - vA);
            if(x > dest || x < A) {
                B = A, vB = vA;
            } 
        }
    }
    let tB = (dest - B) / vB;
    return dest / tB;
}