summaryrefslogtreecommitdiff
path: root/src/splist.c
blob: c990bfa540fae7bc63c24c35aa0caca5679bc309 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include "splist.h"
#include "list.h"
#include <stdio.h>

struct splist_s {
  List *ls;                     /* a list */
  List *inv;                    /* and its inverse */
  NUM len;                      /* how many elements are stored */
};

splist *
new_splist()
{
  splist *result = MYALLOC(splist, 1);

  if (result == NULL) return NULL;

  result->ls = new_list();

  if (result->ls == NULL) {
    free(result);
    return NULL;
  }

  result->inv = new_list();

  if (result->inv == NULL) {
    destroy_list(result->ls, 0);
    free(result);
    return NULL;
  }

  result->len = 0;

  return result;
}

unsigned char
init_splist(splist *s, NUM size)
{
  unsigned char result = 0;

  result = list_assure_size(s->ls, size);

  if (result) return result;

  result = list_set_length(s->ls, size);

  if (result) return result;

  result = list_assure_size(s->inv, size);

  if (result) return result;

  result = list_set_length(s->inv, size);

  return result;
}

P_ATTR
NUM
splist_len(CCR_MOD(splist *)s)
{
  return s->len;
}

P_ATTR
List *
splist_ls(CCR_MOD(splist *) s)
{
  return s->ls;
}

H_ATTR
void
reset_splist(splist *s)
{
  s->len = 0;
}

H_ATTR
unsigned char
add_to_splist(splist *s, NUM element)
{
  if (s->len >= list_length(s->ls)) {
    fleprintf0("The length of the sparse list exceeds its size!\n");
    print_splist(s);
    return 1;
  }

  NUM *index_pointer = list_nth(s->ls, s->len);

  *index_pointer = element;

  NUM *element_pointer = list_nth(s->inv, element);
  *element_pointer = s->len;

  s->len += 1;

  return 0;
}

H_ATTR
unsigned char
splist_is_member(splist *s, NUM element)
{
  NUM *index = list_nth(s->inv, element);

  if (*index < 0 || *index >= s->len)
    return 0;

  NUM *element_pointer = list_nth(s->ls, *index);

  return *element_pointer == element;
}

void
print_splist(splist *s)
{
  printf("Printing a sparse list with size %lu:\n",
         list_length(s->ls));

  for (NUM i = 0; i < list_length(s->ls); i++) {
    NUM *pointer = list_nth(s->ls, i);
    printf("%ld, \t", *pointer);

    pointer = list_nth(s->inv, i);
    printf("%ld\n", *pointer);
  }

  printf("Printing terminated\n");
}

void
destroy_splist(splist *s)
{
  destroy_list(s->ls, 2);
  destroy_list(s->inv, 2);

  free(s);
}