Quantcast
[ 3 / biz / cgl / ck / diy / fa / g / ic / jp / lit / sci / tg / vr / vt ] [ index / top / reports / report a bug ] [ 4plebs / archived.moe / rbt ]

Due to resource constraints, /g/ and /tg/ will no longer be archived or available. Other archivers continue to archive these boards.Become a Patron!

/g/ - Technology


View post   

[ Toggle deleted replies ]
File: 2 KB, 392x260, file.png [View same] [iqdb] [saucenao] [google] [report]
68750257 No.68750257 [Reply] [Original] [archived.moe] [rbt]

Previous thread: >>68747045

http://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.
You need to register with an account but you can appear as anonymous.

Private leaderboard join code: 368748-e33dcae3


People who are inactive for 5 days will be kicked, but other leaderboards can be made if desired.

>> No.68750263

>>68750257
Is it an LCS alg?

>> No.68750269

>tfw brainlet

>> No.68750270

Where my Emacs Lisp boys at?
part 1
(let* ((ids (with-temp-buffer
(insert-file-contents (expand-file-name "./day02-input"))
(split-string (buffer-string) "\n" t)))
(alphabet (cl-loop for x from 97 to 122
collect x))
(checksum-2 0)
(checksum-3 0))
(mapc (lambda (id)
(let ((has-letter-2 nil)
(has-letter-3 nil))
(mapc (lambda (letter)
(let ((count (cl-count letter id)))
(when (= count 2)
(setq has-letter-2 t))
(when (= count 3)
(setq has-letter-3 t))))
alphabet)
(when has-letter-2
(setq checksum-2 (+ checksum-2 1)))
(when has-letter-3
(setq checksum-3 (+ checksum-3 1)))))
ids)
(* checksum-2 checksum-3))

>> No.68750275

>>68750257
>inactive for 5 days
you should prune zerostarlets tomorrow and then go with the 5 days rule for everyone else

>> No.68750277

>>68750263
It was supposed to be the table from http://www.levenshtein.net/ but I copied a gif into a clipboard and fucked up the thread.

>> No.68750294

>>68750275
2 stars for each day should be mandatory (with a delay of 5 days, or less).

>> No.68750298

file = [s[0:len(s) - 1] for s in open('files/puzzle2.txt').readlines()]
two_count = 0
three_count = 0

for i, s in enumerate(file):
letter_table = [0 for idx in range(26)]
two_count_inc = 0
three_count_inc = 0

for c in s:
letter_table[ord(c) - ord('a')] += 1

for l in letter_table:
if l == 2:
two_count_inc = 1
if l == 3:
three_count_inc = 1

two_count += two_count_inc
three_count += three_count_inc

for ss in file[0: i]:
if sum([ord(a) ^ ord(b) >= 1 for a, b in zip(s, ss)]) == 1:
print ''.join(['' if ord(a) ^ ord(b) else a for a, b in zip(s, ss)])

print two_count * three_count


I couldn't figure out a a better way for part 2 other than brute force, I was trying to solve it with a radix tree for a while but gave up.

Whats the non brainlet strat?

>> No.68750301

Alright so I'm trying to optimize my Python solution for D2P2 and I've ran into some weird anomaly.
Currently what I do is I just generate combinations for the input and check that but this obviously generates duplicates, so I tried by simply looping twice over the input however this actually makes the runtime worse from 75ms avg to 95ms avg.
Another thing I tried was converting the combinations result to a set to get unique combinations and here's where the puzzling part starts: Python runs the solution in anywhere between 10ms and 120ms (varies highly between runs) whereas PyPy runs it in consistent 45ms (vs 16ms using naive combinations approach). What the fuck is going on.

>> No.68750304

>he didn't convert his strings to matrices as first step
never gonna make it

>> No.68750325

>>68750298
You don't actually need to optimize anything. I did the most obvious strategy which was just comparing every string with every string and I still measured it to run at 7ms (counting PowerShell command parsing time)

>> No.68750338

Python

part 1

def main():
two_letters = 0
three_letters = 0
data = [ID.strip() for ID in open('input', 'rt').readlines()]

for ID in data:
has_three_letters = False
has_two_letters = False
for letter in ID:
if ID.count(letter) == 3 and not has_three_letters:
three_letters += 1
has_three_letters = True
if ID.count(letter) == 2 and not has_two_letters:
two_letters += 1
has_two_letters = True

print(two_letters * three_letters)
return 0


exit(main())

>> No.68750341

>>68750257
MATLAB stronk.

My solution to part 2 for today, where data is a column vector with all the input strings.

box1 = 0;
box2 = 0;

for i = 1:length(data)
tmp = data ~= data(i,:);
ones = find(sum(tmp, 2) == 1);

if length(ones) == 1
box1 = data(i,:);
box2 = data(ones,:);
break
end
end

uncommon_char_index = find((box1 ~= box2) == 1);
box1(uncommon_char_index) = []

>> No.68750346

>>68750338

part 2

def main():
data = [ID.strip() for ID in open('input', 'rt').readlines()]

for ID1 in data:
for ID2 in data:
if ID1 != ID2:
common_letters = ""
uncommon_letters_count = len(ID1)
for i in range(len(ID1)):
if ID1[i] == ID2[i]:
uncommon_letters_count -= 1
common_letters = common_letters + ID1[i]
if uncommon_letters_count == 1:
print(common_letters)
return 0


exit(main())

>> No.68750392
File: 4 KB, 1014x119, file.png [View same] [iqdb] [saucenao] [google] [report]
68750392

>>68750301
I did some more testing and here's the results visualization.

>> No.68750393

repostan my code for feedback
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>

int main() {
std::vector<std::string> lines;

int threes = 0, twos = 0;
for (std::string line; std::getline(std::cin, line);) {
lines.push_back(line);

std::unordered_map<char, int> count;
for (auto c: line)
count[c]++;

if (std::any_of(count.begin(), count.end(), [](auto const& p){return p.second == 3;}))
threes++;
if (std::any_of(count.begin(), count.end(), [](auto const& p){return p.second == 2;}))
twos++;
}

std::cout << threes * twos << std::endl;

auto diff_one = [] (std::string const& a, std::string const& b) {
int c = 0;
for (size_t i = 0; i < a.size(); i++) {
if (a[i] != b[i] && ++c > 1)
return false;
}
return c == 1;
};

for (size_t i = 0; i < lines.size(); i++) {
for (size_t j = i+1; j < lines.size(); j++) {
if (diff_one(lines[i], lines[j])) {
auto l = lines[i];
auto p = l.find_first_not_of(lines[j]);
l.erase(p, 1);
std::cout << l << std::endl;
return 0;
}
}
}

return 0;
}

>> No.68750439

(use-modules (ice-9 rdelim))
(use-modules (srfi srfi-1))

(define (read-list f)
(let ((s (read-line f 'trim)))
(if (eof-object? s) '()
(cons s (read-list f)))))

(define (slist->intllist sl)
(map (lambda (s) (map (lambda (c) (- (char->integer c) 97)) (string->list s))) sl ))

(define (do-line l) (count-map (fold do-line-help (make-array 0 26) l)))
(define (do-line-help i tbl)
(array-set! tbl (+ 1 (array-ref tbl i)) i) tbl)

(define (count-map tbl)
(let ((n2 0) (n3 0))
(array-for-each (lambda (n)
(cond ((= n 2) (set! n2 1))
((= n 3) (set! n3 1)))) tbl)
`(,n2 ,n3)))

(define (padd a b) `(,(+ (car a) (car b)) ,(+ (cadr a) (cadr b))))

(define (part1 l) (apply * (fold padd '(0 0) (map do-line l))))

(define (all-eq-but-one x y)
(cond ((null? x) #f)
((= (car x) (car y)) (all-eq-but-one (cdr x) (cdr y)))
(else (equal? (cdr x) (cdr y)))))

(define (allpairs y0 x y )
(cond ((null? x) '())
((null? y) (allpairs (cdr y0) (cdr x) (cdr y0)))
(else (cons `(,(car x) . ,(car y)) (allpairs y0 x (cdr y))))))

(define (revert p)
(list->string (map (compose integer->char (lambda (i) (+ i 97)) car)
(filter (lambda (l) (apply = l)) (zip (car p) (cdr p))))))

(define (part2 l)
(revert (find (lambda (p) (all-eq-but-one (car p) (cdr p))) (allpairs l l l))))

(let* ((f (open-input-file "input.txt"))
(l (slist->intllist (read-list f))))
(format #t "p1: ~a\n" (part1 l))
(format #t "p2: ~a\n" (part2 l)))

>> No.68750457

weep at my autsim , but in all fairness I dont think its too bad , I know some duplicate values may get added to my list in the first part but its fine really.
a= open('input.txt','r').read().replace("\n"," ").split(" ")[0:-1]
#partone
cdic = {}
m3 = 0
m2 = 0
crli = []
cur = ""
for i in a:
cdic = {}
cur = i

for r in i:
if r in cdic:
cdic[r] +=1
else:
cdic[r] = 1

if 3 in cdic.values():
m3+=1
crli.append(cur)
if 2 in cdic.values():
m2+=1
crli.append(cur)

print(m3*m2)

#part two
a = crli

cdic = {}
samec = 0
ans = ""
for i in a:

for r in a:
samec = 0

if i == r:
break

else:
for k in range(0,len(i)):
if i[k] == r[k]:
samec +=1
if samec + 1 == len(i):
for z in range(0,len(i)):
if i[z] == r[z]:
ans+= i[z]

print(ans)

>> No.68750458

I failed on 2nd part drastically, had to do O(n^2) solution because I couldn't make a robust O(n) on-spot

import sys
from collections import Counter

def part_one(lines):
two = 0
three = 0
for line in lines:
counts = set(Counter(line.strip()).values())
if 2 in counts:
two += 1
if 3 in counts:
three += 1
print(two * three)

def ex_one_dif(a, b):
if len(a) != len(b):
return False
c = 0
for i in range(len(a)):
if (a[:i] + a[i+1:]) == (b[:i] + b[i+1:]):
c += 1
return c == 1

def part_two(lines):
for i in range(len(lines)):
for j in range(i + 1, len(lines)):
if ex_one_dif(lines[i], lines[j]):
print(lines[i])
print(lines[j])

lines = [i.strip() for i in sys.stdin ]
part_one(lines)
part_two(lines)

>> No.68750479 [DELETED] 

module Day02 where

import Data.List

file :: IO String
Haskell:
file = readFile "input"

occursTimes :: Ord a => Int -> [a] -> Bool
occursTimes n = elem n . map length . group . sort

ifOccursTimesAdd n l | occursTimes n l = (+1)
| otherwise = id

countBoth :: (Traversable t, Ord a) => t [a] -> (Int, Int)
countBoth = foldl f (0,0)
where f (a, b) str = ( ifOccursTimesAdd 2 str a
, ifOccursTimesAdd 3 str b)

star1 :: IO Int
star1 = uncurry (*) . countBoth . lines <$> file

differ :: (Eq a, Num t) => [a] -> [a] -> (t, [a])
differ = go 0 []
where go n rs xs ys = case (xs, ys) of
(a:as, b:bs) | a == b -> go n (a:rs) as bs
| otherwise -> go (n + 1) rs as bs
([],[]) -> (n, reverse rs)
_ -> error "something happened"

findOneDiff :: (Applicative t, Foldable t) => t String -> String
findOneDiff l = maybe "something happened" snd . find ((== 1) . fst)
$ differ <$> l <*> l

star2 :: IO String
star2 = findOneDiff . lines <$> file

main :: IO ()
main = star1 >>= print >> star2 >>= print

>> No.68750516

>>68750457
with open(‘input.txt’, ‘’) as f:data = f.read()

>> No.68750522

Haskell:

module Day02 where

import Data.List

file :: IO String
file = readFile "input"

occursTimes :: Ord a => Int -> [a] -> Bool
occursTimes n = elem n . map length . group . sort

ifOccursTimesAdd n l | occursTimes n l = (+1)
| otherwise = id

countBoth :: (Traversable t, Ord a) => t [a] -> (Int, Int)
countBoth = foldl f (0,0)
where f (a, b) str = ( ifOccursTimesAdd 2 str a
, ifOccursTimesAdd 3 str b)

star1 :: IO Int
star1 = uncurry (*) . countBoth . lines <$> file

differ :: (Eq a, Num t) => [a] -> [a] -> (t, [a])
differ = go 0 []
where go n rs xs ys = case (xs, ys) of
(a:as, b:bs) | a == b -> go n (a:rs) as bs
| otherwise -> go (n + 1) rs as bs
([],[]) -> (n, reverse rs)
_ -> error "something happened"

findOneDiff :: (Applicative t, Foldable t) => t String -> String
findOneDiff l = maybe "something happened" snd . find ((== 1) . fst)
$ differ <$> l <*> l

star2 :: IO String
star2 = findOneDiff . lines <$> file

main :: IO ()
main = star1 >>= print >> star2 >>= print


What are runtimes like today? This runs in 17ms.

>> No.68750530

>>68750457

in part 2 your second loop doesn't need to traverse the whole file, either traverse all the elements in a up to i, or all the elements in a after i.

there's obviously places where you could cut down some code with in built functions/ small shortcuts but your alg is otherwise solid.

>> No.68750531

for me, it's part 2
std::string solve_part_two(std::ifstream& ifs)
{
std::string line;
std::vector<std::string> lines;
while (std::getline(ifs, line))
lines.push_back(std::move(line));

std::sort(lines.begin(), lines.end());

const std::size_t ROWS = lines.size();
const std::size_t COLS = lines.front().size();
for (std::size_t i = 0; i < ROWS - 1; ++i) {
std::size_t diffs = 0;
for (std::size_t j = 0; j < COLS; ++j) {
if (lines[i][j] != lines[i + 1][j] && diffs++ != 0)
break;
}

if (diffs == 1) {
std::string common_chars;
for (std::size_t j = 0; j < COLS; ++j) {
if (lines[i][j] == lines[i + 1][j]) {
common_chars.push_back(lines[i][j]);
}
}

return common_chars;
}
}

return {};
}


anything better than O(N^2) possible?

>>68750341
matlab is neat

>> No.68750542
File: 50 KB, 645x729, 1506099199074.png [View same] [iqdb] [saucenao] [google] [report]
68750542

>>68750257
just find a library to solve the problem for you lmaoooo

from jellyfish import levenshtein_distance

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

best_distance = 99999

for s1 in content:
for s2 in content:
if s1 == s2:
break
else:
if levenshtein_distance(s1, s2) < best_distance:
best_distance = levenshtein_distance(s1, s2)
best_s1 = s1
best_s2 = s2

print(best_distance)
print(best_s1)
print(best_s2)

>> No.68750544

>>68750531
no wait, this is O(N).

>> No.68750552

>>68750544
O(NlogN)*

>> No.68750561

(defn has-multiple-char [multiple string]
(some #(= (second %) multiple) (frequencies string)))

(defn hamming-distance [s1 s2]
(if (not (= (count s1) (count s2)))
nil
(reduce (fn [acc cur]
(if (= (first cur) (second cur))
acc (inc acc)))
0
(map vector s1 s2))))

(let [input (str/split (slurp "input2.txt") #"\n")]
(let [twos (filter (partial has-multiple-char 2) input)
threes (filter (partial has-multiple-char 3) input)]
(* (count twos) (count threes))))

(let [input (str/split (slurp "input2.txt") #"\n")]
(let [twos (filter (partial has-multiple-char 2) input)
threes (filter (partial has-multiple-char 3) input)
all (distinct (concat twos threes))]
(filter
(fn [[s1 s2]] (= 1 (hamming-distance s1 s2)))
(combo/combinations all 2))))

Clojure

>> No.68750562

Any way I could make this code more "rusty"?
use std::fs;

fn main() {
let contents = fs::read_to_string("input.txt").unwrap();

for id in contents.lines() {
contents.lines().for_each(|other| {
if diff_chars(id, other) == 1 {
println!("{}", id);
}
})
}
}

fn diff_chars(id: &str, other: &str) -> i32 {
if id.len() != other.len() {
return -1;
}

let mut diff_chars = 0;
id.chars().zip(other.chars()).for_each(|(a, b)| {
if a != b {
diff_chars += 1
}
});
diff_chars
}

>> No.68750566
File: 46 KB, 774x1236, Capture.png [View same] [iqdb] [saucenao] [google] [report]
68750566

>> No.68750568

>>68750522
my haskell solution runs in 9ms, my scheme solution takes about 25

>> No.68750574

#include <list>
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>

int main()
{
std::fstream f("f.txt");

std::stringstream ss;

ss << f.rdbuf();

unsigned three = 0, two = 0;

std::string line;
std::list<std::string> list;
while (std::getline(ss, line))
{
list.push_back(line);
}
while (list.size())
{
std::list<std::string>::const_iterator i = list.cbegin();
std::string st = *i;
++i;
for (; i != list.cend(); ++i)
{
unsigned comp = 0;
for (unsigned u = 0; u < i->length(); ++u)
{
if (i->at(u) != st[u])
{
++comp;
}
if (comp > 1)
{
break;
}
}
if (comp == 1)
{
std::cout << st << " " << *i;
return 0;
}
}
list.pop_front();
}
return -1;
}



How bad am I?

>> No.68750581

>>68750393
sort your input for an easy speed boost! see >>68750531

>> No.68750619

arg = get_input(1)
S = set()
for line in arg:
m = len(line)
S2 = set()
for k in range(m):
ss = line[0:k] + line[k+1:m]
if ss in S:
print(ss)
else:
S2.add(ss)
for ss in S2:
S.add(ss)


What do you think about this?
With N the number of words and M the length of a word, I think it would be O(NM)

I don't know the complexity of ss = line[0:k] + line[k+1:m], so it could be O(NM2). Still, it's linear in N

>> No.68750620

>>68750581
>mfw
impressive

>> No.68750624
File: 12 KB, 646x144, Screenshot from 2018-12-02 14-15-28.png [View same] [iqdb] [saucenao] [google] [report]
68750624

Oh damn I didn't realize the timer starts when the puzzle unlocks.
I thought it depends on when you generate your input or open the page or something like that.
Do you guys set an alarm to solve the puzzles on time?

>> No.68750633

>>68750624
no, I like sleeping

>> No.68750641

>>68750257
No image for the day yet?

>> No.68750644

>>68750624
must of us are here at midnight/when the puzzle unlocks.

>> No.68750645

>>68750624
Yeah, I wake up at 5AM to shitpost here, then do the puzzle an hour later

>> No.68750647

>>68750624
No I get up at around 11 AM and the puzzle unlocks at 6 so it's not worth it. Last year I worked night shifts so I was doing them on release but I won't reschedule my sleep for a puzzle.

>> No.68750659

>>68750531
Yeah MATLAB was especially good for day 2 as it's nice to solve with matrix manipulations.

>> No.68750669

>>68750633 >>68750647
ye I don't feel like waking up at 6 am just to do a puzzle and feel like shit the rest of the day at work.
guess that means I'm not getting anyplace high in the leaderboards
>>68750644 >>68750645
anyone here on the global leaderboards?

>> No.68750670

>>68750574
You could use a const string reference instead of deep copy for st.
Also you need to strip the duplicate letters from your output.

>> No.68750675

>>68750669
#44

>> No.68750677

>>68750675
I'm #43 :^)

>> No.68750684

>>68750624
It starts at 3:00 in the evening for me. :^)

>> No.68750686

Apologies to people who actually know Common Lisp.
(defun count-char-occurances (line)
(let ((counter (make-hash-table)))
(loop for c across line do
(let ((m (gethash c counter)))
(if (not (null m))
(setf (gethash c counter) (1+ m))
(setf (gethash c counter) 1))))
counter))

(defun count-groups (hash)
(let ((two-count 0)
(three-count 0))
(maphash #'(lambda (k v)
(cond ((= v 2) (setf two-count 1))
((= v 3) (setf three-count 1))))
hash)
(list two-count three-count)))

(defun first-part (input)
(let ((two-total 0)
(three-total 0))
(dolist (l input)
(let ((result (count-groups (count-char-occurances l))))
(incf two-total (first result))
(incf three-total (second result))))
(* two-total three-total)))

(defun char-onediffp (x y)
(let ((diff-count 0))
(loop
for i in (coerce x 'list)
for j in (coerce y 'list)
if (char/= i j)
do (incf diff-count)
when (> diff-count 1)
do (return-from char-onediffp t))
nil))

(defun find-similar-lines (input)
(let ((lines (copy-list input))
(results ()))
(dolist (line lines)
(let ((comparisons (remove-if #'(lambda (l) (or (string= line l)
(char-onediffp line l)))
lines)))
(if comparisons (push line results))))
results))

(defun str-to-char-list (l)
(mapcar #'(lambda (x) (coerce x 'list)) l))

(defun second-part (lines)
(let ((similar (str-to-char-list (find-similar-lines lines))))
(coerce (loop
for i in (first similar)
for j in (second similar)
if (char= i j)
collect i)
'string)))

>> No.68750699

>>68750677
Nice
We'll see if we get to stay or not, I've been lucky yesterday and today but I don't think it's going to last

>> No.68750703

>>68750670
Oh yeah I was a bit lazy and did the stripping myself. That's why I print out both strings. But you're right; I'm bad when it comes to using references, I'll keep it in mind.

>> No.68750707
File: 303 KB, 971x444, rusty.png [View same] [iqdb] [saucenao] [google] [report]
68750707

>>68750562

>> No.68750712

>>68750531
I tried to do it O(n) in n
static void FindPairLinear(string file)
{
string[] words = File.ReadAllLines(file);
int wordsize = words[0].Length;
HashSet<string>[] hs = new HashSet<string>[words.Length];

for (int i = 0; i < words.Length; i++)
for (int j = 0; j < wordsize; j++)
{
if (hs[j] == null) hs[j] = new HashSet<string>();

string word = words[i].Substring(0, j) +
words[i].Substring(j + 1, words[i].Length - j - 1);

if (!hs[j].Add(word))
{
Console.WriteLine(word);
return;
}
}
}

>> No.68750713
File: 450 KB, 1280x1032, diogenes.jpg [View same] [iqdb] [saucenao] [google] [report]
68750713

>>68750699
I wouldn't lie on the internet, would I.

>>68750341
Also part 1 for my MATLAB solution

alphabet = 'a':'z';
alphabet = alphabet';

twice_thrice_map = zeros(length(data), 2);

for i = 1:length(alphabet)
s = sum(data(:,:) == alphabet(i), 2);
twos = find(s == 2);
threes = find(s == 3);
twice_thrice_map(twos,1) = 1;
twice_thrice_map(threes, 2) = 1;
end

checksum = sum(twice_thrice_map(:,1)) * sum(twice_thrice_map(:,2))

>> No.68750723
File: 10 KB, 250x250, 1443553636207.jpg [View same] [iqdb] [saucenao] [google] [report]
68750723

I DONT FUCKING UNDERSTAND IT

>> No.68750732

>>68750723
?

>> No.68750736

>>68750723
install gentoo

>> No.68750738

>>68750619
Answer me you fucks

>> No.68750757

>>68750732
How does one go about finding a proper candidate for twice if the char that occurs thrice is the same that you found twice?
How to find another proper candidate.

>> No.68750758

>>68750619
This won't work for this test case:

abcd
acde

They have a hamming distance of 3, but your algorithm would find these two in your set
a_cd
acd_

thus giving a false positive.

That happened to me too and I fixed it by using a lot of sets here:
>>68750712

>> No.68750759

>>68750712
that's at least O(nm), m being the length of the words. might be more depending on the complexity of Substring and concat

>> No.68750766

>>68750712
looks like you're quadratic in line size

>> No.68750769

>>68750759
the post I quoted disregarded M so I did too, but yeah you're completely right.

>> No.68750771

kinda disappointed in part two, there should've been more data
there's so little that the naive solution in python runs under a second

>> No.68750776
File: 63 KB, 548x810, day2.png [View same] [iqdb] [saucenao] [google] [report]
68750776

>>68750562
>>68750707
heres mine

>> No.68750782

>>68750757
There's only two ids that differ by one.

>> No.68750784
File: 33 KB, 840x182, file.png [View same] [iqdb] [saucenao] [google] [report]
68750784

>>68750757
read the instructions of the problem...

>> No.68750785

>>68750757
*exactly* two of any letter
*exactly* three of any letter


Definition of exactly

1a : in a manner or measure or to a degree or number that strictly conforms to a fact or condition

so if you have a 3x then it doesn't count towards 2x

>> No.68750790

>>68750758
Oh right I forgot about that

>> No.68750795

>>68750686
Then the slightly better attempt that my own shame compelled me to do.
(defun count-repeated (s)
(let ((counter ()))
(loop for c across s
for m = (assoc c counter)
do (if m
(rplacd m (incf (cdr m)))
(setf counter (acons c 1 counter))))
(delete-if-not #'(lambda (x)
(or (= 2 (cdr x)) (= 3 (cdr x))))
counter)))

(defun first-part (input)
(let ((total-two 0)
(total-three 0))
(dolist (line input)
(let ((counted (count-repeated line)))
(if (rassoc 2 counted) (incf total-two))
(if (rassoc 3 counted) (incf total-three))))
(* total-two total-three)))

(defun similar-stringp (x y)
(let ((diff-count 0))
(when (not (eq x y))
(loop for i across x
for j across y
if (char/= i j)
do (incf diff-count)
when (> diff-count 1)
do (return-from similar-stringp nil)
collect i))))

(defun strip-unique (x y)
(coerce (loop for i across x
for j across y
if (char= i j)
collect i)
'string))

(defun second-part (input)
(let ((result ()))
(dolist (l input)
(dolist (s input)
(if (similar-stringp l s)
(push l result))))
(reduce #'strip-unique result)))

>> No.68750796

>>68750757
>>68750784
>read the instructions of the problem...
lmao every fucking time

>> No.68750806

>>68750757
Step away from iterating and think about recording.

>> No.68750807

>>68750776
>for
>for
>iterating over the hashmap 2 times
>'outer: for
>for
use more iterator adaptors/10

>> No.68750811

What's the required IQ to complete all the challenges last year?

>> No.68750816

>>68750811
at most 108

>> No.68750817

>>68750811
about 80

>> No.68750826

>>68750784
>>68750785
>>68750796
Yes Im fucking aware. Notice where it says counts for both?

>>68750806
halp

>> No.68750832

>>68750811
Depends on the language you're using
>List
140+
>C
130+
>Haskell
120+
>Go
100+
>Java-tier shit
80+
>Python
no requirement

>> No.68750834
File: 5 KB, 392x219, brainlet.png [View same] [iqdb] [saucenao] [google] [report]
68750834

>>68750826
forgot image god help me.

>> No.68750842
File: 164 KB, 645x773, file.png [View same] [iqdb] [saucenao] [google] [report]
68750842

>>68750826
>>68750834

>> No.68750850

>>68750832
guess that makes python the best language

>> No.68750857

>>68750832
Solving this shit in C is easier than in Haskell though.

>> No.68750866

arg = get_input(1)
S = set()
for line in arg:
m = len(line)
for k in range(m):
ss = line[0:k] + line[k+1:m]
if (ss,k) in S:
print(ss)
else:
S.add((ss,k))


>>68750758
This should be correct (executes in 15ms)
I think it's the same logic as yours >>68750712

>> No.68750871
File: 23 KB, 352x734, Capture.png [View same] [iqdb] [saucenao] [google] [report]
68750871

>>68750842
please bully me, but I've no fucking idea about which part of the problem I don't understand.

>> No.68750878
File: 50 KB, 964x917, Day02.png [View same] [iqdb] [saucenao] [google] [report]
68750878

C# Linq is my guilty pleasure.

>> No.68750883

>>68750871
I'm guessing it's the 'exactly' part

>> No.68750885

>>68750878
This guy fucks.

>> No.68750890

>>68750871
You're overengineering it.
def count(data, a):
t = 0
for l in data:
for c in l:
if l.count(c) == a:
t=t+1
break
return t
data = [x.strip() for x in open('input.txt').readlines()]
print('Checksum: ' + str(count(data,2)*count(data,3)))

You're already doing most of this in the occurance function.

>> No.68750893

>>68750878
Can't you put split.trim.isnullorempty in the Solution thing?

>> No.68750896

>>68750531
>>68750522
got 0.3ms on this one

>> No.68750900

>>68750878
Mirin'
I see you're using attributes, are you pulling the dataset automagically and checking if it works?

>> No.68750910

>>68750883
;_; thanks

>>68750890
I just wanted this to work before making it pretty and fast.

>> No.68750923

>>68750910
You're not going to get this faster than O(n).
The length of the strings is constant, so it doesn't count.

>> No.68750924

>>68750890
inefficient solution, you are looping through the data twice here when you can get all the info you need by looping it just once.

>> No.68750933

>>68750924
>inefficient solution
it's more readable, so idgaf

>> No.68750947

>>68750878
Linq is a miracle.

>> No.68750955

https://www.twitch.tv/videos/343498733##
Why aren't you watching xir stream? The creator of AoC loves this

>> No.68750957

>>68750947
It's really not, it's just C# syntax for what you do in Haskell often.
Still nice if you /have/ to work with C#, that you can write monadic interfaces to your shit and handle errors in a single function for instance.

>> No.68750969

>>68750955
is that a man?

>> No.68750986

>>68750955
why are trannies so common in the IT but not as much everywhere else? does computer autism enable mental illness?

>> No.68750988
File: 67 KB, 640x480, 1513480589362.jpg [View same] [iqdb] [saucenao] [google] [report]
68750988

>>68750955
>skip ahead
>Social media is half of my life

>> No.68750991
File: 175 KB, 295x460, Capture.png [View same] [iqdb] [saucenao] [google] [report]
68750991

>>68750969

>> No.68750993
File: 26 KB, 558x746, Capture2.png [View same] [iqdb] [saucenao] [google] [report]
68750993

>>68750883
Really though, thanks man.
I made a thing

>> No.68750998

>>68750581
why does sorting the input gives a speed boost tho? I'm getting sub 1ms times so that's great but I don't get it
I'm >>68750393 btw

>> No.68751001

>>68750893
I'll probably start shovelling things like that out into helpers at some point. To be honest I probably don't even need to do all the trimming and empty checking, just split on newline while ignoring empty entries as I don;t think any inputs so far have had leftover whitespace.

>>68750900
The attributes are just there so the program can reflect over them and work out which method corresponds the the latest solution. (or the solution for a certain day if I want to rerun an old one) It just pulls the input from the clipboard before passing it to the method at the moment, but may end up changing that up a bit later on if that starts to prove annoying.

>> No.68751004
File: 395 KB, 719x771, 1541223813581.png [View same] [iqdb] [saucenao] [google] [report]
68751004

>>68750955
>Unironic nano usage

>> No.68751005

>>68750986
Having a macbook on your nuts 24/7 probably has some weird radiation effect.

>> No.68751027

Is there some kind of website that posts these tasks?
I'm not interested in getting an account. I just want to do comfy programming tasks for christmas.

>> No.68751037

>>68751027
literally create a throwaway account takes 5 seconds

>> No.68751042

>>68750257
>A lot redditors,HN users,IOI gold medals and professional FAANG employs
>Win 4chan user
Wtf

>> No.68751046

>>68750257
Rate my python one-liner /10 (day 1)
print(sum(map(int, open("input.txt"))))

>> No.68751047

>>68750998
>why does sorting the input gives a speed boost tho
well, because then lines that differ in one place will be adjacent to each other, so you only have to compare each string to it's subsequent neighbour, instead of each subsequent string like you did (for (size_t j = i + 1, [...]).

>> No.68751058

>>68751047
oh ok so I didn't even understand what you were saying, I just added a std::sort before my loop, I'm gonna redo it

>> No.68751068

>>68751047
the latter is O(N^2) in the number of lines, while the former is O(N), but sorting is O(NlogN), so that's the effective complexity.

>> No.68751076

>>68751046
now do a day 1 part 2 one liner

>> No.68751083

>>68750955
golang is the worst part of this stream

>> No.68751118
File: 86 KB, 531x995, pajeet.jpg [View same] [iqdb] [saucenao] [google] [report]
68751118

Way too many lines for what it does but oh well, still was a <10 minute solution.

>> No.68751120

>>68751047
>>68751058
nice I get it now, sorting is O(NlogN) and finding the pair is O(N) so part2 is O(NlogN)
I get 40-100 micro seconds now ebin

>> No.68751125

java
O(n^3)
7ms

>> No.68751127

def part2():
input.sort()
for i, x in enumerate(input):
for j in range(i + 1, len(input)):
diffs = 0
common = ''
for k in range(len(input[j])):
if input[i][k] != input[j][k]:
diffs += 1
else:
common += input[i][k]
if diffs > 1:
break
if diffs == 1:
return common
if j > i + 2:
break

Ugly as shit but 1.98 ms

>> No.68751138

looking at these threads I'm convinced 99% of /g/ is just braindead retarded monkeys

>> No.68751148

>>68751138
post code or GTFO

>> No.68751162

>>68751138
please point which post are retarded monkeys

>> No.68751176

>>68750988
I remember that guy from last year who intended to stream every challenge, then hit the brainlet filter:
>seriously I mean who has time to do these every day I'm not some NEET blah blah blah

>> No.68751187

>>68751176
kek i wish i was there to see that

>> No.68751188
File: 69 KB, 676x419, Screenshot_2018-12-02_15-22-01.png [View same] [iqdb] [saucenao] [google] [report]
68751188

Here is the final version for day 2 part 2, O(NlogN)

>> No.68751190

>>68751176
On the day 3 spiral right?

>> No.68751203

how 2 program ?

>> No.68751206

>>68751188
gj. it's always good think about how sorting might make things easier
>>68751190
that one was tricky tbf

>> No.68751215

fuck this i swear i entered the exact same input 5 times before they realized it was right

>> No.68751227

>>68750832
What about MATLAB? ;)

>> No.68751234

>>68750832
>C Is a hard language
Shiggy

>> No.68751244

Any good resources for learning C++17/20 for people who already know how to program? I don't want to read 250 pages about for loops, header files and how people did it in 1993

>> No.68751253

>>68751227
MATLAB is working man tier.

>> No.68751255
File: 43 KB, 858x977, file.png [View same] [iqdb] [saucenao] [google] [report]
68751255

>> No.68751267

>>68751244
https://speakerdeck.com/olvemaudal/42-silly-ways-to-say-hello-in-modern-c-plus-plus-sep-2018

>> No.68751280
File: 121 KB, 780x520, corportae-pti-L1[2].jpg [View same] [iqdb] [saucenao] [google] [report]
68751280

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class AdventOfCode2Part2 {
public static boolean isCorrect(String s1, String s2) {
int flag = 0;
int cnt = 0;
int ind = 0;
for (int i=0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i)) {
cnt++;
ind = i;
if (cnt == 2) {
flag = 1;
break;
}
}
}

if (cnt != 1)
return false;
else {
System.out.println(ind + " " + s1.charAt(ind) + " " + s2.charAt(ind));
return true;
}
}

public static void main(String []args) throws IOException {
String st;
int cnt = 0;
String []arr = new String[250];
File file = new File("C://Users//ranjeeshsharma//Desktop//aoc1.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
int i=0;
while ((st = br.readLine()) != null) {
arr[i] = st.toString();
i++;
}

int flag = 0;
for (i=0; i < arr.length; i++) {
for (int j=0; j < arr.length; j++) {
if (i != j) {
if (isCorrect(arr[i], arr[j])) {
System.out.println(arr[i] + " ----- " + arr[j]);
flag = 1;
break;
}
}
}
if (flag == 1)
break;
}
}
}

>> No.68751307
File: 35 KB, 1024x572, member to show to vic.jpg [View same] [iqdb] [saucenao] [google] [report]
68751307

>>68751280
>C://Users//ranjeeshsharma//Desktop//aoc1.txt

>> No.68751322

Predictions on when is the brainlet filter going to be?

>> No.68751324

>>68751322
day 4

>> No.68751327

>>68751280
No offense but, fuck Java, even when currently I am at the namesake island

>> No.68751337
File: 53 KB, 500x737, 1530171555587.jpg [View same] [iqdb] [saucenao] [google] [report]
68751337

>>68751280
>people write in this language every fucking day of their life

>> No.68751374

>>68751280
that's one impressive bait

>> No.68751396
File: 23 KB, 454x435, 1527608887237.jpg [View same] [iqdb] [saucenao] [google] [report]
68751396

Reminder to prepare for the inevitable day where you'll need to do md5 hashes

>> No.68751414

>>68751396
Then prepare for the part 2 where you will have to do the hashes times billion.

>> No.68751416
File: 404 KB, 800x602, 1530121950172.png [View same] [iqdb] [saucenao] [google] [report]
68751416

Submitting tentative calendar image for review

>> No.68751426

>>68751396
import crypto/md5

>> No.68751439

>>68751416
Nice

>> No.68751443

>>68751416
Excellent.

>> No.68751447

>>68751416
it's a strong candidate, anon. i like it.

>> No.68751450

>>68751416
tfw my nigger spam might make it on the calendar
I had 500k lines of nigger in my clipboard at all time

>> No.68751452

https://wheeldecide.com/index.php?c1=Pen+and+Paper&c2=C%2FC%2B%2B&c3=Java&c4=Lisp&c5=Prolog&c6=Python&c7=Ruby&c8=Forth&c9=Haskell&c10=F%23&c11=C%23&c12=Erlang&c13=Javascript&c14=PHP&c15=%2APick+Any%2A&time=5

Have fun

>> No.68751457

>>68751416
As one of the anons in the codeshare (musicanon), this pleases me greatly.

>> No.68751460
File: 1.53 MB, 420x314, 1526456380715.gif [View same] [iqdb] [saucenao] [google] [report]
68751460

>>68751416

>> No.68751462

>>68751452
This but more saner please

>> No.68751465

I might be retarded, but there's no three letter occurrence to be found in the input.
*Main> filter (\i -> length i >= 3) $ concat $ map group i1
[]

Where i1 is the input of type [String].

>> No.68751468

>>68751457
BTW I contributed the cursive nigger, I'm at blame too.

>> No.68751471

>>68751416
I like how you can see it's the 1864084th line of nigger top jej

>> No.68751472

>>68751452
>C/C++
please do not do that

>> No.68751477

1-3ms. I am so shit at naming variables.

func main() {
var ids []string
file, _ := os.Open("2_input.txt")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
ids = append(ids, scanner.Text())
}

twice, thrice := 0, 0
p2done := false

for _, id := range ids {
//Part 1
counts := make(map[rune]int)
for _, char := range id {
if _, in := counts[char]; in {
counts[char] += 1
} else {
counts[char] = 1
}
}
twoseen, threeseen := false, false
for _, count := range counts {
if count == 2 && !twoseen {
twice += 1
twoseen = true
}
if count == 3 && !threeseen {
thrice += 1
threeseen = true
}
}
//Part 2
for _, id2 := range ids {
if id2 != id && len(id2) == len(id) && !p2done {
differences := 0
for j := 0; j < len(id2); j++ {
if id2[j] != id[j] {
differences += 1
}
}
if differences == 1 {
fmt.Println(id, id2)
p2done = true
}
}
}
}
fmt.Println(twice * thrice)
return
}

>> No.68751488

>>68751462
https://www.wheeldecide.com/index.php?c1=C&c2=Java&c3=C%2B%2B&c4=Python&c5=Ruby&c6=Haskell&c7=C%23&c8=Javascript&c9=%2APick+Any%2A&time=5

There ya go chum

>> No.68751495
File: 72 KB, 713x709, 1533908673560.jpg [View same] [iqdb] [saucenao] [google] [report]
68751495

>>68751452
Unironically got Python

>> No.68751496

>>68751465
Post a pastebin link to your input.

>> No.68751503

>>68751496
https://pastebin.com/t1Y7j8fk

>> No.68751504

My part1 solution in python:

import sys

def get_unique_letters(boxID):
return set(boxID)

def has_exactly_n(boxID, n):
uniq = get_unique_letters(boxID)
for u in uniq:
count = 0
for l in boxID:
if(l == u):
count += 1
if(count == n):
#print(u)
return 1
return 0

if(len(sys.argv) < 2):
print('Please supply input file.')
sys.exit()

boxIDs = []
f = open(sys.argv[1], 'r')
for line in f:
boxIDs.append(line)
f.close()

two_count = 0
three_count = 0
for ID in boxIDs:
#print(ID)
#print('Two: ' + str(has_exactly_n(ID, 2)) + ', Three: ' + str(has_exactly_n(ID, 3)))
two_count += has_exactly_n(ID, 2)
three_count += has_exactly_n(ID, 3)

print('Checksum: ' + str(two_count * three_count))

>> No.68751505

>>68751488
Thanks man

>> No.68751508

someone update the calendar and post it

>> No.68751511

I just solved day 2 part 2 10 hrs later using a combination of grep and stack overflow copy pasting. My only excuse is that I learned perl a day before day 1. Am I doomed to become a codemonkey for life.

>> No.68751519
File: 223 KB, 1300x1734, 1428906658299.jpg [View same] [iqdb] [saucenao] [google] [report]
68751519

>>68751416
Good shit anon.

>> No.68751522

>>68751511
Solving with only unix utils is god-tier

>> No.68751523

>>68751503
Nah youre code is just wrong, I dunno what language that is so I cannot help you but my solution finds both answers properly.

>> No.68751526

>>68751416
>MAYBE_MY_NIGGA CIA BIXNOOD STEALS CASHMONEY MUH_EQUALITY DINDUNUFFIN JAILBREAK MUHFUGGA
This is the greatest thing I've read in a long time

>> No.68751539

>>68751503
works for me anon

>> No.68751540
File: 4 KB, 327x133, times.png [View same] [iqdb] [saucenao] [google] [report]
68751540

Dear god, I must've really fucked up part one.

>> No.68751549

>>68751503
Everyone except you now has your answer, have fun debugging

>> No.68751550

>>68751511
epic post

>> No.68751556

>>68751523
>>68751539
>>68751549
I guess I'm retarded...

>> No.68751560

also we should make a codeshare everyday after a few anons have finished
it was /comfy/ as fuck

>> No.68751563

>>68751556
Run that piece on the examples so you know what is the expected result for each string, should help you find the problem.

>> No.68751579

>>68751523
>>68751539
>>68751549
>>68751563
I misinterpreted what group does. From the Haskell documentation:
>>> group "Mississippi"
["M","i","ss","i","ss","i","pp","i"]

>> No.68751585

>>68751244
just use the standard containers and algorithms, easy af
https://en.cppreference.com/w/cpp/algorithm

>> No.68751615

extern crate inputparser;


fn main() {
let file = include_str!("../day2.txt");
let input = inputparser::parse_lines::<String>(&file).unwrap();

println!("{}", find_smallest(&input).unwrap_or(String::from("Nothing found")));
}

fn find_smallest(v: &Vec<String>) -> Option<String>
{
for v1 in v.iter()
{
for v2 in v.iter()
{
if v1 == v2
{
continue;
}
if diff_points(v1, v2) == 1
{
let s = v1.chars().zip(v2.chars())
.filter(|(b1, b2)| b1 == b2)
.map(|(_, b)| b)
.collect();

return Some(s);
}
}
}

None
}

fn diff_points(v1: &String, v2: &String) -> usize
{
v1.chars().zip(v2.chars())
.filter(|(b1, b2)| b1 != b2)
.count()
}

>> No.68751627
File: 29 KB, 759x397, 1.png [View same] [iqdb] [saucenao] [google] [report]
68751627

1

>> No.68751631
File: 34 KB, 770x571, 2-01.png [View same] [iqdb] [saucenao] [google] [report]
68751631

>>68751627
2-1

>> No.68751640
File: 32 KB, 764x451, 2-02.png [View same] [iqdb] [saucenao] [google] [report]
68751640

>>68751631
2-2

>> No.68751642

wrote the O(n^2) solution for part 2 in perl and it spits out the answer in ~150ms. I improved the Hamming distance sub and shaved off 50ms. Not bad.

>> No.68751648

>>68751465
group requires input to be sorted iirc

>> No.68751650

>>68751642
That's still pretty slow, is it just Perl or do you have some more room for improvement?

>> No.68751661

Brainlet here, how do you even time your solution to milisecs?

>> No.68751670

>>68751642
My part 2 is written naively in C#, and it takes 6ms. I think u has some issues.

>> No.68751675
File: 2 KB, 377x125, file.png [View same] [iqdb] [saucenao] [google] [report]
68751675

>>68751661

>> No.68751678

>>68750277
>http://www.levenshtein.net/
It's shit like this why I enjoy these kind of threads. I'm sure this will come in handy some day.

>> No.68751684
File: 65 KB, 900x599, stopwatch.jpg [View same] [iqdb] [saucenao] [google] [report]
68751684

>>68751661

>> No.68751688

>>68751648
Correct, that's what tripped me up.

>> No.68751694

>>68751661
if you're on linux/mac use time
or you can write time measurement code around your functions and print it

>> No.68751705

>>68751037
>google
>twitter
>plebbit
>github
How about fuck you?

I can't imagine that no one has made a mirror site yet.

>> No.68751712

>>68751694
>>68751684
>>68751675

B-but time only shows increments of 10 milliseconds.

>> No.68751715

>>68751705
Because no one is as autistic as you.

>> No.68751721

>>68751675
Fuck off. He asked a legitimate question about technology.

>> No.68751726

>>68751661
def time_ms():
return int(round(time() * 1000))

def run(info):
timings = []

for index, (solve, input, fn, ) in enumerate(info):
solution_start = time_ms()
result = solve(input, fn)
timings.append(time_ms() - solution_start)
print('P{} result: {}'.format(index + 1, result))

print('Time: {} | Total: {}ms'.format(
', '.join(['{}ms (P{})'.format(time, index + 1) for (index, time, ) in enumerate(timings)]),
sum(timings)
))

>> No.68751727

Correct me if Im wrong but cant we use Kadane's algorithm for longest common subsequence?

>> No.68751729

>>68751715
Nothing is more obsessively autistic than providing services that steal data.

>> No.68751732

>>68751705
>going through the effort of a subpar mirror when a throwaway takes no email and less time to make than this post

>> No.68751740

>>68751729
yeah god forbid they steal your puzzle output on a throwaway account

>> No.68751745
File: 33 KB, 445x512, 1532172944741.jpg [View same] [iqdb] [saucenao] [google] [report]
68751745

>>68751715
I'm willing to bet there are a lot more of those around here.

>> No.68751752

>>68751729
I forget some people are secret agents with tons of information they need to hide.

>> No.68751765

>>68751396
let md5sum file =
Digest.to_hex (Digest.file file)
;;

>> No.68751775

>>68751396
i dont wanna ;_;

>> No.68751785

rewrote it to use folds, as >>68751349 suggested
comb [] = []
comb (x:xs) = [(x,y) | y <- xs] ++ comb xs

sdiff' x y = foldr (\(a,b) xs -> if a /= b then 1 + xs else xs) 0 $ zip x y
rdiff' x y = foldr (\(a,b) xs -> if a == b then a:xs else xs) [] $ zip x y

sumd (a, b) = if 1 == sdiff' a b then Just $ rdiff' a b else Nothing

mapComb xs = mconcat $ fmap sumd xs

main = do
interact $ show . mapComb . comb . lines

>> No.68751799

I suck
But I solved it

>> No.68751800

Didn't bother trying to stay awake for today's one. Was comfy doing it during lunch. Anyone else's python look like it was written in C? there's got to be a happy medium between C structured code and one-liners which wrap over multiple lines.


from collections import Counter
from itertools import combinations

boxes = []
with open('input2') as f:
for l in f.readlines():
boxes.append(l.strip())

def checksum(box_id, num_to_find):
duplicate_dict = Counter(box_id)
if num_to_find in duplicate_dict.values():
return 1
return 0

twos = 0
threes = 0
for b in boxes:
twos += checksum(b, 2)
threes += checksum(b, 3)

print('Part 1: %i' % (twos*threes))

for a,b in combinations(boxes,2):
current_matches = 0
final_id = ""
for c in range(len(a)):
if ord(a[c]) - ord(b[c]) == 0:
current_matches += 1
if a[c] == b[c]:
final_id += a[c]
if current_matches == len(a)-1:
print('Part 2: ' + final_id)
break

>> No.68751807

Fuck this shit, I'm just a programming noob and have to implement sets because a standard library was apparantly deemed to niggerlicious for HolyC

>> No.68751810

>>68751800
what is that even supposed to mean you sperg

>> No.68751814

>>68750269
Same anon.. same

>> No.68751817

>>68751396
Not sure why that's a problem. Is there any language around that doesn't have a whole pile of libraries available to do this? if not build in?

>> No.68751840

>>68751810
Are you thick as well as fat? I'm talking about the overuse of list comprehensions in python. Post your code

>> No.68751844

>>68751817
Yeah but you could lose a few minutes if you don't know already what library to use

>> No.68751875

>>68750439
Is this Guile? Cool shit, anon.

>> No.68751879

>>68751840
how does me posting my solution make your original statement less of a gorilla nigger statement?
def part_two(input):
for (a, b, ) in combinations(input, 2):
diff = []
for (x, y, ) in zip(a, b):
if x != y:
diff.append(x)

if len(diff) == 1:
return a.replace(diff[0], '')

>> No.68751920

Take bets on which day the first brainlet filter problem is released
I say day 6
>tfw it's spirals again

>> No.68751934 [DELETED] 

#include "stdio.h"

int main()
{
char strings[250][30];
int diff;
for (int i = 0; i < 250; ++i)
gets(strings[i]);

for (int a = 0; a < 249; ++a)
for (int b = a + 1; b < 250; ++b)
{
diff = 0;
for (int i = 0; i < 25; i++)
if (strings[a][i] != strings[b][i])
diff++;
if (diff == 1)
{
for (int i = 0; i < 25; i++)
if (strings[a][i] == strings[b][i])
printf("%c", strings[a][i]);
printf("\n");
return;
}
}
}

>> No.68751936

>>68751920
I wanted to say it could be late too but I can't remember which year/day the challenge with elevator and elements was.

>> No.68751938

>>68751920
I say day 4.

>> No.68751959

>>68751934
>input changes
>solution stops working
Cniles never change

>> No.68751978

>>68751661
Simplest method is run it from terminal and prepend it with the time command. There's doubtless a better way specific to the language/environment you're using. In jupyter, I just add %%time to the beginning of a section:
%%time
from itertools import combinations
for pair in combinations(the_names, 2):
the_diff_index = None
found_2_diffs = False
for char_index in range(len(pair[0])):
if pair[0][char_index] != pair[1][char_index]:
if the_diff_index is not None:
found_2_diffs = True
continue
the_diff_index = char_index
if the_diff_index is not None and not found_2_diffs:
print(pair[0][:the_diff_index] + pair[0][the_diff_index+1:])
break;

bqlporuexkwzyabnmgjqctvfs
CPU times: user 26.3 ms, sys: 1.82 ms, total: 28.1 ms
Wall time: 28.7 ms

>> No.68751983

def contains_same(word, count):
return any([word.count(letter) == count for letter in word])

def task_one(testable):
twos = len([item for item in testable if contains_same(item, 2)])
threes = len([item for item in testable if contains_same(item, 3)])
return twos*threes

def test_difference(word_one, word_two):
similar = [letter for ind, letter in enumerate(word_one) if (word_one[ind] == word_two[ind])]
if len(similar) == (len(word_one) - 1):
return ''.join(similar)
else:
return word_one

def task_two(testable):
for ind, original_word in enumerate(testable):
off_by_one_word = functools.reduce(test_difference, testable[ind:])
if off_by_one_word != original_word :
return off_by_one_word

>> No.68751984
File: 45 KB, 690x621, file.png [View same] [iqdb] [saucenao] [google] [report]
68751984

>>68751920
>>68751936
Nevermind, found it, it was 2016 Day 11.
https://adventofcode.com/2016/day/11

>> No.68751997

>>68751959
I'm too lazy to manually allocate the strings and an idiot who can't count

>> No.68751999

>>68751785
>interact
why haven't I heard about this before

>> No.68752021

>>68751984
plebbit seems to have fucked up and given me a new authentication or some shit because all my old scores are gone
boo!

>> No.68752049

>>68751650
>>68751670
I rewrote the main loop and stopped measuring the distance if it goes over 1. Got it down to ~35ms

>> No.68752059

>>68751047
>well, because then lines that differ in one place will be adjacent to each other, so you only have to compare each string to it's subsequent neighbour, instead of each subsequent string like you did (for (size_t j = i + 1, [...]).

thats not true though

aa
bb
ca

this list is already sorted and the two strings that differ in 1 character are not adjacent to each other

>> No.68752075

>>68751615
Might as well post my meme answer for part 1

extern crate inputparser;


fn main() {
let file = include_str!("../day2.txt");

let checksum = inputparser::parse_lines::<Occurences>(&file).unwrap()
.into_iter()
.inspect(|i| println!("{:?}", i))
.fold(Occurences::default(), |o1, o2| o1 + o2)
.checksum();

println!("{}", checksum);
}

#[derive(Debug)]
struct Occurences
{
two: usize,
three: usize
}

impl Occurences
{
fn checksum(self) -> usize
{
self.two * self.three
}
}

impl Default for Occurences
{
fn default() -> Self
{
Occurences
{
two: 0,
three: 0
}
}
}

impl std::ops::Add for Occurences
{
type Output = Self;

fn add(self, other: Self) -> Self
{
Occurences
{
two: self.two + other.two,
three: self.three + other.three
}
}
}

impl std::str::FromStr for Occurences
{
type Err = std::char::ParseCharError;

fn from_str(s: &str) -> Result<Self, Self::Err>
{
use std::collections::HashMap;
use std::collections::HashSet;

let mut map: HashMap<char, usize> = HashMap::new();

for byte in s.chars()
{
map.entry(byte)
.and_modify(|i| *i += 1)
.or_insert(1);
}
let set: HashSet<_> = map.values().collect();

Ok(Occurences
{
two: set.get(&2).map_or_else(|| 0, |_| 1),
three: set.get(&3).map_or_else(|| 0, |_| 1),
})
}
}

>> No.68752078

#include "stdio.h"

int main()
{
char strings[250][30];
int diff;
for (int i = 0; i < 250; ++i)
gets(strings[i]);

for (int a = 0; a < 249; ++a)
for (int b = a + 1; b < 250; ++b)
{
diff = 0;
for (int i = 0; i < 27; i++)
if (strings[a][i] != strings[b][i])
diff++;
if (diff == 1)
{
printf("%d\n", diff);
printf("%s\n", strings[a]);
printf("%s\n", strings[b]);
for (int i = 0; i < 27; i++)
if (strings[a][i] == strings[b][i])
printf("%c", strings[a][i]);
printf("\n");
return;
}
}
}

Found a mistake in the post that >>68751959
replied to. At least it is 7ms. Damn my C is rusty

>> No.68752081

>>68752059
finally someone noticed. yes, that's true. if you fail the first pass, you should sort with respect to the "backwards order" (e.g, the reversed lines). i think that should work, at least.

>> No.68752102

>>68751999
>>68751785

a bit more aesthetic:
comb [] = []
comb (x:xs) = [(x,y) | y <- xs] ++ comb xs

sumd (a, b) = if 1 == f z then Just $ g z else Nothing
where f = foldr (\(a,b) xs -> if a /= b then 1 + xs else xs) 0
g = foldr (\(a,b) xs -> if a == b then a:xs else xs) []
z = zip a b

main = do
interact $ show . mconcat . fmap sumd . comb . lines

>> No.68752127

>>68752081
>if you fail the first pass, you should sort with respect to the "backwards order" (e.g, the reversed lines). i think that should work, at least.

not true either. imagine the following list:

aaa
abb
aca
bba

reversing each string and sorting the list again will result in exactly the same list

>> No.68752149

>>68752127
blah, you're right. it can't be salvaged it seems

>> No.68752153

Why do I never see D solutions?

>> No.68752164

>>68752153
I forgot that D exists, will try to do 2b with it

>> No.68752176
File: 921 B, 204x26, file.png [View same] [iqdb] [saucenao] [google] [report]
68752176

which one of you fuckers

>> No.68752179

>>68751875
yes it is! I thought I'd use the AOC to get better at scheme

>> No.68752196

>>68752149
>salvaged
copy, shuffle, sort

>> No.68752203

I'm not doing today's part at midnight, it was extremely /not comfy/ and I'd rather focus on building a pretty solution than getting it quickly.

>> No.68752212

>>68752203
keep us updated

>> No.68752227

>>68751477
who else /measuringinmicroseconds/?

>> No.68752239

>>68752102
can you explain this?
f -> counts how many differences between two strings
g -> gets the common characters between two strings
comb -> uses list comprehension to run sumd against every pair of lines in the file
is that right?

>> No.68752252

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>

bool contains_multiple(std::string s, int n) {
std::map<char, int> frequencies;
for (auto c : s) {
frequencies[c]++;
}
for (auto el : frequencies) {
if (el.second == n) {
return true;
}
}
return false;
}

int hamming_distance(std::string s1, std::string s2) {
if (s1.size() != s2.size()) {
return -1;
}
int distance = 0;
for (int i = 0; i < s1.size(); i++) {
if (s1[i] != s2[i]) {
distance++;
}
}
return distance;
}

std::vector<std::string> get_file_contents(const std::string filename) {
std::vector<std::string> lines;
std::string line;
std::ifstream in(filename);
while (std::getline(in, line)) {
lines.push_back(line);
}
return lines;
}

int main() {
auto lines = get_file_contents("input.txt");
std::vector<std::string> twos;
std::vector<std::string> threes;
std::set<std::string> all;
for (auto line : lines) {
if (contains_multiple(line, 2)) {
twos.push_back(line);
all.insert(line);
}
if (contains_multiple(line, 3)) {
threes.push_back(line);
all.insert(line);
}
}

std::cout << twos.size() << "*" << threes.size() << "=" << twos.size() * threes.size() << std::endl;

for (auto iter = all.begin(); iter != std::prev(all.end()); iter++) {
for (auto iter2 = std::next(iter); iter2 != all.end(); iter2++) {
if (hamming_distance(*iter, *iter2) == 1) {
std::cout << *iter << std::endl << *iter2 << std::endl;
}
}
}
}

I haven't written C++ since college and haven't seen auto in my life, is the last part considered an abuse of iterators?

>> No.68752253

>>68752203
>not doing a pajeet tier solution at midnight to try to hit the leaderboard, then a clean solution the next day

>> No.68752270

>>68750393
Pretty elegant m8. Thank you for teaching me new things.

>> No.68752274

>>68752196
i don't understand

>> No.68752320

>>68752253
Even doing that at midnight isn't fun to me. I sleep around 11:30 to 8:30 every day and programming that late isn't fun and fucks my sleep up. I went to bed at 12:30 last night and only woke up half an hour ago, slept for ten hours and I'm still drowsy.

>> No.68752332

>brainlets can't solve part 2 in O(1)

>> No.68752352

>>68752332
I solved in O(-1)

>> No.68752355

>>68752320
Yeah.. I wish they released the new ones during the day.

>> No.68752356
File: 9 KB, 255x198, file.png [View same] [iqdb] [saucenao] [google] [report]
68752356

>brainlets can't solve part 2 in O(0)

>> No.68752359

>>68752239
that's the idea, anon

>> No.68752362

I'm stuck at the first. Site says my answer is too low. But this works for the example and some inputs I created by hand.

inputlist <- fmap lines (readFile filename)
let list1 = multiplefinder inputlist
print list1
let count2 = counter2 list1
let count3 = counter3 list1
print count2
print count3
print(count2*count3)

multiplefinder :: [String] -> [[Int]]
multiplefinder [] = []
multiplefinder (x:xs) = [cleaner(stringfinder x 'a')] ++ multiplefinder xs

stringfinder :: [Char] -> Char -> [Int]
stringfinder x y
|y == 'y' = [length(filter (==y) x)]
|otherwise = [length(filter (==y) x)] ++ stringfinder x (succ y)

cleaner :: [Int] -> [Int]
cleaner [] = []
cleaner (x:xs)
|(x==2)||(x==3) = [x] ++ cleaner xs
|otherwise = cleaner xs

counter2 :: [[Int]] -> Int
counter2 [] = 0
counter2 (x:xs)
|length(filter (==2) x)>0 = 1 + counter2 xs
|otherwise = counter2 xs

counter3 :: [[Int]] -> Int
counter3 [] = 0
counter3 (x:xs)
|length(filter (==3) x)>0 = 1 + counter3 xs
|otherwise = counter3 xs

>> No.68752363

>>68752332
best solution I see is O(14)

>> No.68752378

>>68752270
thanks, I posted a better version here >>68751188

>> No.68752383

>>68752203
>>68752253
>>68752320

try getting up at 6 in the morning and only getting 1300th+ place :C

>> No.68752390

>>68752274
yeah it's a bit more more complex than what I said but if you copy the datas and you shuffle the characters of each line, then sort the lines, then you'd have to be really unlucky to hit the edge case fail.

Of course you'd have to remember each string's original index, and it's a probabilistic algo.

Just a salvage if you you took this route and wanted a solution in time, i guess.

>> No.68752393
File: 56 KB, 645x773, 1526188457277.jpg [View same] [iqdb] [saucenao] [google] [report]
68752393

>brainlets didn't just submitted a random string and got it accepted

>> No.68752405

>>68751188
does this work for this input >>68752127

>> No.68752411

>brainlets don't hack the server and

update parts set solved = true where part = 2 and user = hacker

>> No.68752417 [DELETED] 
File: 106 KB, 1000x1800, 1487819946313.jpg [View same] [iqdb] [saucenao] [google] [report]
68752417

>his has a slider

pffffhahhahahahahhahahh

>> No.68752424
File: 88 KB, 480x480, 560.jpg [View same] [iqdb] [saucenao] [google] [report]
68752424

who's gonna wear the shirt?

>> No.68752427

>>68752411
>brainlets don't just hack the bank and give themselves 10000000 bajilion dollars

>> No.68752430
File: 5 KB, 159x156, 1495947553014.jpg [View same] [iqdb] [saucenao] [google] [report]
68752430

>>68752362
I was ignoring 'z', because it looked all the repetitions from 'a' to 'y'.

>> No.68752433

>>68752405
hmm no it doesn't, well fugg this it works for the puzzle's input

>> No.68752436

>>68752417
his code

>> No.68752449

can somebody pastebin the part 2 of today? i don't want to login with an account

>> No.68752464

>>68752449
no make a throwaway

>> No.68752469

>>68752449
https://pastebin.com/raw/qH6B6qtT

>> No.68752472

>>68752417
kek nice

sliderposting is the new meme

>he sliderposts
shiggy

>> No.68752475

So I looked on perlmonks for a faster Hamming distance sub and I reached 15ms https://www.perlmonks.org/?node_id=500235

>> No.68752477

>>68752449
You can make a reblit account with nothing, just hit next when it asks for an email

>> No.68752495

So since the sorting part seems to not work for all cases, what's the most efficient way to do part two except just bruteforce checking each string vs each string?

>> No.68752507
File: 25 KB, 564x604, aoc2-fs8.png [View same] [iqdb] [saucenao] [google] [report]
68752507

Is this ok or should I an hero?

>> No.68752509

208834-4a1a9383
Anon leaderboard that isn't full like the OP's

>> No.68752510

>>68752430
Cleaner version

main :: IO ()
main = do
filename<-getLine
inputlist <- fmap lines (readFile filename)
let list1 = multiplefinder inputlist
let count2 = counterx list1 2
let count3 = counterx list1 3
print(count2*count3)

multiplefinder :: [String] -> [[Int]]
multiplefinder [] = []
multiplefinder (x:xs) = [stringfinder x 'a'] ++ multiplefinder xs

stringfinder :: [Char] -> Char -> [Int]
stringfinder x y
|y == 'z' = [length(filter (==y) x)]
|otherwise = [length(filter (==y) x)] ++ stringfinder x (succ y)

counterx :: [[Int]] -> Int -> Int
counterx [] y = 0
counterx (x:xs) y
|length(filter (==y) x)>0 = 1 + counterx xs y
|otherwise = counterx xs y

>> No.68752531

>>68752469
uh thank you but i actually need the text which explains the problem for part2 too

here's my solution for part1 in case anyone is bored https://pastebin.com/raw/Yftd5XfT

>> No.68752536
File: 20 KB, 300x300, 1543525037.jpg [View same] [iqdb] [saucenao] [google] [report]
68752536

>his solution for part two isn't linear

>> No.68752538

>>68752509
what's even the point of multiple leaderboards?

>> No.68752540

It's horrible, but it works.
p1 = let pair xs = (contains 2 xs, contains 3 xs)
contains _ [] = 0
contains n xs = if null $ find (== n) xs
then 0
else 1
merge (a, b) (x, y) = (a + x, b + y)
result = foldr merge (0, 0) $ map (pair . map length . group . sort) i1
in fst result * snd result

p2 = let pair (xs, ys) = (xs, ys, countDiff xs ys 0)
countDiff [] _ total = total
countDiff _ [] total = total
countDiff (x:xs) (y:ys) total = countDiff xs ys $ if x == y then total + 1 else total
same (xs, ys, _) = same' xs ys []
same' [] _ acc = acc
same' _ [] acc = acc
same' (x:xs) (y:ys) acc = same' xs ys $ if x == y then acc ++ [x] else acc
in same $ foldr (\[email protected](_, _, x) [email protected](_, _, y) -> if x > y then a else b) ("", "", 0) $ map pair [(x,y) | x <- i1, y <- i1, x /= y]

>> No.68752544

>>68750522
my haskell runs in 19ms, and my sepples in 3ms. I run in a shitty VM tho.

>> No.68752546

>>68752538
One of them is full

>> No.68752555

>>68752546
>>68752509
Just kick people with zero stars

>> No.68752557

>>68752531
https://pastebin.com/raw/rEmxupig

But you should create a fake reddit account.

>> No.68752568

I'll just try to at least finish it this year, and worry about efficiency next year

>> No.68752583

>>68752568
>I'll just try to at least finish it this year
Why? Is it hard? It's the first year that I participate, so I don't know how difficult it is.

>> No.68752587

>>68752568
Being asleep when the new problem gets posted is a great excuse to not care about leaderboards

>> No.68752594

>>68752546
Sure, but I mean, you're not comparing yourself with all the rest of this thread anymore, so why bother?

>> No.68752615

>>68752495
i was thinking a good hash function that maps similar strings to near values

>> No.68752630

>>68752495
A guy over on plebbit has a nice tree-based solution, it's imo too much to actually implement for a meme coding challenge. There's also a bunch of things you can do if you don't care about memory.

>> No.68752634
File: 5 KB, 203x203, 1527896992775.jpg [View same] [iqdb] [saucenao] [google] [report]
68752634

>>68752557
There's no such thing as a fake reddit account anon. Once you're in, they got you by the botnet balls.

>> No.68752641

>>68752634
And? Where is the problem in having a reddit account?

>> No.68752642

>>68752630
Link?

>> No.68752643

>>68752594

Fairly sure half of this board is already there with the other half from /tech/.

>> No.68752663

>>68752642
literally the first thing on the subreddit
/r/adventofcode

>> No.68752715
File: 84 KB, 800x800, 1522839409369.png [View same] [iqdb] [saucenao] [google] [report]
68752715

enjoy my brainlet solution, not even gonna try and make it look better. getting more comfortable reading the rust documents at least.

use std::fs;
use std::collections::HashMap;

fn main() {
let contents = fs::read_to_string("input").expect("error reading file");
let mut h = HashMap::new();
let (mut two, mut three) = (0, 0);
let mut p2 = Vec::new();

// p2
for line in contents.lines() {
h.clear();
for ch in line.chars() {
let c = h.entry(ch).or_insert(0);
*c += 1;
}

let (mut btwo, mut bthree) = (true, true); // whatever
for val in h.values() {
if *val == 2 && btwo {
two += 1;
btwo = false;
p2.insert(0, line);
} else if *val == 3 && bthree {
three += 1;
bthree = false;
p2.insert(0, line);
}
}
}

// p2
let mut matches = 0;
let mut chrs = String::new();
for line in p2.iter() {
for lone in p2.iter() {
let mut lmatches = 0;
let mut lchrs = String::new();
if line == lone {
break
} else {
let test = line.chars().zip(lone.chars());
for (ch1, ch2) in test {
if ch1 == ch2 {
lmatches += 1;
lchrs.push(ch1);
}
}
}
if lmatches > matches {
matches = lmatches;
chrs = lchrs;
}
}
}

println!("part 2 = {}", chrs);
println!("part 1 = {}", two * three); // p1
}

>> No.68752718
File: 82 KB, 531x603, day2.png [View same] [iqdb] [saucenao] [google] [report]
68752718

I don't know whats wrong pls halp

>> No.68752722

>>68752715
the rust documentation is the only good part of the language

>> No.68752731

>>68752718
>whats wrong
C

>> No.68752743
File: 7 KB, 549x169, aoc2_2-fs8.png [View same] [iqdb] [saucenao] [google] [report]
68752743

>>68752507
I changed part 2 to (hopefully) less brainlet

>> No.68752748

In Python, what is this called?
[x for x, y in zip(a,b) if x == y]

I understand what it's doing, but I don't know what to search for to see more on the syntax.

>> No.68752752

>>68752748
list comprehension maybe

>> No.68752753

>>68752718
the fact that you've both written it in German and not used proper spacing.

What is "ent" short for? I know what it's doing I'm just curious what the word is.

>> No.68752754

>>68750561
My nigga

>> No.68752759

>>68752748
List comprehension

>> No.68752765

>>68752718
You are not programming in english. That's the first problem.

>> No.68752778

>>68752753
another german here, my guess in "enthält" meaning "contains"

>> No.68752784

>>68752778
s/in/is/

>> No.68752786

>>68752718
Don't you need to read 33 characters?

>> No.68752788

>>68752765
That's why I only use one letter var, nobody know in which language I am coding.

>> No.68752790

>>68752557
thanks, here is my terrible solution, i have to go now. thanks, tomorrow i will make an account https://pastebin.com/5ZCTY1RJ

>> No.68752798

>>68752718
are you larping? none of my german coworkers write variable names like that

>> No.68752811

>>68752788
That's even worse

>> No.68752821

>>68752788
One letter vars are too much voodoo for this gay world.

>> No.68752822

>>68752449
I made my python one 10x faster by using a set and for each string, putting all strings made by replacing one character with a space. Then the first duplicate is the answer:
def task2(names):
found = set()
for name in names:
for i in range(len(name)):
test = name[:i] + ' ' + name[i+1:]
if test in found:
return test.replace(" ", "")
found.add(test)
return None
print(task2(the_names))

It's actually shorter too

>> No.68752845
File: 129 KB, 690x621, bl.png [View same] [iqdb] [saucenao] [google] [report]
68752845

>>68751984

>> No.68752879
File: 389 KB, 800x602, aoc2_2.png [View same] [iqdb] [saucenao] [google] [report]
68752879

here's the calendar image from the thread last night

>> No.68752904

post utils
(define-module (aoc utils))
(use-modules (ice-9 rdelim))
(use-modules (statprof))

(define (read-file f)
(let ((s (read-line f 'trim)))
(if (eof-object? s) '()
(cons s (read-file f)))))

(define-public (file->list fn) (read-file (open-input-file fn)))

(define-public (report p1 p2)
(statprof-start)
(format #t "p1: ~a\n" (p1))
(format #t "p2: ~a\n" (p2))
(statprof-stop)
(format #t "execution time: ~a sec\n" (statprof-accumulated-time)))

(define-public (cl f . x) (lambda () (apply f x)))

>> No.68752910

>>68752879
kek nice

>> No.68752922

>>68750542
based

>> No.68752946

>not solving the problem by hand

>> No.68752947
File: 70 KB, 641x470, 1542493468510.jpg [View same] [iqdb] [saucenao] [google] [report]
68752947

>>68751785
>>68752102
god i love haskell

>> No.68752983

>>68752879 see >>68751416

anyone have day 1 calendar image?

>> No.68752998
File: 565 KB, 10000x10000, 1536474757614.png [View same] [iqdb] [saucenao] [google] [report]
68752998

>>68752983

>> No.68753000

NEW THREAD:
>>68752995
>>68752995
>>68752995

>> No.68753025

>>68752718
>whats wrong
Literally this >>68752731
90% of your code will just be managing memory as can be seen with your constantly looping through your arrays to reset values. You also use magic numbers to predefine the sizes of all your arrays but what if you didn't have the luxury of knowing how many lines in the input file there is going to be? or how many letters in each box ID?

Also your C style is horrible. Please use whitespace and brackets even for one line if statements if you actually want people to read your code.

You're checking array[i+1] != '\n' I don't believe this check ever actually returns false for the last line in the input file (by default)

Other than that the code does look like it should work. You count the occurrence of each letter in the string and then check to see if any letters occur exactly twice or three times. You correctly don't double count if a string has two letters that both show up exactly twice and the like. Try stepping through with a debugger to see whats going wrong.

>> No.68753081

>>68752879
good post

>> No.68753281

>>68751188
Question: it looks like after you sort the input, you just take the difference in consecutive strings... would it still work if you had:

ABC
BBB
CBC

>> No.68753803
File: 16 KB, 326x326, 7b9.jpg [View same] [iqdb] [saucenao] [google] [report]
68753803

>Because you have guessed incorrectly 9 times on this puzzle, please wait 10 minutes before trying again.
guess I'm just brain dead

>> No.68753870

>>68751984
The elevator problem was a chore to solve even when you know how to do it.

>> No.68753902
File: 53 KB, 728x380, 1514491744737.jpg [View same] [iqdb] [saucenao] [google] [report]
68753902

>puzzle forces you do do some thinking
Nothing wrong with that

>> No.68753921

who /sepples/ here?
int part1(std::vector<std::string> &data) {
int dubs = 0, trip = 0;
for (std::string &line : data) {
int cnt[26]{0};
std::for_each(line.begin(), line.end(),
[&cnt](char &c) { ++cnt[c - 'a']; });
dubs += std::any_of(std::begin(cnt), std::end(cnt),
[](int n) { return n == 2; })
? 1
: 0;
trip += std::any_of(std::begin(cnt), std::end(cnt),
[](int n) { return n == 3; })
? 1
: 0;
}
return dubs * trip;
}

>> No.68755442

// O(n^2)
func part2(lines []string) string {
for k, l1 := range lines {
for _, l2 := range lines[k+1:] {
numDiffs := 0
lastPos := 0

for i := 0; i < len(l1); i++ {
if l1[i] != l2[i] {
numDiffs++
lastPos = i

if numDiffs > 1 {
break
}
}
}

if numDiffs == 1 {
return strings.Join([]string{l1[:lastPos], l1[lastPos+1:]}, "")
}
}
}

panic("Not found")
}

// O(nm)
func part2Map(lines []string) string {
seen := make(map[string]bool)
for _, line := range lines {
for i := 0; i < len(line); i++ {
str := strings.Join([]string{line[:i], line[i+1:]}, "_")
_, present := seen[str]
if present {
return strings.Join([]string{line[:i], line[i+1:]}, "")
}
seen[str] = true
}
}

panic("Not found")
}

Part 2: umdryabviapkozistwcnihjqx
223.276µs
Part 2 (map): umdryabviapkozistwcnihjqx
477.56µs

They should give you bigger inputs...

>>
Name (leave empty)
Comment (leave empty)
Name
E-mail
Subject
Comment
Password [?]Password used for file deletion.
Captcha
Action