/aocg/ - Advent of Code General #6

Babbies First Infosec Edition!
Previous thread: adventofcode.com/
>Advent of Code is a series of small programming puzzles for a variety of skill levels. They are self-contained and are just as appropriate for an expert who wants to stay sharp as they are for a beginner who is just learning to code. Each puzzle calls upon different skills and has two parts that build on a theme.

Every puzzle gives you an input file, you provide the correct output, so there's no need to submit code.
Sup Forums has it's own private leaderboard

join code: 194764-c554ff91

You need to register with an account but you can appear as anonymous.
Also, (anonymous user #194764), please delete the the users with no stars off your leaderboard so new people can join.

Other urls found in this thread:

jetbrains.com/ruby/
sabrefilms.co.uk/revolutionelite/
paiza.jp/poh/ando
paiza.jp/poh/enshura
paiza.jp/poh/enshura-special
codingame.com/
rosalind.info/problems/locations/
exercism.io/
codewars.com/
codechef.com/
pythonchallenge.com/
codingame.com/multiplayer/clashofcode
paiza.jp/poh/ec-campaign?locale=en
xkcd.com/936/
twitter.com/AnonBabble

fugg beat me to the new thread

also that leaderboard is full I think

>join code: 194764-c554ff91
Full at the moment. I'll give one day to 0starlets before I kick them for inactivity.
There's another leaderboard with a lot of room left
join code: 43046-941b8011

I think love Javascript now.

#!/usr/bin/env node

let lines = require('fs')
.readFileSync('./' + process.argv.slice(2)[0])
.toString()
.trim()
.split('\n')
.map(line => line.split(' '));

function valid(line) {
return !/(\b\S+\b).+\b\1\b/.test(line.join(' '));
}

// Part 1
console.log("Part 1: "+ lines
.reduce(function(acc, line) {
return valid(line) ? acc+1 : acc;
}, 0));

// Part 2
console.log("Part 2: "+ lines
.reduce(function(acc, line) {
return valid(line.map(w => w.split('').sort().join(''))) ? acc+1: acc;
}, 0));

process.exit();

Shitty code coming
3 foreach loops that could be fit in one

php, 4.2:

$a = explode(PHP_EOL, $input);
foreach($a as $n => $l) {
$table[$n] = explode(' ', $l);
//$table[$n] = preg_split('/\s+/', $l);
// array_pop($table[$n]);
}

foreach($table as $row_number => $row) {
if(count(array_unique($row)) !== count($row)) {
unset($table[$row_number]);
}
}

foreach($table as $row_number => $row) {
foreach($row as $word_number => $word) {
$k = str_split($word);
sort($k);
$table[$row_number][$word_number] = $k;
}
}

foreach($table as $row_number => $row) {
foreach($row as $word_number => $word) {
for($i = 0; $i < count($row); $i++) {
if($row[$i] == $word) {
if($i !== $word_number) {
unset($table[$row_number]);
}
}
}
}
}

echo count($table);

why are timezones a thing
the challenges is released 6 in the mornings
i should be /comfy/ in bed not damaging my skin from early mornings and stress

just go to bed earlier
or wake up later and stay up later
there, suddenly no timezones

>no
mommy wakes me up at 8 still when she goes to work

So when are we going to deal with space filling curves? The calendar is foreshadowing them pretty hard.

i'll just have you know you have to be 18 to post on this website

>tfw 27 goodboy neet who moved back with mommy a year ago after dropping out of uni for the third time

todays

part1:
def main():
with open("input.txt") as f:
content = f.read().splitlines()

input_list = [list(i.split()) for i in content]
valid, invalid = 0, 0

for passphrase in input_list:
if is_valid(passphrase):
valid += 1
else:
invalid += 1
print(f"Valid: {valid}, Invalid: {invalid}")


def is_valid(passphrase):
for index, word in enumerate(passphrase):
for i in range(index + 1, len(passphrase)):
if word == passphrase[i]:
return False
return True


part2:
def main():
with open("input.txt") as f:
content = f.read().splitlines()

input_list = [list(i.split()) for i in content]
invalid, valid = 0, 0

for passphrase in input_list:
if is_valid(passphrase):
valid += 1
else:
invalid += 1
print(f"Valid: {valid}, Invalid: {invalid}")


def is_valid(passphrase):
for index, word in enumerate(passphrase):
for i in range(index + 1, len(passphrase)):
if is_anagram(word, passphrase[i]):
return False
return True


def is_anagram(word_a, word_b):
word_a = list(word_a)
word_b = list(word_b)

word_a.sort()
word_b.sort()

if word_a == word_b:
return True
else:
return False


pretty easy, going to refactor and clean up now. Hope we get some more challenging ones like day 3

Stop avatarfagging or I'll bap the shit out of you.

go
package main

import (
"bufio"
"fmt"
"os"
"strings"
"sort"
)

func valid1(pwd string) bool {
words := map[string]int{}
fields := strings.Fields(pwd)
for _, w := range strings.Fields(pwd) {
words[w]++
}
return len(words) == len(fields)
}

func valid2(pwd string) bool {
words := map[string]int{}
fields := strings.Fields(pwd)
for _, w := range fields {
letters := strings.Split(w, "")
sort.Strings(letters)
w = strings.Join(letters, "")
words[w]++
}
return len(words) == len(fields)
}

func main() {
c1, c2 := 0, 0
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if valid1(line) {
c1++
}
if valid2(line) {
c2++
}
}
fmt.Println(c1, c2)
}

jeez I really miss iterators and methods on them

day4 part2 in perl

I see you're having fun with go too user

day 4 part 1 in ruby. I fucking love ruby

total = 0
File.open('input-4-1.txt').each do |l|
total += 1 if l.split(' ').size == l.split(' ').uniq.size
end
puts total

if x == y:
return True
else:
return False


Why not:
return x == y

use std::collections::BTreeSet;

fn is_valid(passphrase: &str) -> bool {
let mut m = BTreeSet::new();
for word in passphrase.split_whitespace() {
if m.contains(word) {
return false;
}
m.insert(word);
}
return true;
}

#[test]
fn test_valid() {
assert!(is_valid("aa bb cc dd ee"));
assert!(!is_valid("aa bb cc dd aa"));
assert!(is_valid("aa bb cc dd aaa"));
}

fn is_valid_anagrams(passphrase: &str) -> bool {
let mut m = BTreeSet::new();
for word in passphrase.split_whitespace() {
let mut word: Vec = word.chars().collect();
word.sort();
if m.contains(&word) {
return false;
}
m.insert(word);
}
return true;
}

#[test]
fn test_valid_anagrams() {
assert!(is_valid_anagrams("abcde fghij"));
assert!(!is_valid_anagrams("abcde xyz ecdab"));
assert!(is_valid_anagrams("a ab abc abd abf abj"));
assert!(is_valid_anagrams("iiii oiii ooii oooi oooo"));
assert!(!is_valid_anagrams("oiii ioii iioi iiio"));
}

fn main() {
let stdin = std::io::stdin();
let mut s = String::new();
let mut count = 0;
while let Ok(_) = stdin.read_line(&mut s) {
s.pop();
if s.is_empty() {
println!("Count: {}", count);
return;
}
if is_valid_anagrams(s.as_str()) {
count += 1;
}
s.clear();
}
}

This is my first year doing this. I tried to do the 2016 challenges because I was bored and I did number 1 to 7 (FUCK md5 btw)
It seems everything was just implementation issues; there was never a problem of algorithmic
Is it every time like this? Kinda boring desu

and 4-2... that was easy. I've still not done day 3 :$

def is_valid?(p)
pa = p.split
ps = pa.map{|x| x.split(//).sort.join}.uniq
pa.size == ps.size
end

total = 0
File.open('input-4-2.txt').each do |l|
total += 1 if is_valid?(l)
end
puts total

Why doesn't someone in your country make the AoC instead?

didn't see that while I was working on it, I fixed it while I was cleaning it up.

do you know any ruby gui debugger?

Afraid not. I write all my ruby in vim. I make heavy use of Pry during debugging though.

I cleaned up main a little bit:
fn main() {
let stdin = std::io::stdin();
println!("count: {}", stdin.lock()
.lines()
.filter(|line| match line {
&Ok(ref line) => is_valid_anagrams(line.trim()),
_ => panic!("io error"),
})
.count());
}

use vscode?

vim but anything is fine

as_ref was what I needed to convert &Result to Result:
fn main() {
let stdin = std::io::stdin();
println!("count: {}", stdin.lock()
.lines()
.filter(|line| is_valid_anagrams(line.as_ref().unwrap().trim()))
.count());
}

decided to shrink it down a little more

total = 0
File.open('input-4-2.txt').each do |l|
total += 1 if l.split.map{|x| x.chars.sort.join}.uniq.size == l.split.size
end
puts total

I meant you should use vscode because it has a ruby debugger

Have you lot finished the previous years' challenges? Which was your favourite?

i did the one of the last year and it was not interesting at all; boring challenges, many of the same kinds, outdated website,... there are much better alternatives for doing programming challenges.

Didn't finish 2 (D7 & D24) last year, but I liked D8 and D23 a lot.

DON'T RUIN THE CHRISTMAS SPIRIT

Nicely done, user. Ruby has an inject() method that you can use to iterate through a list and collect a total with, that you might like:

puts File.read('input-4-1.txt').each_line.inject(0) { |total, l| l.split.uniq! ? total : total + 1 }


jetbrains.com/ruby/

lol still better and more fun than pajeet-tier sites like hackerrank

List them

Kick people with 1 star too, they gave up and are useless

I'm working on AoC2015 in the downtime right now, Python

After I'm done with that I guess do AoC2016, but not sure which language I'll do that in though. Maybe Ruby

21 & 22 in 2015

Final version:
use std::collections::BTreeSet;
use std::io::prelude::*;

fn is_valid(passphrase: &str) -> bool {
let word_count = passphrase.split_whitespace().count();
let unique_words: BTreeSet = passphrase.split_whitespace().collect();
word_count == unique_words.len()
}

#[test]
fn test_valid() {
assert!(is_valid("aa bb cc dd ee"));
assert!(!is_valid("aa bb cc dd aa"));
assert!(is_valid("aa bb cc dd aaa"));
}

fn is_valid_anagrams(passphrase: &str) -> bool {
let word_count = passphrase.split_whitespace().count();
let unique_words: BTreeSet = passphrase.split_whitespace()
.map(|word| {
let mut word: Vec = word.chars().collect();
word.sort();
word
})
.collect();
word_count == unique_words.len()
}

#[test]
fn test_valid_anagrams() {
assert!(is_valid_anagrams("abcde fghij"));
assert!(!is_valid_anagrams("abcde xyz ecdab"));
assert!(is_valid_anagrams("a ab abc abd abf abj"));
assert!(is_valid_anagrams("iiii oiii ooii oooi oooo"));
assert!(!is_valid_anagrams("oiii ioii iioi iiio"));
}

fn main() {
let stdin = std::io::stdin();
let count = stdin.lock()
.lines()
.filter(|line| is_valid_anagrams(line.as_ref().unwrap().trim()))
.count();
println!("count: {}", count);
}

not that scrooge, but try something like sabrefilms.co.uk/revolutionelite/

or some ctf sites like pwnable.kr

Nah user, I'm a brainlet these thing are way too complex for me

It gets us all trying out new languages and comparing cool tricks in languages we already know, plus you can still make them challenging as code golf puzzles. If they were all very difficult then people probably wouldn't have time to keep up every day.

should give them a go at least, there's also pythonchallenge. you'll go from brainlet to less brainlet in a short time

Nice, just ready the rubydoc on #uniq! after looking at your code. I didn't know this:
Returns nil if no changes are made (that is, no duplicates are found).

Managed to shrink 4-2.rb down even more as a result:

puts File.read('input-4-2.txt').each_line.inject(0){|t,l| x=l.split; x.map{|x| x.chars.sort.join}.uniq! ? t : t+1}

paiza is definitively the best but it's japanese only. they have the most funny challenges to do, like the one where you have to program your own girlfriends paiza.jp/poh/ando

they did one hackaton for the international audience:

paiza.jp/poh/enshura
paiza.jp/poh/enshura-special

otherwise, i would say

codingame.com/
rosalind.info/problems/locations/
exercism.io/
codewars.com/
codechef.com/

and there was one where you had to debug a small code before the given time run out but i can't remember the name.

weeb challenges? no thanks.

all of those (except maybe rosalind, which is specifically about bioinformatics) are cs undergrad boring as fuck level challenges.

codingame challenges are quite hard. try the one from Nintendo.

I taught myself to program with k&r and codeeval.com, I stopped going when they fucked up the way they calculate runtime and started giving me shit scores for my C programs.

>no project euler

>codeeval.com
did you find any work through it? or is the site only about epeen?

last time i checked, it was not really made with programming in mind.

I'd add
pythonchallenge.com/
It assumes you're using python but you can do it in pretty much any language. The hints may not make much sense though.

the encryption one? meh, doesn't look particularly interesting though. Just some dry bit manipulation, not fun at all.

Doesn't matter at this point, the site's shutting down
I would say try hackerrank as an alternative but they only recommend you to jobs in a few cities and mine isn't one of them
So I don't know if it actually works

if actually much deeper than that, you can simply reverse the encryption procedure because there is a lost of informations.

if you want fun,

codingame.com/multiplayer/clashofcode

Even if you're right the point is that AoC is something that Sup Forums can get excited about together every midnight
You can try to make a coding challenges general thread but I don't think it'll go very fast because it would have no focus

>tfw too brainlet to understand this taxicab geometry
why live

>doing AoC with Python
>Python outright gives you the methods to do Day 4

Probably for the best to have a breather from yesterday though.

it's interesting because of the community, not because of aoc itself.

>program your own girlfriends
I guess it's time to learn japanese

>codingame.com/multiplayer/clashofcode

ok, i like the idea of quick 5 minute programming races with friends, but can't get behind the interface; shit's really over-engineered. plenty of other sites.

If you're still stuck on Problem 3, here's a hint:

You can only go in one of the four cardinal directions. Each movement is one "step"

If you're on the same row as the middle, the number of steps is the distance from your column to the middle column
If you're on the same column as the middle, a similar argument follows.

Now find a way to do {Current Position} -> {Same Row as Destination} -> {Same Column as Destination}

this one also is available in english

paiza.jp/poh/ec-campaign?locale=en

thanks fwinned

I don't imagine that part being a problem, the problem is figuring out what row and column my input is located on. Is there some kind of equation which you can figure out that'll tell you where it's located? I don't want the answer, just asking if that's the right way to approach it because I'm not seeing a pattern so far

Streaming a guy who is newbie at C# doing those challenges.

twitch tv automatic1111

We had a weekly programming project general for some time but people quickly got bored of it.

Doing tasks with Sup Forums is fun though, regardless of what it is

If you're asking whether it's possible to do Part 1 without building the array, then yes, there is a pattern that each ring of the square follows.

So I'm assuming you haven't figured out how to make a spiral array.

To make the spiral array, you'll need to "change directions". If you start at the middle, you'll need to go right, then up, then left, then down, etc..

The biggest problem in making the spiral array is figuring out when to rotate, and there are several ways of doing this:
The method I used is realizing that, you rotate at the "corners" (except for the bottom right, that's the 'corner + 1' rotation), so if you figure out these numbers, then you can focus exclusively on which direction you need to do. If you need help coming up with a solution, look at the bottom-right corner of each "layer" and see what you get as the relationship.

Another method is realizing that you start at 1, then you move RIGHT, 1
then UP 1
then LEFT 2
then DOWN 2
then RIGHT 3

etc...
So there's definitely a pattern when it comes to figuring out at which point you should rotate.

My #4 solutions

// part 1
let result1 = input
.split('\n')
.map(row => row.split(' '))
.filter(row => new Set(row).size === row.length)
.length;

console.log(result1);

// part 2
let result2 = input
.split('\n')
.map(row => row
.split(' ')
.map(word => word.split('').sort().join(''))
)
.filter(row => new Set(row).size === row.length)
.length;

console.log(result2);

First part

kek
I gave my android waifu programming socks
10/10

>people inlining thousands of lines of puzzle input

jeezus people, just put it in its own file

>m-m-muh runtime

Day four.

const validatePassPhrase = userInputString => {
const tracker = userInputString
.split(" ")
.reduce(
(total, item) => ({ ...total, [item]: (total[item] || 0) + 1 }),
{}
);

return Object.keys(tracker).reduce(
(total, key) => (total ? tracker[key] === 1 : total),
true
);
};

Second part

ever considered reading input from stdin over copy pasting it into code?

>pub fn
Why. What possible reason could there be for a language to truncate "public" to "pub" and "func" or "function" to "fn"?
It makes it so fucking stupid to read

Copypasting is faster

I think the original creator, Graydon Hoare, didn't want keywords longer than 5 letters, for some autistic reason

>private leaderboard is full

you guys have a discord by any chance?

See

Day one.

/**
* Functions.
*/
const reducer = initial => (total, current, i) => {
const currentNumberStr = current;
const nextNumberStr = i + 1 < initial.length ? initial[i + 1] : initial[0];
const currentNumber = parseInt(currentNumberStr, 10);
const nextNumber = parseInt(nextNumberStr, 10);
return currentNumber === nextNumber ? currentNumber + total : total;
};

/**
* Handle user input.
*/
const input = process.argv[2].split("");
const value = input.reduce(reducer(input), 0);

/**
* Display output.
*/
console.log(value);

Rena a best

wtf I love rust now
where do I subscribe ?

>weeb challenges? no thanks.
why?

Day two.

/**
* Input.
*/
const spreadsheet = [[5, 1, 9, 5], [7, 5, 3], [2, 4, 6, 8]];

/**
* Functions.
*/
const calculateChecksumFromSpreadsheet = sp =>
sp.reduce((spTotal, row) => {
const min = row.reduce((rTotal, i) => (i < rTotal ? i : rTotal), Infinity);
const max = row.reduce((rTotal, i) => (i > rTotal ? i : rTotal), 0);
return spTotal + (max - min);
}, 0);

/**
* Get output and display.
*/
const data = calculateChecksumFromSpreadsheet(spreadsheet);
console.log(data);

i don't get day 4's image

I'd love to be able to get aroused by cartoon pussy, it'd really make my NEETness complete. Just doesn't do it for me is all.

xkcd.com/936/

Advent of Code day 3 part 1 in O(1), python

def hamiltonOfSpiral(number):
print ((1 + int((int(sqrt(number - 0.5)) + ((int(sqrt(number - 0.5)) % 2) - 1)) / 2)) + abs(((2 * (1 + int((int(sqrt(number - 0.5)) + ((int(sqrt(number - 0.5)) % 2) - 1)) / 2)))/2) - ((number - (int((int(sqrt(number - 0.5)) + ((int(sqrt(number - 0.5)) % 2) - 1))) * int((int(sqrt(number - 0.5)) + ((int(sqrt(number - 0.5)) % 2) - 1)))) - 1) % (2 * (1 + int((int(sqrt(number - 0.5)) + ((int(sqrt(number - 0.5)) % 2) - 1)) / 2))) + 1)))

>wanting to lewd the anime girl

>it runs faster if it's all on one line

No it doesn't, because some calculations are repeated. It would run faster by buffering them. It's more fun if it's all on one line though. And considering it calculates the result instantly for 200+ digit numbers I think it's fast enough.

BAZIMGA MY FRIEND
LOL

Oh I see, you're meant to appreciate the narrative, not the shading between the kid's legs. Even so, I'll stick to AoC's ascii art, if you don't mind.