User avatar
bensimmo
Posts: 5815
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Advent 2022

Sat Dec 03, 2022 11:59 am

Already behind.
Day2

Python (3.10+) because I've not used Match/Case before in Python.
Part2, but just switch the addition for Part1.

Code: Select all

import csv

ROCK = 1
PAPER = 2
SCISSOR = 3
WIN = 6
DRAW = 3
LOST = 0

total = 0

with open('input.txt', newline='\n') as f:
    reader = csv.reader(f)
    
    for row in reader:
        match row:
            case ['A X']:
                total += (SCISSOR + LOST)
            case ['A Y']:
                total += (ROCK + DRAW)
            case ['A Z']:
                total += (PAPER + WIN)
            case ['B X']:
                total += (ROCK + LOST)
            case ['B Y']:
                total += (PAPER + DRAW)
            case ['B Z']:
                total += (SCISSOR + WIN)
            case ['C X']:
                total += (PAPER + LOST)
            case ['C Y']:
                total += (SCISSOR + DRAW)
            case ['C Z']:
                total += (ROCK + WIN)
            case other:
                print("error")

print(f"Score = {total}")
I wonder if everyone's puzzle had the same answer.
I guess not as my day2 are different 12740 & 11980

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Sat Dec 03, 2022 2:48 pm

day3 translated for pshell

Code: Select all

#pragma uchar

int toprio(char c) { return c > 'Z' ? c - 'a' + 1 : c - 'A' + 27; }

int part1(char* line) {
    char* cp = line;
    while (*cp)
        ++cp;
    int n = cp - line;
    cp = line;
    int i, j, h = n / 2;
    for (i = 0; i < h; ++i)
        for (j = h; j < n; ++j)
            if (line[i] == line[j])
                return toprio(line[i]);
}

int part2(char* l1, char* l2, char* l3) {
    char count1[53], count2[53], count3[53];
    memset(count1, 0, 53);
    memset(count2, 0, 53);
    memset(count3, 0, 53);
    char* cp = l1;
    while (*cp)
        count1[toprio(*cp++)] = 1;
    cp = l2;
    while (*cp)
        count2[toprio(*cp++)] = 1;
    cp = l3;
    while (*cp)
        count3[toprio(*cp++)] = 1;
    int i;
    for (i = 1; i < 53; ++i)
        if (count1[i] && count2[i] && count3[i])
            return i + 1;
    return 0;
}

char* txt;

void nextline() {
    while ((*txt != '\n') && *txt)
        ++txt;
    if (*txt == '\n') {
        *txt = 0;
        ++txt;
    }
}

char *l1, *l2, *l3;

void main() {
    int start = time_us_32(), f = open("day3.txt", O_RDONLY), n = lseek(f, 0, SEEK_END);
    lseek(f, 0, SEEK_SET);
    txt = (char*)malloc(n + 1);
    read(f, txt, n);
    txt[n] = 0;
    int prio = 0, badges = 0;
    while (*txt) {
        l1 = txt;
        nextline();
        l2 = txt;
        nextline();
        l3 = txt;
        nextline();
        prio += part1(l1) + part1(l2) + part1(l3);
        badges += part2(l1, l2, l3);
    }
    printf("--- Day 3: Rucksack Reorganization ---\n"
           "Part 1 - %d\nPart 2 - %d\nElapsed - %f ms.\n",
           prio, badges, (float)(time_us_32() - start) / 1000.0);
}
Last edited by lurk101 on Sun Dec 04, 2022 4:25 am, edited 1 time in total.
History doesn’t repeat itself, it rarely even rhymes.

User avatar
bensimmo
Posts: 5815
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Advent 2022

Sat Dec 03, 2022 3:13 pm

Python again

Part1

Code: Select all

total = 0

def get_priority(letter):
    if letter.islower():
        value = ord(letter) - 97 + 1
    elif letter.isupper():
        value = ord(letter) - 65 + 27
    else:
        value = "E"
    return value


with open('input.txt', newline='\n') as file:
    
    for row in file:
        row = row.rstrip("\r\n")
        
        half_row=int(len(row)/2)
        compartment1 = set(row[:half_row])
        compartment2 = set(row[half_row:])     
        
        for item in compartment1:
            if item in compartment2:
                total += get_priority(item)

print(f"sum of priorities = {total}")
Part2

Code: Select all

total = 0

def get_priority(letter):
    if letter.islower():
        value = ord(letter) - 97 + 1
    else:
        value = ord(letter) - 65 + 27
    return value

with open('input.txt', newline='\n') as file:
    elves = [row.strip("\r\n") for row in file.readlines()]
    
for elf in range(0, len(elves), 3):  
    common_item = []
    group_elf = (set(elves[elf]) , set(elves[elf+1]), set(elves[elf+2]))
    
    for item in group_elf[1]:
        if item in group_elf[0]:
            common_item.append(item)
    
    for item in group_elf[2]:
        if item in common_item:
            total += get_priority(item)

print(f"sum of priorities = {total}")

User avatar
RogerW
Posts: 364
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

Re: Advent 2022

Sat Dec 03, 2022 3:50 pm

A variation on day 3 in c++

Code: Select all

#include <iostream>
#include <fstream>
#include <cstring>

int main()
{
    std::ifstream file("/home/roger/Advent22/Dec3/data.txt");
    char a[100];
    char* b;
    char r;
    int score = 0;
    // Part 1
    while(file)
    {
        file.getline(a,sizeof(a));
        int l = std::strlen(a)/2;
        b = a + l;
        for(int i = 0; i < l; i++)
        {
            r = a[i];
            for(int j = 0; j < l ; j++)
            {
                if(b[j] == r)
                {
                    i= l;
                    j = l;

                    if( r < 'a')
                        score += r - 'A' + 27;
                    else
                        score += r - 'a' + 1;
                }
            }
        }

    }
    std::cout << "Part 1 " << score << "\n";

    // rewind
    file.clear();
    file.seekg(0);
    //part 2
    char c[3][100];
    int len[3];
    score = 0;
    while(file)
    {
        for(int i = 0; i < 3; i++)
        {
            file.getline(c[i],100);
            len[i] = std::strlen(c[i]);
        }
        for(int i = 0; i < len[0]; i++)
        {
            r = c[0][i];
            for(int j = 0; j < len[1] ; j++)
            {
                if(c[1][j] == r)
                {
                    for(int k = 0; k < len[2] ; k++)
                    {
                        if(c[2][k] == r)
                        {
                            i = 100;
                            j = 100;
                            k = 100;

                            if( r < 'a')
                                score += r - 'A' + 27;
                            else
                                score += r - 'a' + 1;
                        }
                    }
                }
            }
        }
    }
    std::cout << "Part 2 " << score << "\n";
    file.close();

    return 0;
}

ejolson
Posts: 10539
Joined: Tue Mar 18, 2014 11:47 am

Re: Advent 2022

Sat Dec 03, 2022 5:36 pm

RogerW wrote:
Sat Dec 03, 2022 3:50 pm
A variation on day 3 in c++

Code: Select all

#include <iostream>
#include <fstream>
#include <cstring>

int main()
{
    std::ifstream file("/home/roger/Advent22/Dec3/data.txt");
    char a[100];
    char* b;
    char r;
    int score = 0;
    // Part 1
    while(file)
    {
        file.getline(a,sizeof(a));
        int l = std::strlen(a)/2;
        b = a + l;
        for(int i = 0; i < l; i++)
        {
            r = a[i];
            for(int j = 0; j < l ; j++)
            {
                if(b[j] == r)
                {
                    i= l;
                    j = l;

                    if( r < 'a')
                        score += r - 'A' + 27;
                    else
                        score += r - 'a' + 1;
                }
            }
        }

    }
    std::cout << "Part 1 " << score << "\n";

    // rewind
    file.clear();
    file.seekg(0);
    //part 2
    char c[3][100];
    int len[3];
    score = 0;
    while(file)
    {
        for(int i = 0; i < 3; i++)
        {
            file.getline(c[i],100);
            len[i] = std::strlen(c[i]);
        }
        for(int i = 0; i < len[0]; i++)
        {
            r = c[0][i];
            for(int j = 0; j < len[1] ; j++)
            {
                if(c[1][j] == r)
                {
                    for(int k = 0; k < len[2] ; k++)
                    {
                        if(c[2][k] == r)
                        {
                            i = 100;
                            j = 100;
                            k = 100;

                            if( r < 'a')
                                score += r - 'A' + 27;
                            else
                                score += r - 'a' + 1;
                        }
                    }
                }
            }
        }
    }
    std::cout << "Part 2 " << score << "\n";
    file.close();

    return 0;
}
Welcome to the party! It's amazing how many different ways there are to solve the same puzzle in just one language.
Last edited by ejolson on Sun Dec 04, 2022 2:54 pm, edited 1 time in total.

ejolson
Posts: 10539
Joined: Tue Mar 18, 2014 11:47 am

Re: Advent 2022

Sat Dec 03, 2022 5:39 pm

bensimmo wrote:
Sat Dec 03, 2022 11:59 am
Already behind.
Day2

Python (3.10+) because I've not used Match/Case before in Python.
Part2, but just switch the addition for Part1.

Code: Select all

import csv

ROCK = 1
PAPER = 2
SCISSOR = 3
WIN = 6
DRAW = 3
LOST = 0

total = 0

with open('input.txt', newline='\n') as f:
    reader = csv.reader(f)
    
    for row in reader:
        match row:
            case ['A X']:
                total += (SCISSOR + LOST)
            case ['A Y']:
                total += (ROCK + DRAW)
            case ['A Z']:
                total += (PAPER + WIN)
            case ['B X']:
                total += (ROCK + LOST)
            case ['B Y']:
                total += (PAPER + DRAW)
            case ['B Z']:
                total += (SCISSOR + WIN)
            case ['C X']:
                total += (PAPER + LOST)
            case ['C Y']:
                total += (SCISSOR + DRAW)
            case ['C Z']:
                total += (ROCK + WIN)
            case other:
                print("error")

print(f"Score = {total}")
I wonder if everyone's puzzle had the same answer.
I guess not as my day2 are different 12740 & 11980
That's good to know. I was surprised to get the same answer as lurk101 and wondered whether something had gone wrong with the website for that puzzle.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Sun Dec 04, 2022 5:42 am

day4

Code: Select all

#define title "--- Day 4: Camp Cleanup ---"
#include <chrono>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;
using namespace chrono;

int part1(int l1, int h1, int l2, int h2) {
    if (l1 < l2)
        return h1 >= h2 ? 1 : 0;
    if (l2 < l1)
        return h2 >= h1 ? 1 : 0;
    return 1;
}

int part2(int l1, int h1, int l2, int h2) {
    if (l1 < l2)
        return h1 < l2 ? 0 : 1;
    if (l2 < l1)
        return h2 < l1 ? 0 : 1;
    return 1;
}

int main() {
    auto start = high_resolution_clock::now();
    ifstream f("day4.txt");
    string l;
    int contained = 0, overlapped = 0;
    while (getline(f, l)) {
        int l1, h1, l2, h2;
        (void)sscanf(l.c_str(), "%d-%d,%d-%d", &l1, &h1, &l2, &h2);
        contained += part1(l1, h1, l2, h2);
        overlapped += part2(l1, h1, l2, h2);
    }
    cout << title << endl
        << "Part 1 - " << contained << endl
        << "Part 2 - " << overlapped << endl
        << "Elapsed - "
        << duration_cast<microseconds>(high_resolution_clock::now() - start).count() / 1e3
        << " ms." << endl;
}

Code: Select all

pi@pi4b:~/AoC-2022-cplusplus/day4 $ taskset -c 3 ./a.out 
--- Day 4: Camp Cleanup ---
Part 1 - 605
Part 2 - 914
Elapsed - 0.902 ms.

Code: Select all

rock@rock-5b:~/AoC-2022-cplusplus/day4$ taskset -c 7 ./a.out 
--- Day 4: Camp Cleanup ---
Part 1 - 605
Part 2 - 914
Elapsed - 0.537 ms.
Last edited by lurk101 on Sun Dec 04, 2022 6:01 am, edited 1 time in total.
History doesn’t repeat itself, it rarely even rhymes.

ejolson
Posts: 10539
Joined: Tue Mar 18, 2014 11:47 am

Re: Advent 2022

Sun Dec 04, 2022 5:43 am

Another day it's another puzzle and a Pshell solution.

Code: Select all

/aofcode/2022/: cc day04.c

Advent of Code 2022 Day 4 Camp Cleanup

Part 1 The subset sum is 534
Part 2 The intersection sum is 841

Total execution time 0.0456240 seconds.
For reference the code is

Code: Select all

/*  Advent of Code 2022 Day 4 Camp Cleanup
    Written December 2022 by Eric Olson */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#ifdef LINUX
#include <time.h>
static struct timespec tic_start;
void tic(){
    clock_gettime(CLOCK_MONOTONIC_RAW,&tic_start);
}
float toc(){
    struct timespec tic_stop;
    clock_gettime(CLOCK_MONOTONIC_RAW,&tic_stop);
    float sec=tic_stop.tv_sec-tic_start.tv_sec;
    return sec+(tic_stop.tv_nsec-tic_start.tv_nsec)*1.0e-9;
}
#endif

#ifndef LINUX
int tstart;
void tic(){
    tstart=time_us_32();
}
float toc(){
    return (float)(time_us_32()-tstart)/1000000.0;
}
#endif

#define BUFSZ 128
#define UGBSZ 32

struct fpspec {
    int fd,a,b,m;
    char c[BUFSZ],u[UGBSZ];
    struct fpspec *r;
};

struct fpspec rroot;
struct fpspec *fproot;

char *psindex(char *s,int c){
    do {
        if(*s==c) return s;
    } while(*++s);
    return 0;
}

char *fierror;
struct fpspec *fpopen(char *fn,char *mode){
    int m=0;
    if(psindex(mode,'r')) m|=1;
    if(psindex(mode,'w')) m|=2;
    if(!m){
        printf("Invalid mode %s to open file %s!\n",mode,fn);
        exit(1);
    }
    switch(--m){
case 0:
        m=O_RDONLY; break;
case 1:
        m=O_WRONLY; break;
case 2:
        m=O_RDWR; break;
    }
    int fd=open(fn,m);
    if(fd<0){
        printf("Unable to open %s for mode %s!\n",fn,mode);
        exit(1);
    }
    struct fpspec *fp,*fpo;
    for(fp=&rroot;fp;fpo=fp,fp=fp->r){
        if(fp->fd==0||fp->fd==fd){
            fp->fd=fd;
            fp->a=0; fp->b=0; fp->m=0;
            return fp;
        }
    }
    fp=(struct fpspec *)malloc(sizeof(struct fpspec));
    if(!fp){
        printf("Can't allocate memory for fpspec!\n");
        exit(1);
    }
    fpo->r=fp;
    fp->fd=fd;
    fp->a=0; fp->b=0; fp->m=0;
    fp->r=0;
    return fp;
}

int fpgetc(struct fpspec *fp){
    if(fp->m) return fp->u[--fp->m];
    if(fp->a>=fp->b){
        if(fp->fd<0) return -1;
        fp->a=0;
        fp->b=read(fp->fd,fp->c,BUFSZ);
    }
    if(fp->a<fp->b){
        return fp->c[fp->a++];
    }
    return -1;
}

char *fpgets(char *s,int n,struct fpspec *fp){
    int i=0;
    --n;
    for(i=0;i<n;i++){
        int c=fpgetc(fp);
        if(c<=0||c=='\n'||c=='\r'){
            if(c<=0&&!i) return 0;
            s[i]=0;
            return s;
        }
        s[i]=c;
    }
    s[n]=0;
    return s;
}

void fpugetc(int c,struct fpspec *fp){
    if(fp->a>0) fp->c[--fp->a]=c;
    else if(fp->m<UGBSZ) fp->u[fp->m++]=c;
    else {
        printf("Unget buffer overflow fpugetc!\n");
        exit(1);
    }
}

int fpputc(int c,struct fpspec *fp){
    if(fp->fd<0) return -1;
    char b=c;
    return write(fp->fd,&b,1);
}

int fpclose(struct fpspec *fp){
    return close(fp->fd);
}

struct interval {
    int a,b;
};

int mydigit(int c){
    if(c>='0'&&c<='9') return c-'0';
    return -1;
}

char *getint(int *n,char *s){
    *n=0;
    for(;;){
        int d=mydigit(*s);
        if(d<0) return s;
        *n=*n*10+d;
        ++s;
    }
}

char *parserange(struct interval *I0,char *s){
    s=getint(&I0->a,s);
    if(*s=='-') ++s;
    else {
        printf("Parse range missing - at %s\n",s);
        exit(1);
    }
    s=getint(&I0->b,s);
    return s;
}

char subset(struct interval *I0,struct interval *I1){
    if(I0->a<I1->a) return 0;
    if(I0->b>I1->b) return 0;
    return 1;
}

char meet(struct interval *I0,struct interval *I1){
    if(I0->a>I1->b) return 0;
    if(I0->b<I1->a) return 0;
    return 1;
}

void dowork(){
    char *fn="day04.txt";
    struct fpspec *fp=fpopen(fn,"r");
    if(!fp){
        printf("Unable to open %s for reading!\n",fn);
        exit(1);
    }
    char *s,buf[128];
    struct interval I0,I1;
    int rsum1=0,rsum2=0;
    for(;;){
        s=fpgets(buf,128,fp);
        if(!s) break;
        s=parserange(&I0,s);
        if(*s==',') ++s;
        else {
            printf("Pair specifier missing , at %s\n",s);
            exit(1);
        }
        s=parserange(&I1,s);
        if(subset(&I0,&I1)||subset(&I1,&I0)) ++rsum1;
        if(meet(&I1,&I0)) ++rsum2;
    }
    printf("Part 1 The subset sum is %d\n",rsum1);
    printf("Part 2 The intersection sum is %d\n",rsum2);
}

int main(){
    printf("Advent of Code 2022 Day 4 Camp Cleanup\n\n");
    tic();
    dowork();
    printf("\nTotal execution time %g seconds.\n",toc());
    return 0;
}
This time I developed the code on a Pi Zero and then transferred it to the Pico. No changes were needed for Pshell. Simply typing cc day04.c is sure easier than creating a CMakeLists.txt file and running cmake followed by make. If the dog developer weren't asleep tails would certainly be wagging.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Sun Dec 04, 2022 7:15 am

day4 pshell translation

Code: Select all

int part1(int l1, int h1, int l2, int h2) {
    if (l1 < l2)
        return h1 >= h2 ? 1 : 0;
    if (l2 < l1)
        return h2 >= h1 ? 1 : 0;
    return 1;
}

int part2(int l1, int h1, int l2, int h2) {
    if (l1 < l2)
        return h1 < l2 ? 0 : 1;
    if (l2 < l1)
        return h2 < l1 ? 0 : 1;
    return 1;
}

char* txt;

int number() {
    int n = strtol(txt, &txt, 10);
    if (txt)
        ++txt;
    return n;
}

void main() {
    int start = time_us_32(), f = open("day4.txt", O_RDONLY), n = lseek(f, 0, SEEK_END);
    lseek(f, 0, SEEK_SET);
    txt = (char*)malloc(n + 1);
    read(f, txt, n);
    txt[n] = 0;
    int contained = 0, overlapped = 0;
    while (*txt) {
        int l1 = number(), h1 = number(), l2 = number(), h2 = number();
        contained += part1(l1, h1, l2, h2);
        overlapped += part2(l1, h1, l2, h2);
    }
    printf("--- Day 4: Camp Cleanup ---\nPart 1 - %d\nPart 2 - %d\nElapsed - %f\n",
        contained, overlapped, (float)(time_us_32() - start) / 1000.0);
}
They usually get harder after day4

Code: Select all

/AoC/day4/: cc day4

--- Day 4: Camp Cleanup ---
Part 1 - 605
Part 2 - 914
Elapsed - 15.693000
History doesn’t repeat itself, it rarely even rhymes.

User avatar
RogerW
Posts: 364
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

Re: Advent 2022

Sun Dec 04, 2022 10:28 am

Finally got my head round day 2
It is a bit long winded - I need to remember how to pass a 2 dimensional array to a function.

Code: Select all

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream file("/home/roger/Advent22/Dec2/data.txt");
    char b[6];
    int total = 0;
    //                  r  p  s
    int scores[3][3] = {4, 8, 3,    // rock
                        1, 5, 9,    // paper
                        7, 2, 6};   // scissors
    while(file)
    {
        file.getline(b,sizeof(b));
        if(b[0] == '\0')
            break;

        total += scores[b[0] - 'A'][b[2] - 'X'];
    }

    std::cout << "Part 1 " << total << "\n";

    file.clear();
    file.seekg(0);
    total = 0;

    //                   l  d  w
    int scores2[3][3] = {3, 4, 8,
                         1, 5, 9,
                         2, 6, 7};
    while(file)
    {
        file.getline(b,sizeof(b));
        if(b[0] == '\0')
            break;

        total += scores2[b[0] - 'A'][b[2] - 'X'];
    }

    std::cout << "Part 2 " << total << "\n";
    file.close();

    return 0;
}

User avatar
bensimmo
Posts: 5815
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Advent 2022

Sun Dec 04, 2022 11:51 am

Simple Python Day4

Code: Select all

contains_total = 0
overlap_total = 0

with open('input.txt', newline='\n') as file:
    elves = [row.strip("\r\n") for row in file.readlines()]

for elf in elves:
    elf_pair = elf.replace("-",",")
    elf_pair = elf_pair.split(",")

    if   (int(elf_pair[0]) >= int(elf_pair[2])) and (int(elf_pair[1]) <= int(elf_pair[3])):
        contains_total += 1

    elif (int(elf_pair[0]) <= int(elf_pair[2])) and (int(elf_pair[1]) >= int(elf_pair[3])):
        contains_total += 1

    elif (int(elf_pair[1]) <  int(elf_pair[2])) or  (int(elf_pair[3]) <  int(elf_pair[0])):
        pass # No overlap
    
    else:
        overlap_total += 1
        
print(f"Fully contains = {contains_total}")
print(f"Any Overlap = {contains_total + overlap_total}")

ejolson
Posts: 10539
Joined: Tue Mar 18, 2014 11:47 am

Re: Advent 2022

Sun Dec 04, 2022 6:54 pm

RogerW wrote:
Sun Dec 04, 2022 10:28 am
Finally got my head round day 2
It is a bit long winded - I need to remember how to pass a 2 dimensional array to a function.
I like the way the comments are formatted for scores and scores2. That makes it a lot easier to understand what's going on.

Did you get the same day 2 output as lurk101 and I in

viewtopic.php?p=2059145#p2059145

Given over 100 000 people are participating

Code: Select all

 4   78769  2338  *******************
 3  105679  5794  **************************
 2  139786  6301  *********************************
 1  174045  6723  *****************************************
https://adventofcode.com/2022/stats

I suspect the chances are pretty high some people get the same puzzles or at least output. Finding two identical solutions in this thread was surprising--three identical solutions would be even more so.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Sun Dec 04, 2022 7:20 pm

ejolson wrote:
Sun Dec 04, 2022 6:54 pm
I suspect the chances are pretty high some people get the same puzzles or at least output. Finding two identical solutions in this thread was surprising--three identical solutions would be even more so.
There must be a finite number of data sets per puzzle. Could it be that you're assigned a data set index that you keep throughout the 25 days?
History doesn’t repeat itself, it rarely even rhymes.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Mon Dec 05, 2022 5:53 am

day5

Code: Select all

#define title "--- 5: Supply Stacks ---"
#include <chrono>
#include <fstream>
#include <iostream>
#include <string>
#include <list>
#include <algorithm>

using namespace std;
using namespace chrono;

list<char> stack[10], stack2[10];

int main() {
    auto start = high_resolution_clock::now();
    ifstream f("day5.txt");
    string l;
    while (getline(f, l)) {
        if (l[1] == '1') {
            getline(f, l);
            break;
        }
        int len = l.length();
        for (int i = 1; i < 10; ++i) {
            if (((i * 4) - 3) >= len)
                break;
            char c = l[(i * 4) - 3];
            if (c != ' ')
                stack[i].push_front(c);
        }
    }
    for (int i = 1; i < 10; ++i)
        stack2[i] = stack[i];
    int n, from, to;
    string s;
    while (f >> s >> n >> s >> from >> s >> to) {
        for (int j = 0; j < n; ++j) {
            stack[to].push_back(stack[from].back());
            stack[from].pop_back();
        }
        list<char> temp;
        for (int j = 0; j < n; ++j) {
            temp.push_back(stack2[from].back());
            stack2[from].pop_back();
        }
        while (temp.size()) {
            stack2[to].push_back(temp.back());
            temp.pop_back();
        }
    }
    cout << title << endl << "Part 1 - ";
    for (int i = 1; i < 10; i++)
        if (stack[i].size())
            cout << stack[i].back();
    cout << endl << "Part 2 - ";
    for (int i = 1; i < 10; i++)
        if (stack2[i].size())
            cout << stack2[i].back();
    cout << endl << "Elapsed - "
        << duration_cast<microseconds>(high_resolution_clock::now() - start).count() / 1e3
        << " ms." << endl;
}

Code: Select all

--- 5: Supply Stacks ---
Part 1 - VGBBJCRMN
Part 2 - LBBVJBRMH
Elapsed - 5.801 ms.
Last edited by lurk101 on Mon Dec 05, 2022 1:27 pm, edited 1 time in total.
History doesn’t repeat itself, it rarely even rhymes.

User avatar
RogerW
Posts: 364
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

Re: Advent 2022

Mon Dec 05, 2022 9:53 am

ejolson wrote:
Sun Dec 04, 2022 6:54 pm
Did you get the same day 2 output as lurk101 and I i
Not the same I am afraid. Part 1 14069, Part 2 12411

User avatar
RogerW
Posts: 364
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

Re: Advent 2022

Mon Dec 05, 2022 2:27 pm

My variation on day 5. I did not get the same answers as lurk101

Code: Select all

#include <iostream>
#include <fstream>
#include <stack>
#include <string>

void loadstacks(std::ifstream& file,std::stack<char>* stacks)
{
    // we need to load stacks from the bottom up
    // my data only needed 8 lines
    char lines[16][40];
    int cols[9] = {1,5,9,13,17,21,25,29,33};
    int next = 0;
    while(true)
    {
        file.getline(lines[next],sizeof(lines[next]));
        //std::cout << lines[next] << "\n";

        if(lines[next][1] == '1')
        {
            next--;
            break;
        }
        next++;
    }

    while(next >= 0)
    {
        for(int i = 0; i < 9 ;i++)
            if(lines[next][cols[i]] != ' ')
                stacks[i].push(lines[next][cols[i]]);
        next--;
    }
}
std::string top(std::stack<char>* stacks)
{
    std::string s;
    for(int i = 0; i < 9 ; i++)
        s += stacks[i].top();

    return s;
}

void move(std::stack<char>* stacks,int mov,int from,int to)
{
    // move crates
    for(int i = 0; i < mov; i++)
    {
        stacks[to].push(stacks[from].top());
        stacks[from].pop();
    }
}

void move2(std::stack<char>* stacks,int mov,int from,int to)
{
    // for part 2 order is preserved
    std::stack<char> s;
    for(int i = 0; i < mov; i++)
    {
        s.push(stacks[from].top());
        stacks[from].pop();
    }
    for(int i = 0; i < mov; i++)
    {
        stacks[to].push(s.top());
        s.pop();
    }
}

int main()
{
    std::cout << "Advent of Code 2022 day 5\n";
    std::ifstream file("/home/roger/Advent22/Dec5/Data.txt");

    std::stack<char> stacks[9];

    // load the stacks
    loadstacks(file,stacks);

    // skip a line
    char buf[40];
    file.getline(buf,sizeof(buf));

    int mov,from,to;
    std::string s;
    while(!file.eof())
    {
        file >> s >> mov >> s >> from >> s >> to ;
        move(stacks,mov,from - 1,to - 1);
    }

    std::cout << "Part 1 " << top(stacks) << "\n";

    // reposition file
    file.clear();
    file.seekg(0);

    std::stack<char> stacks2[9];
    // load the stacks
    loadstacks(file,stacks2);

    // skip a line
    file.getline(buf,sizeof(buf));

    while(!file.eof())
    {
        file >> s >> mov >> s >> from >> s >> to ;
        move2(stacks2,mov,from - 1,to - 1);
    }

    std::cout << "Part 2 " << top(stacks2) << "\n";

    file.close();
    return 0;
}

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Tue Dec 06, 2022 12:57 am

Day 5 for pshell

Uncovered a few compiler issues with this one!

Code: Select all

int line_length(char* t) {
    char* cp = t;
    int l = 0;
    while (*cp++ != '\n')
        l++;
    return l;
}

void push(int *stk, char c) {
    stk[++stk[0]] = c;
}

char pop(int *stk) {
    return stk[stk[0]--];
}

int size(int* stk) {
    return stk[0];
}

char top(int* stk) {
    return stk[stk[0]];
}
    
void reverse(int *stk) {
    int i, n = size(stk);
    if (n < 2)
        return;
    for (i = 0; i < n / 2; ++i) {
        int temp = stk[i + 1];
        stk[i + 1] = stk[n - i];
        stk[n - i] = temp;
    }
}

char* skip_past_str(char* t) {
    while (*t != ' ')
        ++t;
    ++t;
    return t;
}

int s1[9][60], s2[9][60];

void main() {
    int start = time_us_32();
    int f = open("day5.txt", O_RDONLY);
    int i, j, n = lseek(f, 0, SEEK_END);
    lseek(f, 0, SEEK_SET);
    char* txt = (char*)malloc(n + 1);
    read(f, txt, n);
    txt[n] = 0;
    for (i = 0; i < 9; ++i)
        s1[i][0] = 0;
    while (txt[1] != '1') {
        int len = line_length(txt);
        for (i = 0; i < 9; ++i) {
            if (((i * 4) + 1) >= len)
                break;
            char c = txt[(i * 4) + 1];
            if (c != ' ')
                push(s1[i], c);
        }
        txt += len + 1;
    }
    txt += line_length(txt) + 1;
    txt += line_length(txt) + 1;
    for (i = 0; i < 9; ++i)
        reverse(s1[i]);
    memcpy(s2, s1, sizeof(s2));
    int from, to;
    while (*txt) {
                if (line_length(txt) == 0)
                        break;
        txt = skip_past_str(txt);
        n = strtol(txt, &txt, 10);
        txt = skip_past_str(++txt);
        from = strtol(txt, &txt, 10) - 1;
        txt = skip_past_str(++txt);
        to = strtol(txt, &txt, 10) - 1;
        if (*txt)
            ++txt;
        for (j = 0; j < n; ++j)
            push(s1[to], pop(s1[from]));
        int temp[60];
        temp[0] = 0;
        for (j = 0; j < n; ++j)
            push(temp, pop(s2[from]));
        for (j = 0; j < n; ++j)
            push(s2[to], pop(temp));
    }
    printf("--- 5: Supply Stacks ---\nPart 1 - ");
    for (i = 0; i < 9; i++)
        if (size(s1[i]))
            printf("%c", top(s1[i]));
    printf("\nPart 2 - ");
    for (i = 0; i < 9; i++)
        if (size(s2[i]))
            printf("%c", top(s2[i]));
    printf("\nElapsed - %f ms.\n", (float)(time_us_32() - start) / 1000.0);
}

Code: Select all

/: cc day5

--- 5: Supply Stacks ---
Part 1 - VGBBJCRMN
Part 2 - LBBVJBRMH
Elapsed - 26.541000 ms.

Last edited by lurk101 on Tue Dec 06, 2022 4:35 am, edited 1 time in total.
History doesn’t repeat itself, it rarely even rhymes.

ejolson
Posts: 10539
Joined: Tue Mar 18, 2014 11:47 am

Re: Advent 2022

Tue Dec 06, 2022 1:37 am

lurk101 wrote:
Tue Dec 06, 2022 12:57 am
Day 5 for pshell

Uncovered a few compiler issues with this one!
Do I need to update my copy of Pshell?

Fido's been working on a solution using dogly (doubly) linked lists to represent the stacks. This seems like a weird data structure for this puzzle to me but Fido insisted. In my opinion someone is enjoying all the dogfooding too much.

Hopefully, day 5 will be finished before the next puzzle opens.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Tue Dec 06, 2022 2:40 am

ejolson wrote:
Tue Dec 06, 2022 1:37 am
Do I need to update my copy of Pshell?
Two problems discovered. Text strings, which are allocated as global data, were limited to the 1st 4K. That should have been 16K. I've pushed a fix for that.
The second problem I don't have a fix for yet. Seems large local arrays aren't handled properly. This can me illustrated by moving the S1 and S2 array declarations in day5.c from global storage to local inside main. The local storage version crashes. There should be plenty of stack space left to accommodate large locals.

Oh! and a third. sizeof seems to be broken for multidimensional arrays.
Last edited by lurk101 on Tue Dec 06, 2022 2:55 am, edited 1 time in total.
History doesn’t repeat itself, it rarely even rhymes.

ejolson
Posts: 10539
Joined: Tue Mar 18, 2014 11:47 am

Re: Advent 2022

Tue Dec 06, 2022 2:48 am

lurk101 wrote:
Tue Dec 06, 2022 2:40 am
ejolson wrote:
Tue Dec 06, 2022 1:37 am
Do I need to update my copy of Pshell?
Two problems discovered. Text strings, which are allocated as global data, were limited to the 1st 4K. That should have been 16K. I've pushed a fix for that.
The second problem I don't have a fix for yet. Seems large local arrays aren't handled properly. This can me illustrated by moving the S1 and S2 array declarations in day5.c from global storage to local inside main. The local storage version crashes. There should be plenty of stack space left to accommodate large locals.
I've been somewhat frugal with memory by using an out-of-core algorithm for each solution so far. Fido's code didn't discover any bugs.

The output was

Code: Select all

/aofcode/2022/: cc day05.c

Advent of Code 2022 Day 5 Camp Cleanup

Part 1 The reversed crates are QPJPLMNNR
Part 2 The correct crates are BQDNWJPVJ

Total execution time 0.0795550 seconds.
and the code

Code: Select all

/*  Advent of Code 2022 Day 5 Camp Cleanup
    Written December 2022 by Eric Olson */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#ifdef LINUX
#include <time.h>
static struct timespec tic_start;
void tic(){
    clock_gettime(CLOCK_MONOTONIC_RAW,&tic_start);
}
float toc(){
    struct timespec tic_stop;
    clock_gettime(CLOCK_MONOTONIC_RAW,&tic_stop);
    float sec=tic_stop.tv_sec-tic_start.tv_sec;
    return sec+(tic_stop.tv_nsec-tic_start.tv_nsec)*1.0e-9;
}
#endif

#ifndef LINUX
int tstart;
void tic(){
    tstart=time_us_32();
}
float toc(){
    return (float)(time_us_32()-tstart)/1000000.0;
}
#endif

#define BUFSZ 128
#define UGBSZ 32

struct fpspec {
    int fd,a,b,m;
    char c[BUFSZ],u[UGBSZ];
    struct fpspec *r;
};

struct fpspec rroot;
struct fpspec *fproot;

char *psindex(char *s,int c){
    do {
        if(*s==c) return s;
    } while(*++s);
    return 0;
}

char *fierror;
struct fpspec *fpopen(char *fn,char *mode){
    int m=0;
    if(psindex(mode,'r')) m|=1;
    if(psindex(mode,'w')) m|=2;
    if(!m){
        printf("Invalid mode %s to open file %s!\n",mode,fn);
        exit(1);
    }
    switch(--m){
case 0:
        m=O_RDONLY; break;
case 1:
        m=O_WRONLY; break;
case 2:
        m=O_RDWR; break;
    }
    int fd=open(fn,m);
    if(fd<0){
        printf("Unable to open %s for mode %s!\n",fn,mode);
        exit(1);
    }
    struct fpspec *fp,*fpo;
    for(fp=&rroot;fp;fpo=fp,fp=fp->r){
        if(fp->fd==0||fp->fd==fd){
            fp->fd=fd;
            fp->a=0; fp->b=0; fp->m=0;
            return fp;
        }
    }
    fp=(struct fpspec *)malloc(sizeof(struct fpspec));
    if(!fp){
        printf("Can't allocate memory for fpspec!\n");
        exit(1);
    }
    fpo->r=fp;
    fp->fd=fd;
    fp->a=0; fp->b=0; fp->m=0;
    fp->r=0;
    return fp;
}

int fpgetc(struct fpspec *fp){
    if(fp->m) return fp->u[--fp->m];
    if(fp->a>=fp->b){
        if(fp->fd<0) return -1;
        fp->a=0;
        fp->b=read(fp->fd,fp->c,BUFSZ);
    }
    if(fp->a<fp->b){
        return fp->c[fp->a++];
    }
    return -1;
}

char *fpgets(char *s,int n,struct fpspec *fp){
    int i=0;
    --n;
    for(i=0;i<n;i++){
        int c=fpgetc(fp);
        if(c<=0||c=='\n'||c=='\r'){
            if(c<=0&&!i) return 0;
            s[i]=0;
            return s;
        }
        s[i]=c;
    }
    s[n]=0;
    return s;
}

void fpugetc(int c,struct fpspec *fp){
    if(fp->a>0) fp->c[--fp->a]=c;
    else if(fp->m<UGBSZ) fp->u[fp->m++]=c;
    else {
        printf("Unget buffer overflow fpugetc!\n");
        exit(1);
    }
}

int fpputc(int c,struct fpspec *fp){
    if(fp->fd<0) return -1;
    char b=c;
    return write(fp->fd,&b,1);
}

int fpclose(struct fpspec *fp){
    return close(fp->fd);
}

int mydigit(int c){
    if(c>='0'&&c<='9') return c-'0';
    return -1;
}

char myletter(int c){
    if(c>='A'&&c<='Z') return c-'A';
    return -1;
}

char *getint(int *n,char *s){
    *n=0;
    for(;;){
        int d=mydigit(*s);
        if(d<0) return s;
        *n=*n*10+d;
        ++s;
    }
}

char *bparse(char *s){
    if(!strncmp(s,"   ",3)) return s+3;
    return s;
}

char *lparse(int *c,char *s){
    if(s[0]=='['){
        *c=myletter(s[1]);
        if(*c>=0){
            if(s[2]==']'){
                return s+3;
            }
        }
    }
    return s;
}

struct dogll {
    struct dogll *a,*b;
    int x;
};

#define SMAX 10
struct dogll head[SMAX],tail[SMAX];

void llbins(struct dogll *l0,struct dogll *l1){
    struct dogll *l2=l0->b;
    l1->a=l0; l1->b=l2;
    l2->a=l1; l0->b=l1;
}

void llains(struct dogll *l1,struct dogll *l2){
    struct dogll *l0=l2->a;
    l1->a=l0; l1->b=l2;
    l2->a=l1; l0->b=l1;
}

void ddrem(struct dogll *l1){
    struct dogll *l0=l1->a;
    struct dogll *l2=l1->b;
    l0->b=l2; l2->a=l0;
}

void cleanup(){
    int i;
    for(i=0;i<SMAX;i++){
        struct dogll *l0=&head[i],*l1;
        for(l0=l0->b;l0->b;l0=l1){
            l1=l0->b; free(l0);
        }
    }
    for(i=0;i<SMAX;i++){
        head[i].b=&tail[i];
        tail[i].a=&head[i];
    }
}

char buf[128];
char *decode(){
    int i;
    for(i=0;i<SMAX;i++){
        struct dogll *l0=&head[i];
        l0=l0->b;
        if(!l0->b) break;
        buf[i]=l0->x+'A';
    }
    buf[i]=0;
    return buf;
}

void doinit(struct fpspec *fp){
    char *s,*t;
    int c,i;
    for(i=0;i<SMAX;i++){
        head[i].b=&tail[i];
        tail[i].a=&head[i];
    }
    for(;;){
        s=fpgets(buf,128,fp);
        if(!s) {
            printf("Reached end before initializing\n");
            exit(1);
        }
        for(i=0;i<SMAX;i++){
            s=lparse(&c,t=s);
            if(s>t){
                struct dogll *l1=(struct dogll *)malloc(sizeof(struct dogll));
                l1->x=c;
                llains(l1,&tail[i]);
            } else {
                s=bparse(s);
            }
            if(s==t){
                if(!strncmp(s," 1 ",3)){
                    s=fpgets(buf,128,fp);
                }
                return;
            }
            if(*s==' ') s++;
            if(!*s) break;
        }
    }
}

char *mstring(char *w,char *s){
    int n=strlen(w);
    if(!strncmp(w,s,n)) return s+n;
    printf("Unable to match %s starting %s\n",w,s);
    exit(1);
}

void pmove(int *n,int *f,int *t,char *s){
    s=mstring("move ",s);
    s=getint(n,s);
    s=mstring(" from ",s);
    s=getint(f,s); --(*f);
    s=mstring(" to ",s);
    s=getint(t,s); --(*t);
}

void part1(char *fn){
    struct fpspec *fp=fpopen(fn,"r");
    if(!fp){
        printf("Unable to open %s for reading!\n",fn);
        exit(1);
    }
    doinit(fp);
    char *s;
    for(;;){
        int j,n,f,t;
        s=fpgets(buf,128,fp);
        if(!s) break;
        pmove(&n,&f,&t,s);
        for(j=0;j<n;j++){
            struct dogll *l1=head[f].b;
            ddrem(l1);
            llbins(&head[t],l1);
        }
    }
    printf("Part 1 The reversed crates are %s\n",decode());
    cleanup();
    fpclose(fp);
}

void part2(char *fn){
    struct fpspec *fp=fpopen(fn,"r");
    if(!fp){
        printf("Unable to open %s for reading!\n",fn);
        exit(1);
    }
    doinit(fp);
    char *s;
    for(;;){
        int j,n,f,t;
        s=fpgets(buf,128,fp);
        if(!s) break;
        pmove(&n,&f,&t,s);
        if(f==t) continue;
        struct dogll *l2=head[t].b;
        for(j=0;j<n;j++){
            struct dogll *l1=head[f].b;
            ddrem(l1);
            llains(l1,l2);
        }
    }
    printf("Part 2 The correct crates are %s\n",decode());
    cleanup();
    fpclose(fp);
}

void dowork(){
    char *fn="day05.txt";
    part1(fn);
    part2(fn);
}

int main(){
    printf("Advent of Code 2022 Day 5 Camp Cleanup\n\n");
    tic();
    dowork();
    printf("\nTotal execution time %g seconds.\n",toc());
    return 0;
}
Someone bought up all the dog treats and is scalping them on Amazon. At 346 lines of code I hope the dog developer does not expect to get paid per line.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Tue Dec 06, 2022 4:33 am

Pushed a fix for the string literal and array sizeof problem. I'll look at the large local array issue tomorrow.
History doesn’t repeat itself, it rarely even rhymes.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Tue Dec 06, 2022 5:40 am

Day 6

Code: Select all

#define title "--- Day 6: Tuning Trouble  ---"
#include <chrono>
#include <fstream>
#include <iostream>
#include <string>

using namespace std;
using namespace chrono;

bool all_diff(char* c, int l) {
    for (int i = 0; i < l - 1; ++i)
        for (int j = i + 1; j < l; ++j)
            if (c[i] == c[j])
                return false;
    return true;
}

void rotate(char* cn, char c, int l) {
    for (int i = 0; i < l - 1; ++i)
        cn[i] = cn[i + 1];
    cn[l - 1] = c;
}

int main() {
    auto start = high_resolution_clock::now();
    ifstream f("day6.txt");
    char c;
    char c4[4] = { 0 };
    int n1 = 0;
    while (f >> c) {
        rotate(c4, c, 4);
        if ((n1 > 4) && all_diff(c4, 4))
            break;
        ++n1;
    }
    f.clear();
    f.seekg(0, ios_base::beg);
    char c14[14] = { 0 };
    int n2 = 0;
    while (f >> c) {
        rotate(c14, c, 14);
        if ((n2 > 14) && all_diff(c14, 14))
            break;
        ++n2;
    }
    cout << title << endl
        << "Part 1 - " << n1 + 1 << endl
        << "Part 2 - " << n2 + 1 << endl
        << "Elapsed - "
        << duration_cast<microseconds>(high_resolution_clock::now() - start).count() / 1e3
        << " ms." << endl;
}

Code: Select all

--- Day 6: Tuning Trouble  ---
Part 1 - 1757
Part 2 - 2950
Elapsed - 0.319 ms.
History doesn’t repeat itself, it rarely even rhymes.

User avatar
lurk101
Posts: 2094
Joined: Mon Jan 27, 2020 2:35 pm
Location: Cumming, GA (US)

Re: Advent 2022

Tue Dec 06, 2022 6:19 am

Easy translation of day 6 to pshell

Code: Select all

int all_diff(char* c, int l) {
    int i, j;
    for (i = 0; i < l - 1; ++i)
        for (j = i + 1; j < l; ++j)
            if (c[i] == c[j])
                return 0;
    return 1;
}

void rotate(char* cn, char c, int l) {
    int i;
    for (i = 0; i < l - 1; ++i)
        cn[i] = cn[i + 1];
    cn[l - 1] = c;
}

void main() {
    int start = time_us_32();
    int f = open("day6.txt", O_RDONLY);
    int l = lseek(f, 0, SEEK_END);
    lseek(f, 0, SEEK_SET);
    char* txt = (char*)malloc(l + 1);
    read(f, txt, l);
    txt[l] = 0;
    char* cp = txt;
    char c4[4];
    memset(c4, 0, sizeof(c4));
    int n1 = 0;
    while (*cp) {
        rotate(c4, *cp++, 4);
        if ((n1 > 4) && all_diff(c4, 4))
            break;
        ++n1;
    }
    cp = txt;
    char c14[14];
    memset(c14, 0, sizeof(c14));
    int n2 = 0;
    while (*cp) {
        rotate(c14, *cp++, 14);
        if ((n2 > 14) && all_diff(c14, 14))
            break;
        ++n2;
    }
    printf("--- Day 6: Tuning Trouble  ---\nPart 1 - %d\nPart 2 - %d\nElapsed - %f ms.\n", n1 + 1,
           n2 + 1, (float)(time_us_32() - start) / 1000.0);
}

Code: Select all

/AoC/day6/: cc day6

--- Day 6: Tuning Trouble  ---
Part 1 - 1757
Part 2 - 2950
Elapsed - 57.172001 ms.
History doesn’t repeat itself, it rarely even rhymes.

jalih
Posts: 211
Joined: Mon Apr 15, 2019 3:54 pm

Re: Advent 2022

Tue Dec 06, 2022 9:11 am

ejolson wrote:
Tue Dec 06, 2022 2:48 am
Someone bought up all the dog treats and is scalping them on Amazon. At 346 lines of code I hope the dog developer does not expect to get paid per line.
Using 8th I was lazy and just modified my day 2 solution for day 5 task... ;)

Code: Select all

[
  ["P","F","M","Q","W","G","R","T"],
  ["H","F","R"],
  ["P","Z","R","V","G","H","S","D"],
  ["Q","H","P","B","F","W","G"],
  ["P","S","M","J","H"],
  ["M","Z","T","H","S","R","P","L"],
  ["P","T","H","N","M","L"],
  ["F","D","Q","R"],
  ["D","S","C","N","L","P","H"]
] constant data

ns?

ns: stacks

: move
  parsews >n ;

: from  \ n -- n n
  parsews >n n:1- ;

defer: to

: to1  \ n n --
  swap >r parsews >n n:1- swap 2 a:close data swap a:_@
  a:open ( a:pop _swap a:push swap ) r> times 2drop ;

: to2  \ n n --
  dup>r data swap a:@ rot n:neg a:/ _swap r> swap a:!
  parsews >n n:1- a:_@ swap a:+ drop ;

: interpret
  ns:stacks only
  eval
  null only ;

ns

: app:main
  "a5.txt" f:slurp
  ' stacks:to1 w:is stacks:to  \ Change to "stacks:to2" to solve part 2 of the puzzle
  ' stacks:interpret s:eachline data ( -1 a:_@ ) a:map "" a:join . cr ;
  

jalih
Posts: 211
Joined: Mon Apr 15, 2019 3:54 pm

Re: Advent 2022

Tue Dec 06, 2022 8:34 pm

Just solved the day 6 using the 8th programming language. I used combination of brute force, table lookup and some binary magic...

Code: Select all

( "" swap s:+ ) 'a 'z a:generate
( 1 swap n:shl ) 0 25 a:generate m:zip
( swap m:_@ ) curry: lookup    \ s -- n

\ MSB of the number
: msb?  \ n -- msb
  n:ln 2 n:ln n:/ n:int ;

\ Bits set in the 32-bit integer
: bits32-set?  \ n -- n
  dup 1 n:shr x55555555 n:band n:-
  dup 2 n:shr x33333333 n:band swap x33333333 n:band n:+
  dup 4 n:shr n:+ x0f0f0f0f n:band
  dup 8 n:shr n:+ x00ff00ff n:band
  dup 16 n:shr n:+ x0000ffff n:band ;

\ Bits set in the integer, handle 32-bit at a time
: bits-set?  \ n -- n
  dup>r msb? n:1+ 32 n:/mod swap if
    n:1+
  then
  >r 0
  ( r@ swap n:shr xffffffff n:band bits32-set?
    n:+  \ bits set
    32 step ) 0 r> 5 n:shl n:1- loop rdrop ;

: sequence \ a n -- a
  a:new
  rot
  ( over swap 4 pick a:slice _swap a:push swap )
  0 2 pick a:len n:1- nip 5 pick n:1+ n:- loop drop nip ;

: find  \ n --
  dup>r sequence
  ( ' lookup a:map ' n:bor 0 a:reduce bits-set? ) a:map
  r@ ' n:= a:indexof null? !if
    r@ n:+ . cr
  else
    drop "Sorry, not found!\n" .
  then drop rdrop ;

: app:main
  "a6.txt" f:slurp >s "" s:/ dup 4 find 14 find ;
  

Return to “General programming discussion”