Commit df971358 authored by Taddeüs Kroes's avatar Taddeüs Kroes

Now using array instead of structs.

parent 1dc110f0
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <assert.h>
typedef struct rabbit { void sequence(int n, int max_age) {
unsigned short age; int i, mature = 0, new[n], died = 0;
struct rabbit *prev, *next;
} rabbit;
rabbit *rabbits = NULL; new[0] = 1;
int rabbit_count = 0;
rabbit *rabbit_born() {
rabbit *r = (rabbit*) malloc(sizeof(rabbit));
if( (r->next = rabbits) )
rabbits->prev = r;
r->age = 0;
r->prev = NULL;
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 = r->next;
else
*ptr = NULL;
rabbit_count--;
free(r);
}
void sequence(int generations, int max_age) {
int i;
rabbit *r, *next = NULL;
rabbits = rabbit_born();
printf("1"); printf("1");
for( i = 1; i < generations; i++ ) { for( i = 1; i < n; i++ ) {
for( r = rabbits; r != NULL; r = next ) { died = i < max_age ? 0 : new[i - max_age];
next = r->next; new[i] = mature;
mature = mature + new[i - 1] - died;
if( r->age++ ) {
rabbit_born();
if( r->age == max_age )
rabbit_die(&r);
}
}
printf(" %d", rabbit_count); printf(" %d", mature + new[i]);
} }
puts(""); 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 main(int argc, char *argv[]) {
...@@ -90,12 +26,14 @@ int main(int argc, char *argv[]) { ...@@ -90,12 +26,14 @@ int main(int argc, char *argv[]) {
return 1; return 1;
} }
generations = atoi(argv[1]); max_age = generations = atoi(argv[1]);
if( argc > 2 && (max_age = atoi(argv[2])) == 1 ) { if( argc > 2 && (max_age = atoi(argv[2])) < 2 ) {
puts("MAX_AGE should be at least 2 (or 0 for infinite)."); puts("MAX_AGE should be at least 2.");
return 1; return 1;
} }
sequence(generations, max_age); sequence(generations, max_age);
return 0;
} }
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