Primeagen's Polyglot Class 1
- Published
- Tags
- #notes#typescript#rust#go
Typescript
ts
function getInput(): string {
return `forward 5
down 5
forward 8
up 3
down 8
forward 2`
}
function parseLine(line: string): [number, number] {
const [dir, num] = line.split(' ')
const amount = +num
if (dir === 'forward')
return [amount, 0]
else if (dir === 'up')
return [0, -amount]
return [0, amount]
}
const out = getInput()
.split('\n')
.map(x => parseLine(x))
.reduce((acc, amount) => {
acc[0] += amount[0]
acc[1] += amount[1]
return acc
}, [0, 0])
console.log(out, out[0] * out[1])
Go
go
package main
import (
"fmt"
"log"
"strconv"
"strings"
)
func getInput() string {
return `forward 5
down 5
forward 8
up 3
down 8
forward 2`
}
type Point struct {
x int
y int
}
func parseLine(line string) Point {
parts := strings.Split(line, " ")
amount, err := strconv.Atoi(parts[1])
if err != nil {
log.Fatal("This should never happen")
}
if parts[0] == "forward" {
return Point{
x: amount,
y: 0,
}
} else if parts[0] == "up" {
return Point{
x: 0,
y: -amount,
}
}
return Point{
x: 0,
y: amount,
}
}
func main() {
lines := strings.Split(getInput(), "\n")
pos := Point{0, 0}
for _, line := range lines {
amount := parseLine(line)
pos.x += amount.x
pos.y += amount.y
}
fmt.Printf("point: %+v", pos)
}
Rust
rust
fn get_input() -> &'static str {
"forward 5
down 5
forward 8
up 3
down 8
forward 2"
}
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn parse_line(line: &str) -> Point {
let (dir, amount) = line.split_once(' ').expect("Must contain a whitespace");
let amount = str::parse::<i32>(amount).expect("second part must be an integer");
if dir == "forward" {
return Point { x: amount, y: 0 };
} else if dir == "up" {
return Point { x: 0, y: -amount };
}
Point { x: 0, y: amount }
}
fn main() {
let result =
get_input()
.lines()
.map(parse_line)
.fold(Point { x: 0, y: 0 }, |mut acc, point| {
acc.x += point.x;
acc.y += point.y;
acc
});
println!("Result: {:?}", result);
}