Commit 23bf36ac authored by Taddeüs Kroes's avatar Taddeüs Kroes

Added assignment 7.

parent 155a9451
...@@ -3,4 +3,6 @@ q2 ...@@ -3,4 +3,6 @@ q2
q3 q3
q4 q4
q5 q5
q6
q7
*.o *.o
...@@ -2,7 +2,7 @@ CC=clang ...@@ -2,7 +2,7 @@ CC=clang
CFLAGS=-Wall -Wextra -pedantic -std=c99 -D_GNU_SOURCE CFLAGS=-Wall -Wextra -pedantic -std=c99 -D_GNU_SOURCE
LFLAGS=-lm LFLAGS=-lm
all: q1 q2 q3 q4 q5 all: q1 q2 q3 q4 q5 q7
q%: q%.o q%: q%.o
$(CC) $(CFLAGS) $(LFLAGS) -o $@ $^ $(CC) $(CFLAGS) $(LFLAGS) -o $@ $^
...@@ -11,7 +11,7 @@ q%: q%.o ...@@ -11,7 +11,7 @@ q%: q%.o
$(CC) $(CFLAGS) -o $@ -c $^ $(CC) $(CFLAGS) -o $@ -c $^
clean: clean:
for i in `seq 6`; do \ for i in `seq 7`; do \
rm -vf q$$i; \ rm -vf q$$i; \
done; done;
rm -vf *.o rm -vf *.o
No preview for this file type
/*
* Usage: ./q7 [ generations [ max_age ] ]
*/
#include <stdlib.h>
#include <stdio.h>
typedef struct rabbit {
int age;
struct rabbit *prev, *next;
} rabbit;
rabbit *rabbits = NULL;
int rabbit_count = 0;
rabbit *rabbit_born() {
rabbit *r = (rabbit*) malloc(sizeof(rabbit));
if( (r->next = rabbits) )
rabbits->prev = r;
r->age = 0;
rabbits = r;
rabbit_count++;
return r;
}
void rabbit_die(rabbit **ptr) {
rabbit *r = *ptr;
if( r->prev != NULL )
r->prev->next = r->next;
if( r->next != NULL )
r->next->prev = r->prev;
if( r == rabbits )
rabbits = NULL;
*ptr = NULL;
rabbit_count--;
free(r);
}
void sequence(int generations, int max_age) {
int i;
rabbit *r, *next = NULL;
printf("0");
rabbits = rabbit_born();
for( i = 1; i < generations; i++ ) {
for( r = rabbits; r != NULL; r = next ) {
next = r->next;
if( r->age++ ) {
rabbit_born();
if( r->age == max_age )
rabbit_die(&r);
}
}
printf(" %d", rabbit_count);
}
puts("");
while( rabbits )
rabbit_die(&rabbits);
}
void sequence_old(int n) {
int i, new = 1, new_new, mature = 0, died = 0;
for( i = 0; i < n; i++ ) {
printf("%d + %d = %d\n", mature, new, new + mature);
new_new = mature;
mature = mature + new - died;
new = new_new;
}
}
int main(int argc, char *argv[]) {
int max_age = 0, generations = 10;
if( argc > 1 ) {
generations = atoi(argv[1]);
if( argc > 2 )
max_age = atoi(argv[2]);
}
sequence(generations, max_age);
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment