-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortList.cpp
More file actions
73 lines (64 loc) · 1.44 KB
/
ShortList.cpp
File metadata and controls
73 lines (64 loc) · 1.44 KB
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
#include "ShortList.h"
#include <algorithm> // For std::find
#include <iostream>
#include <assert.h>
ShortList::ShortList() : size(0)
{
std::fill(arr, arr + MAX_SIZE, -1);
std::fill(indexArr, indexArr + MAX_SIZE, -1);
}
bool ShortList::insert(int num)
{
if (indexArr[num] >= 0)
return false;
arr[size] = num;
indexArr[num] = size;
++size;
return true;
}
bool ShortList::remove(int num)
{
if (indexArr[num] >= 0)
{
int idx = indexArr[num];
if (idx != (size - 1))
{
int v = arr[idx] = arr[--size]; // Replace the element with the last element and decrement size
indexArr[v] = idx; // Update indexArr for the moved element
}
else
{
size--;
}
indexArr[num] = -1; // Invalidate the index of the removed element
return true;
}
return false;
}
int ShortList::getRandomElement(std::mt19937 &rng) const
{
return arr[rng() % size];
}
int ShortList::getSize() const
{
return size;
}
int ShortList::getValue(int pos) const
{
return arr[pos];
}
void ShortList::print() const
{
std::cout << "List: ";
for (int i = 0; i < size; ++i)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
void ShortList::clear()
{
size = 0;
std::fill(indexArr, indexArr + MAX_SIZE, -1); // Invalid index
std::fill(arr, arr + MAX_SIZE, -1); // Invalid index
}