filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/data_structures/src/tree/space_partitioning_tree/interval_tree/interval_tree.java | //This is a java program to implement a interval tree
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
class Interval<Type> implements Comparable<Interval<Type>>
{
private long start;
private long end;
private Type data;
public Interval(long start, long end, Type data)
{
this.start = start;
this.end = end;
this.data = data;
}
public long getStart()
{
return start;
}
public void setStart(long start)
{
this.start = start;
}
public long getEnd()
{
return end;
}
public void setEnd(long end)
{
this.end = end;
}
public Type getData()
{
return data;
}
public void setData(Type data)
{
this.data = data;
}
public boolean contains(long time)
{
return time < end && time > start;
}
public boolean intersects(Interval<?> other)
{
return other.getEnd() > start && other.getStart() < end;
}
public int compareTo(Interval<Type> other)
{
if (start < other.getStart())
return -1;
else if (start > other.getStart())
return 1;
else if (end < other.getEnd())
return -1;
else if (end > other.getEnd())
return 1;
else
return 0;
}
}
class IntervalNode<Type>
{
private SortedMap<Interval<Type>, List<Interval<Type>>> intervals;
private long center;
private IntervalNode<Type> leftNode;
private IntervalNode<Type> rightNode;
public IntervalNode()
{
intervals = new TreeMap<Interval<Type>, List<Interval<Type>>>();
center = 0;
leftNode = null;
rightNode = null;
}
public IntervalNode(List<Interval<Type>> intervalList)
{
intervals = new TreeMap<Interval<Type>, List<Interval<Type>>>();
SortedSet<Long> endpoints = new TreeSet<Long>();
for (Interval<Type> interval : intervalList)
{
endpoints.add(interval.getStart());
endpoints.add(interval.getEnd());
}
long median = getMedian(endpoints);
center = median;
List<Interval<Type>> left = new ArrayList<Interval<Type>>();
List<Interval<Type>> right = new ArrayList<Interval<Type>>();
for (Interval<Type> interval : intervalList)
{
if (interval.getEnd() < median)
left.add(interval);
else if (interval.getStart() > median)
right.add(interval);
else
{
List<Interval<Type>> posting = intervals.get(interval);
if (posting == null)
{
posting = new ArrayList<Interval<Type>>();
intervals.put(interval, posting);
}
posting.add(interval);
}
}
if (left.size() > 0)
leftNode = new IntervalNode<Type>(left);
if (right.size() > 0)
rightNode = new IntervalNode<Type>(right);
}
public List<Interval<Type>> stab(long time)
{
List<Interval<Type>> result = new ArrayList<Interval<Type>>();
for (Entry<Interval<Type>, List<Interval<Type>>> entry : intervals
.entrySet())
{
if (entry.getKey().contains(time))
for (Interval<Type> interval : entry.getValue())
result.add(interval);
else if (entry.getKey().getStart() > time)
break;
}
if (time < center && leftNode != null)
result.addAll(leftNode.stab(time));
else if (time > center && rightNode != null)
result.addAll(rightNode.stab(time));
return result;
}
public List<Interval<Type>> query(Interval<?> target)
{
List<Interval<Type>> result = new ArrayList<Interval<Type>>();
for (Entry<Interval<Type>, List<Interval<Type>>> entry : intervals
.entrySet())
{
if (entry.getKey().intersects(target))
for (Interval<Type> interval : entry.getValue())
result.add(interval);
else if (entry.getKey().getStart() > target.getEnd())
break;
}
if (target.getStart() < center && leftNode != null)
result.addAll(leftNode.query(target));
if (target.getEnd() > center && rightNode != null)
result.addAll(rightNode.query(target));
return result;
}
public long getCenter()
{
return center;
}
public void setCenter(long center)
{
this.center = center;
}
public IntervalNode<Type> getLeft()
{
return leftNode;
}
public void setLeft(IntervalNode<Type> left)
{
this.leftNode = left;
}
public IntervalNode<Type> getRight()
{
return rightNode;
}
public void setRight(IntervalNode<Type> right)
{
this.rightNode = right;
}
private Long getMedian(SortedSet<Long> set)
{
int i = 0;
int middle = set.size() / 2;
for (Long point : set)
{
if (i == middle)
return point;
i++;
}
return null;
}
@Override
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(center + ": ");
for (Entry<Interval<Type>, List<Interval<Type>>> entry : intervals
.entrySet())
{
sb.append("[" + entry.getKey().getStart() + ","
+ entry.getKey().getEnd() + "]:{");
for (Interval<Type> interval : entry.getValue())
{
sb.append("(" + interval.getStart() + "," + interval.getEnd()
+ "," + interval.getData() + ")");
}
sb.append("} ");
}
return sb.toString();
}
}
class IntervalTree<Type>
{
private IntervalNode<Type> head;
private List<Interval<Type>> intervalList;
private boolean inSync;
private int size;
public IntervalTree()
{
this.head = new IntervalNode<Type>();
this.intervalList = new ArrayList<Interval<Type>>();
this.inSync = true;
this.size = 0;
}
public IntervalTree(List<Interval<Type>> intervalList)
{
this.head = new IntervalNode<Type>(intervalList);
this.intervalList = new ArrayList<Interval<Type>>();
this.intervalList.addAll(intervalList);
this.inSync = true;
this.size = intervalList.size();
}
public List<Type> get(long time)
{
List<Interval<Type>> intervals = getIntervals(time);
List<Type> result = new ArrayList<Type>();
for (Interval<Type> interval : intervals)
result.add(interval.getData());
return result;
}
public List<Interval<Type>> getIntervals(long time)
{
build();
return head.stab(time);
}
public List<Type> get(long start, long end)
{
List<Interval<Type>> intervals = getIntervals(start, end);
List<Type> result = new ArrayList<Type>();
for (Interval<Type> interval : intervals)
result.add(interval.getData());
return result;
}
public List<Interval<Type>> getIntervals(long start, long end)
{
build();
return head.query(new Interval<Type>(start, end, null));
}
public void addInterval(Interval<Type> interval)
{
intervalList.add(interval);
inSync = false;
}
public void addInterval(long begin, long end, Type data)
{
intervalList.add(new Interval<Type>(begin, end, data));
inSync = false;
}
public boolean inSync()
{
return inSync;
}
public void build()
{
if (!inSync)
{
head = new IntervalNode<Type>(intervalList);
inSync = true;
size = intervalList.size();
}
}
public int currentSize()
{
return size;
}
public int listSize()
{
return intervalList.size();
}
@Override
public String toString()
{
return nodeString(head, 0);
}
private String nodeString(IntervalNode<Type> node, int level)
{
if (node == null)
return "";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < level; i++)
sb.append("\t");
sb.append(node + "\n");
sb.append(nodeString(node.getLeft(), level + 1));
sb.append(nodeString(node.getRight(), level + 1));
return sb.toString();
}
}
public class IntervalTreeProblem
{
public static void main(String args[])
{
IntervalTree<Integer> it = new IntervalTree<Integer>();
it.addInterval(0L, 10L, 1);
it.addInterval(20L, 30L, 2);
it.addInterval(15L, 17L, 3);
it.addInterval(25L, 35L, 4);
List<Integer> result1 = it.get(5L);
List<Integer> result2 = it.get(10L);
List<Integer> result3 = it.get(29L);
List<Integer> result4 = it.get(5L, 15L);
System.out.print("\nIntervals that contain 5L:");
for (int r : result1)
System.out.print(r + " ");
System.out.print("\nIntervals that contain 10L:");
for (int r : result2)
System.out.print(r + " ");
System.out.print("\nIntervals that contain 29L:");
for (int r : result3)
System.out.print(r + " ");
System.out.print("\nIntervals that intersect (5L,15L):");
for (int r : result4)
System.out.print(r + " ");
}
}
|
code/data_structures/src/tree/space_partitioning_tree/kd_tree/kd_tree.cpp | #include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
const int k = 2;
struct Node
{
int point[k]; // To store k dimensional point
Node *left, *right;
};
struct Node* newNode(int arr[])
{
struct Node* temp = new Node;
for (int i = 0; i < k; i++)
temp->point[i] = arr[i];
temp->left = temp->right = NULL;
return temp;
}
Node *insertRec(Node *root, int point[], unsigned depth)
{
if (root == NULL)
return newNode(point);
unsigned cd = depth % k;
if (point[cd] < (root->point[cd]))
root->left = insertRec(root->left, point, depth + 1);
else
root->right = insertRec(root->right, point, depth + 1);
return root;
}
Node* insert(Node *root, int point[])
{
return insertRec(root, point, 0);
}
bool arePointsSame(int point1[], int point2[])
{
for (int i = 0; i < k; ++i)
if (point1[i] != point2[i])
return false;
return true;
}
bool searchRec(Node* root, int point[], unsigned depth)
{
if (root == NULL)
return false;
if (arePointsSame(root->point, point))
return true;
unsigned cd = depth % k;
if (point[cd] < root->point[cd])
return searchRec(root->left, point, depth + 1);
return searchRec(root->right, point, depth + 1);
}
bool search(Node* root, int point[])
{
return searchRec(root, point, 0);
}
int main()
{
struct Node *root = NULL;
int points[][k] = {{3, 6}, {17, 15}, {13, 15}, {6, 12},
{9, 1}, {2, 7}, {10, 19}};
int n = sizeof(points) / sizeof(points[0]);
for (int i = 0; i < n; i++)
root = insert(root, points[i]);
int point1[] = {10, 19};
(search(root, point1)) ? cout << "Found\n" : cout << "Not Found\n";
int point2[] = {12, 19};
(search(root, point2)) ? cout << "Found\n" : cout << "Not Found\n";
return 0;
}
|
code/data_structures/src/tree/space_partitioning_tree/kd_tree/kd_tree.java | import java.util.Comparator;
import java.util.HashSet;
public class KDTree
{
int k;
KDNode root;
public KDTree(KDPoint[] points)
{
k = 2;
root = createNode(points,0);
}
public KDNode createNode(KDPoint[] points,int level)
{
if(points.length == 0) return null;
int axis = level % k;
KDPoint median = null;
Comparator<KDPoint> comparator = KDPoint.getComparator(axis);
median = quickSelect(points,0,points.length-1,points.length/2+1,comparator);
KDNode node = new KDNode(median,level);
if(points.length>1){
int tam = 0;
for(int i=0;i<points.length;i++) if(comparator.compare(points[i], median)<0) tam++;
KDPoint[] p1 = new KDPoint[tam];
KDPoint[] p2 = new KDPoint[points.length-tam-1];
int i1 = 0;
int i2 = 0;
for(int i=0;i<points.length;i++){
if(points[i].equals(median)) continue;
else if(comparator.compare(points[i], median)<0) p1[i1++] = points[i];
else p2[i2++] = points[i];
}
KDNode l = createNode(p1, level+1);
KDNode r = createNode(p2,level+1);
if(l!=null) l.parent = node;
if(r!=null) r.parent = node;
node.left = l;
node.right = r;
}
return node;
}
public int nearestNeighbor(KDPoint p,KDNode r,HashSet<KDNode> visitados)
{
KDNode node = r;
int res = Integer.MAX_VALUE;
KDNode prev = null;
while(node!=null){
int axis = node.level%k;
Comparator<KDPoint> comparator = KDPoint.getComparator(axis);
prev = node;
if(comparator.compare(p,node.point)<0 && node.left!=null) node = node.left;
else if(comparator.compare(p,node.point)>0 && node.right!=null) node = node.right;
else node = node.left!=null ? node.left:node.right;
}
node = prev;
while(true){
if(!node.point.equals(p)) res = Math.min(res, p.distance(node.point));
int axis = node.level % k;
KDNode r2 = null;
if(Math.abs(p.coordinates[axis]-node.point.coordinates[axis])<res){
r2 = prev !=null && node.left!=null && prev.equals(node.left) ? node.right:node.left;
}
if(r2 != null && !visitados.contains(r2)){
res = Math.min(res, nearestNeighbor(p, r2,visitados));
}
visitados.add(node);
if(node.equals(r)) break;
prev = node;
node = node.parent;
}
return res;
}
public KDPoint quickSelect(KDPoint[] points,int left,int right,int k,Comparator<KDPoint> c)
{
while(true){
int pivotIndex = left+right/2;
int pivotNewIndex = partition(points,left,right,pivotIndex,c);
int pivotDist = pivotNewIndex - left + 1;
if(pivotDist == k){
return points[pivotNewIndex];
}else if(k<pivotDist){
right= pivotNewIndex - 1;
}else{
k=k-pivotDist;
left=pivotNewIndex + 1;
}
}
}
public int partition(KDPoint[] points,int left,int right,int pivotIndex,Comparator<KDPoint> c)
{
KDPoint pivotValue = points[pivotIndex];
KDPoint aux = points[pivotIndex];
points[pivotIndex] = points[right];
points[right] = aux;
int storeIndex = left;
for(int i=left;i<right;i++){
if(c.compare(points[i],pivotValue)<0){
aux = points[storeIndex];
points[storeIndex] = points[i];
points[i] = aux;
storeIndex++;
}
}
aux = points[right];
points[right] = points[storeIndex];
points[storeIndex] = aux;
return storeIndex;
}
public class KDNode
{
KDPoint point;
KDNode parent;
KDNode left;
KDNode right;
int level;
public KDNode(KDPoint p,int l)
{
point = p;
level = l;
}
public boolean equals(Object o)
{
KDNode n = (KDNode) o;
return point.equals(n.point);
}
public String toString()
{
return point.toString();
}
}
public static class KDPoint
{
int[] coordinates;
public KDPoint(int... coordinates)
{
this.coordinates = coordinates;
}
public static Comparator<KDPoint> getComparator(int axis)
{
final int a = axis;
return new Comparator<KDPoint>(){
public int compare(KDPoint n1,KDPoint n2){
return n1.coordinates[a] - n2.coordinates[a];
}
};
}
public double euclideandistance(KDPoint p)
{
double res = 0;
for(int i=0;i<coordinates.length;i++){
res+= Math.pow(coordinates[i] - p.coordinates[i], 2);
}
return Math.sqrt(res);
}
public int distance(KDPoint p)
{
return Math.abs(coordinates[0]-p.coordinates[0])+Math.abs(coordinates[1]-p.coordinates[1]);
}
public boolean equals(Object o)
{
KDPoint n2 = (KDPoint) o;
for(int i=0;i<coordinates.length;i++){
if(coordinates[i]!=n2.coordinates[i]) return false;
}
return true;
}
public String toString()
{
StringBuilder res = new StringBuilder().append("(");
for(int i=0;i<coordinates.length;i++) res.append(coordinates[i]+",");
res.setLength(res.length()-1);
res.append(")");
return res.toString();
}
}
} |
code/data_structures/src/tree/space_partitioning_tree/oc_tree/oc_tree.py | # Part of Cosmos by OpenGenus Foundation
class Octant:
"""
UP: Y positive.
DOWN: Y negative.
FRONT: Z positive.
BACK: Z negative.
RIGHT: X positive.
LEFT: X negative.
"""
UP_FRONT_LEFT = 0
UP_FRONT_RIGHT = 1
UP_BACK_LEFT = 2
UP_BACK_RIGHT = 3
DOWN_FRONT_LEFT = 4
DOWN_FRONT_RIGHT = 5
DOWN_BACK_LEFT = 6
DOWN_BACK_RIGHT = 7
OUT_OF_BOUNDS = -1
class Point3D:
"""
3d point representation.
+----+
/ /| Y
+----+ |
| | +
| |/ Z
+----+
X
"""
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class Dimension:
"""
Dimension representation.
"""
def __init__(self, width, height, depth):
self.width = width
self.height = height
self.depth = depth
class Box:
"""
Box Class represents boundaries.
"""
def __init__(self, x, y, z, width, height, depth):
self.center = Point3D(x, y, z)
self.dimension = Dimension(width, height, depth)
self.minPos = Point3D(x - width / 2, y - height / 2, z - depth / 2)
self.maxPos = Point3D(x + width / 2, y + height / 2, z + depth / 2)
def contains(self, point3d):
"""
Check if box contains a point.
3D collision detection.
https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection#point_vs._aabb
"""
return (
point3d.x >= self.minPos.x
and point3d.x <= self.maxPos.x
and point3d.y >= self.minPos.y
and point3d.y <= self.maxPos.y
and point3d.z >= self.minPos.z
and point3d.z <= self.maxPos.z
)
def intersect(self, box):
"""
Check if 2 boxes intersect.
3D collision detection.
https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection#aabb_vs._aabb
"""
return (
self.minPos.x <= box.maxPos.x
and self.maxPos.x >= box.minPos.x
and self.minPos.y <= box.maxPos.y
and self.maxPos.y >= box.minPos.y
and self.minPos.z <= box.maxPos.z
and self.maxPos.z >= box.minPos.z
)
def find_octant(self, point3d):
"""
Find which octant contains a specific point.
"""
print(f"POINT x:{point3d.x} y:{point3d.y} z:{point3d.z} IN ", end="")
if (
self.center.x - self.dimension.width / 2 <= point3d.x
and self.center.x >= point3d.x
and self.center.y + self.dimension.height / 2 >= point3d.y
and self.center.y <= point3d.y
and self.center.z + self.dimension.depth / 2 >= point3d.z
and self.center.z <= point3d.z
):
print("UP FRONT LEFT")
return Octant.UP_FRONT_LEFT
if (
self.center.x + self.dimension.width / 2 >= point3d.x
and self.center.x <= point3d.x
and self.center.y + self.dimension.height / 2 >= point3d.y
and self.center.y <= point3d.y
and self.center.z + self.dimension.depth / 2 >= point3d.z
and self.center.z <= point3d.z
):
print("UP FRONT RIGHT")
return Octant.UP_FRONT_RIGHT
if (
self.center.x - self.dimension.width / 2 <= point3d.x
and self.center.x >= point3d.x
and self.center.y + self.dimension.height / 2 >= point3d.y
and self.center.y <= point3d.y
and self.center.z - self.dimension.depth / 2 <= point3d.z
and self.center.z >= point3d.z
):
print("UP BACK LEFT")
return Octant.UP_BACK_LEFT
if (
self.center.x + self.dimension.width / 2 >= point3d.x
and self.center.x <= point3d.x
and self.center.y + self.dimension.height / 2 >= point3d.y
and self.center.y <= point3d.y
and self.center.z - self.dimension.depth / 2 <= point3d.z
and self.center.z >= point3d.z
):
print("UP BACK RIGHT")
return Octant.UP_BACK_RIGHT
if (
self.center.x - self.dimension.width / 2 <= point3d.x
and self.center.x >= point3d.x
and self.center.y - self.dimension.height / 2 <= point3d.y
and self.center.y >= point3d.y
and self.center.z + self.dimension.depth / 2 >= point3d.z
and self.center.z <= point3d.z
):
print("DOWN FRONT LEFT")
return Octant.DOWN_FRONT_LEFT
if (
self.center.x + self.dimension.width / 2 >= point3d.x
and self.center.x <= point3d.x
and self.center.y - self.dimension.height / 2 <= point3d.y
and self.center.y >= point3d.y
and self.center.z + self.dimension.depth / 2 >= point3d.z
and self.center.z <= point3d.z
):
print("DOWN FRONT RIGHT")
return Octant.DOWN_FRONT_RIGHT
if (
self.center.x - self.dimension.width / 2 <= point3d.x
and self.center.x >= point3d.x
and self.center.y - self.dimension.height / 2 <= point3d.y
and self.center.y >= point3d.y
and self.center.z - self.dimension.depth / 2 <= point3d.z
and self.center.z >= point3d.z
):
print("DOWN BACK LEFT")
return Octant.DOWN_BACK_LEFT
if (
self.center.x + self.dimension.width / 2 >= point3d.x
and self.center.x <= point3d.x
and self.center.y - self.dimension.height / 2 <= point3d.y
and self.center.y >= point3d.y
and self.center.z - self.dimension.depth / 2 <= point3d.z
and self.center.z >= point3d.z
):
print("DOWN BACK RIGHT")
return Octant.DOWN_BACK_RIGHT
print("NOT IN BOX")
return Octant.OUT_OF_BOUNDS
class OctreeNode:
"""
Octree node:
- 8 octants, 8 children
- It stores Point3D (a specific capacity)
"""
def __init__(self, box, capacity):
self.children = [None] * 8 # each node has 8 children
self.values = [None] * capacity
self.boundary = box
self.divided = False
self.size = 0
def subdivide(self):
"""
When the node is full, each octant (children) is initialized
with a new center, capacity is the same.
"""
self.divided = True
w = self.boundary.dimension.width / 2
h = self.boundary.dimension.height / 2
d = self.boundary.dimension.depth / 2
x = self.boundary.center.x
y = self.boundary.center.y
z = self.boundary.center.z
capacity = len(self.values)
# UPPER PART
self.children[Octant.UP_FRONT_LEFT] = OctreeNode(
Box(x - w / 2, y + h / 2, z + d / 2, w, h, d), capacity
)
self.children[Octant.UP_FRONT_RIGHT] = OctreeNode(
Box(x + w / 2, y + h / 2, z + d / 2, w, h, d), capacity
)
self.children[Octant.UP_BACK_LEFT] = OctreeNode(
Box(x - w / 2, y + h / 2, z - d / 2, w, h, d), capacity
)
self.children[Octant.UP_BACK_RIGHT] = OctreeNode(
Box(x + w / 2, y + h / 2, z - d / 2, w, h, d), capacity
)
# LOWER PART
self.children[Octant.DOWN_FRONT_LEFT] = OctreeNode(
Box(x - w / 2, y - h / 2, z + d / 2, w, h, d), capacity
)
self.children[Octant.DOWN_FRONT_RIGHT] = OctreeNode(
Box(x + w / 2, y - h / 2, z + d / 2, w, h, d), capacity
)
self.children[Octant.DOWN_BACK_LEFT] = OctreeNode(
Box(x - w / 2, y - h / 2, z - d / 2, w, h, d), capacity
)
self.children[Octant.DOWN_BACK_RIGHT] = OctreeNode(
Box(x + w / 2, y - h / 2, z - d / 2, w, h, d), capacity
)
class Octree:
def __init__(self, box, capacity):
self.root = OctreeNode(box, capacity)
self.capacity = capacity
def insert(self, point3d):
"""
Each node is divided in 8 octants and has a capacity.
At first, root node octants are empty
- If a point is not inside the boudaries, it is not inserted
- If node is not full the we insert it
- Otherwise we subdive the node, find which octant contains
the point and then insert the point
"""
def insert_recursive(point3d, node):
if node.boundary.contains(point3d) == False:
print(f"NOT INSERTED x:{point3d.x} y:{point3d.y} z:{point3d.z}")
return
if node.size < self.capacity:
node.values[node.size] = point3d
node.size += 1
else:
node.subdivide()
octant = node.boundary.find_octant(point3d)
node = node.children[octant]
insert_recursive(point3d, node)
insert_recursive(point3d, self.root)
if __name__ == "__main__":
box = Box(x=0, y=0, z=0, width=2, height=2, depth=2)
octree = Octree(box, capacity=4) # root
# Example
# center=(x=0,y=0,z=0)
# +--------+
# / /|
# / / | height = 2
# +--------+ | Y
# | | |
# | (0,0,0)| +
# | * | / depth=2
# | |/ Z
# +--------+
# width = 2
# X
# Points to be inserted
points = [
# 4 initial nodes, Octree does not subdivides
Point3D(-1, 1, 1),
Point3D(1, 1, 1),
Point3D(-1, 1, -1),
Point3D(1, 1, -1),
# DOWN, Octree subdivides because node is Full
Point3D(-1, -1, 1), # (Octant) DOWN FRONT LEFT
Point3D(1, -1, 1), # (Octant) DOWN FRONT RIGHT
Point3D(-1, -1, -1), # (Octant) DOWN BACK LEFT
Point3D(1, -1, -1), # (Octant) DOWN BACK RIGHT
Point3D(2, 2, 2), # This point is not inserted
]
for p in points:
octree.insert(p)
# Octants
print("Octants:")
point = Point3D(x=-1, y=1, z=1)
assert box.find_octant(point) == Octant.UP_FRONT_LEFT, "should be UP_FRONT_LEFT"
point = Point3D(x=1, y=1, z=1)
assert box.find_octant(point) == Octant.UP_FRONT_RIGHT, "should be UP_FRONT_RIGHT"
point = Point3D(x=-1, y=1, z=-1)
assert box.find_octant(point) == Octant.UP_BACK_LEFT, "should be UP_BACK_LEFT"
point = Point3D(x=1, y=1, z=-1)
assert box.find_octant(point) == Octant.UP_BACK_RIGHT, "should be UP_BACK_RIGHT"
point = Point3D(x=-1, y=-1, z=1)
assert box.find_octant(point) == Octant.DOWN_FRONT_LEFT, "should be DOWN_FRONT_LEFT"
point = Point3D(x=1, y=-1, z=1)
assert (
box.find_octant(point) == Octant.DOWN_FRONT_RIGHT
), "should be DOWN_FRONT_RIGHT"
point = Point3D(x=-1, y=-1, z=-1)
assert box.find_octant(point) == Octant.DOWN_BACK_LEFT, "should be DOWN_BACK_LEFT"
point = Point3D(x=1, y=-1, z=-1)
assert box.find_octant(point) == Octant.DOWN_BACK_RIGHT, "should be DOWN_BACK_RIGHT"
# Intersection
assert (
Box(0, 0, 0, 1, 1, 1).intersect(Box(0.5, 0.5, 0.5, 1, 1, 1)) == True
), "Should Intersect!"
assert (
Box(1, 1, 1, 1, 1, 1).intersect(Box(1, 1, 1, 1, 1, 1)) == True
), "Should Intersect!"
assert (
Box(0, 0, 0, 1, 1, 1).intersect(Box(2, 2, 2, 2, 2, 2)) == False
), "Should NOT Intersect!"
|
code/data_structures/src/tree/space_partitioning_tree/quad_tree/Python_Implementation_Visualization/QuadTree.py | # Part of Cosmos by OpenGenus Foundation
from tkinter import *
class Rectangle:
def __init__(self, x, y, h, w):
self.x = x
self.y = y
self.h = h
self.w = w
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class QuadTree:
def __init__(self, boundary, bucket):
self.boundary = boundary
self.bucket = bucket
self.arr = []
self.NorthEast = None
self.NorthWest = None
self.SouthEast = None
self.SouthWest = None
self.divided = False
def contains(self, point):
if (((point.x >= self.boundary.x - self.boundary.w) and (point.x <= self.boundary.x + self.boundary.w)) and
((point.y <= self.boundary.y + self.boundary.h) and (point.y >= self.boundary.y - self.boundary.h))):
return True
return False
def subdivide(self):
nE = Rectangle(self.boundary.x + (self.boundary.w / 2), self.boundary.y + (self.boundary.h / 2),
self.boundary.w / 2, self.boundary.h / 2)
nW = Rectangle(self.boundary.x - (self.boundary.w / 2), self.boundary.y + (self.boundary.h / 2),
self.boundary.w / 2, self.boundary.h / 2)
sE = Rectangle(self.boundary.x + (self.boundary.w / 2), self.boundary.y - (self.boundary.h / 2),
self.boundary.w / 2, self.boundary.h / 2)
sW = Rectangle(self.boundary.x - (self.boundary.w / 2), self.boundary.y - (self.boundary.h / 2),
self.boundary.w / 2, self.boundary.h / 2)
self.NorthEast = QuadTree(nE, self.bucket)
self.NorthWest = QuadTree(nW, self.bucket)
self.SouthEast = QuadTree(sE, self.bucket)
self.SouthWest = QuadTree(sW, self.bucket)
def insert(self, point):
if not self.contains(point):
return False
if len(self.arr) < self.bucket:
self.arr.append(point)
return True
if not self.divided:
self.subdivide()
self.divided = True
if self.NorthEast.insert(point) is not None:
return True
if self.NorthWest.insert(point) is not None:
return True
if self.SouthEast.insert(point) is not None:
return True
if self.SouthWest.insert(point) is not None:
return True
return False
def visualize(self, pointsList):
root = Tk()
canvas = Canvas(root, height=700, width=700, bg='#fff')
canvas.pack()
for point in pointsList:
canvas.create_oval(point.x - 3, point.y - 3, point.x + 3, point.y + 3)
self.paint(canvas)
root.mainloop()
def paint(self, canvas):
canvas.create_rectangle(self.boundary.x - self.boundary.w, self.boundary.y + self.boundary.h,
self.boundary.x + self.boundary.w, self.boundary.y - self.boundary.h, outline='#fb0')
if self.divided:
self.NorthEast.paint(canvas)
self.NorthWest.paint(canvas)
self.SouthEast.paint(canvas)
self.SouthWest.paint(canvas)
|
code/data_structures/src/tree/space_partitioning_tree/quad_tree/Python_Implementation_Visualization/Visualizer.py | # Part of Cosmos by OpenGenus Foundation
from QuadTree import *
if __name__ == '__main__':
boundary = Rectangle(200, 200, 150, 150)
QT = QuadTree(boundary, 1)
pointsList = [Point(240, 240), Point(150, 150), Point(300, 215), Point(200, 266), Point(333, 190)]
for point in pointsList:
QT.insert(point)
QT.visualize(pointsList)
|
code/data_structures/src/tree/space_partitioning_tree/quad_tree/quad_tree.swift | // Part of Cosmos by OpenGenus Foundation
public struct Point {
let x: Double
let y: Double
public init(_ x: Double, _ y: Double) {
self.x = x
self.y = y
}
}
extension Point: CustomStringConvertible {
public var description: String {
return "Point(\(x), \(y))"
}
}
public struct Size: CustomStringConvertible {
var xLength: Double
var yLength: Double
public init(xLength: Double, yLength: Double) {
precondition(xLength >= 0, "xLength can not be negative")
precondition(yLength >= 0, "yLength can not be negative")
self.xLength = xLength
self.yLength = yLength
}
var half: Size {
return Size(xLength: xLength / 2, yLength: yLength / 2)
}
public var description: String {
return "Size(\(xLength), \(yLength))"
}
}
public struct Rect {
var origin: Point
var size: Size
public init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
var minX: Double {
return origin.x
}
var minY: Double {
return origin.y
}
var maxX: Double {
return origin.x + size.xLength
}
var maxY: Double {
return origin.y + size.yLength
}
func containts(point: Point) -> Bool {
return (minX <= point.x && point.x <= maxX) &&
(minY <= point.y && point.y <= maxY)
}
var leftTopRect: Rect {
return Rect(origin: origin, size: size.half)
}
var leftBottomRect: Rect {
return Rect(origin: Point(origin.x, origin.y + size.half.yLength), size: size.half)
}
var rightTopRect: Rect {
return Rect(origin: Point(origin.x + size.half.xLength, origin.y), size: size.half)
}
var rightBottomRect: Rect {
return Rect(origin: Point(origin.x + size.half.xLength, origin.y + size.half.yLength), size: size.half)
}
func intersects(rect: Rect) -> Bool {
func lineSegmentsIntersect(lStart: Double, lEnd: Double, rStart: Double, rEnd: Double) -> Bool {
return max(lStart, rStart) <= min(lEnd, rEnd)
}
if !lineSegmentsIntersect(lStart: minX, lEnd: maxX, rStart: rect.minX, rEnd: rect.maxX) {
return false
}
// vertical
return lineSegmentsIntersect(lStart: minY, lEnd: maxY, rStart: rect.minY, rEnd: rect.maxY)
}
}
extension Rect: CustomStringConvertible {
public var description: String {
return "Rect(\(origin), \(size))"
}
}
protocol PointsContainer {
func add(point: Point) -> Bool
func points(inRect rect: Rect) -> [Point]
}
class QuadTreeNode {
enum NodeType {
case leaf
case `internal`(children: Children)
}
struct Children: Sequence {
let leftTop: QuadTreeNode
let leftBottom: QuadTreeNode
let rightTop: QuadTreeNode
let rightBottom: QuadTreeNode
init(parentNode: QuadTreeNode) {
leftTop = QuadTreeNode(rect: parentNode.rect.leftTopRect)
leftBottom = QuadTreeNode(rect: parentNode.rect.leftBottomRect)
rightTop = QuadTreeNode(rect: parentNode.rect.rightTopRect)
rightBottom = QuadTreeNode(rect: parentNode.rect.rightBottomRect)
}
struct ChildrenIterator: IteratorProtocol {
private var index = 0
private let children: Children
init(children: Children) {
self.children = children
}
mutating func next() -> QuadTreeNode? {
defer { index += 1 }
switch index {
case 0: return children.leftTop
case 1: return children.leftBottom
case 2: return children.rightTop
case 3: return children.rightBottom
default: return nil
}
}
}
public func makeIterator() -> ChildrenIterator {
return ChildrenIterator(children: self)
}
}
var points: [Point] = []
let rect: Rect
var type: NodeType = .leaf
static let maxPointCapacity = 3
init(rect: Rect) {
self.rect = rect
}
var recursiveDescription: String {
return recursiveDescription(withTabCount: 0)
}
private func recursiveDescription(withTabCount count: Int) -> String {
let indent = String(repeating: "\t", count: count)
var result = "\(indent)" + description + "\n"
switch type {
case .internal(let children):
for child in children {
result += child.recursiveDescription(withTabCount: count + 1)
}
default:
break
}
return result
}
}
extension QuadTreeNode: PointsContainer {
@discardableResult
func add(point: Point) -> Bool {
if !rect.containts(point: point) {
return false
}
switch type {
case .internal(let children):
for child in children {
if child.add(point: point) {
return true
}
}
fatalError("rect.containts evaluted to true, but none of the children added the point")
case .leaf:
points.append(point)
if points.count == QuadTreeNode.maxPointCapacity {
subdivide()
}
}
return true
}
private func subdivide() {
switch type {
case .leaf:
type = .internal(children: Children(parentNode: self))
case .internal:
preconditionFailure("Calling subdivide on an internal node")
}
}
func points(inRect rect: Rect) -> [Point] {
if !self.rect.intersects(rect: rect) {
return []
}
var result: [Point] = []
for point in points {
if rect.containts(point: point) {
result.append(point)
}
}
switch type {
case .leaf:
break
case .internal(let children):
for childNode in children {
result.append(contentsOf: childNode.points(inRect: rect))
}
}
return result
}
}
extension QuadTreeNode: CustomStringConvertible {
var description: String {
switch type {
case .leaf:
return "leaf \(rect) Points: \(points)"
case .internal:
return "parent \(rect) Points: \(points)"
}
}
}
public class QuadTree: PointsContainer {
let root: QuadTreeNode
public init(rect: Rect) {
self.root = QuadTreeNode(rect: rect)
}
@discardableResult
public func add(point: Point) -> Bool {
return root.add(point: point)
}
public func points(inRect rect: Rect) -> [Point] {
return root.points(inRect: rect)
}
}
extension QuadTree: CustomStringConvertible {
public var description: String {
return "Quad tree\n" + root.recursiveDescription
}
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/README.md | # Segment Trees
Segment Tree is used in cases where there are multiple range queries on array and modifications of elements of the same array. For example, finding the sum of all the elements in an array from indices **L to R**, or finding the minimum (famously known as **Range Minumum Query problem**) of all the elements in an array from indices **L to R**. These problems can be easily solved with one of the most versatile data structures, **Segment Tree**.
## What is Segment Tree ?
Segment Tree is basically a binary tree used for storing the intervals or segments. Each node in the Segment Tree represents an interval. Consider an array **A** of size **N** and a corresponding Segment Tree **T** :
1. The root of **T** will represent the whole array `A[0:N−1]`.
2. Each leaf in the Segment Tree **T** will represent a single element `A[i]` such that `0≤i<N`.
3. The internal nodes in the Segment Tree **T** represents the union of elementary intervals `A[i:j]` where `0≤i<j<N`.
The root of the Segment Tree represents the whole array `A[0:N−1]`. Then it is broken down into two half intervals or segments and the two children of the root in turn represent the `A[0:(N−1)/2]` and `A[(N−1)/2+1:(N−1)]`. So in each step, the segment is divided into half and the two children represent those two halves. So the height of the segment tree will be **log N** (base 2). There are **N** leaves representing the **N** elements of the array. The number of internal nodes is **N−1**. So, the total number of nodes are **2×N−1**.
Once the Segment Tree is built, its structure cannot be changed. We can update the values of nodes but we cannot change its structure. Segment tree provides two operations:
1. **Update**: To update the element of the array **A** and reflect the corresponding change in the Segment tree.
2. **Query**: In this operation we can query on an interval or segment and return the answer to the problem (say minimum/maximum/summation in the particular segment).
## Implementation :
Since a Segment Tree is a **binary tree**, a simple linear array can be used to represent the Segment Tree. Before building the Segment Tree, one must figure **what needs to be stored in the Segment Tree's node?**
For example, if the question is to find the sum of all the elements in an array from indices **L to R**, then at each node (except leaf nodes) the sum of its children nodes is stored, or if the question is to find the minimum of all the elements in an array from indices **L to R**, then at each node the minimum of its children nodes is stored (**Range Minumum Query problem**).
A Segment Tree can be built using **recursion (bottom-up approach)**. Start with the leaves and go up to the root and update the corresponding changes in the nodes that are in the path from leaves to root. Leaves represent a single element. In each step, the data of two children nodes are used to form an internal parent node. Each internal node will represent a union of its children’s intervals. Merging may be different for different questions. So, recursion will end up at the root node which will represent the whole array.
For **update()**, search the leaf that contains the element to update. This can be done by going to either on the left child or the right child depending on the interval which contains the element. Once the leaf is found, it is updated and again use the bottom-up approach to update the corresponding change in the path from that leaf to the root.
To make a **query()** on the Segment Tree, select a range from **L to R** (which is usually given in the question). Recurse on the tree starting from the root and check if the interval represented by the node is completely in the range from **L to R**. If the interval represented by a node is completely in the range from
**L to R**, return that node’s value.
### Example :
Given an array **A** of size **N** and some queries. There are two types of queries :
1. **Update :** Given `idx` and `val`, update array element `A[idx]` as `A[idx]=A[idx]+val`.
2. **Query :** Given `l` and `r` return the value of `A[l]+A[l+1]+A[l+2]+…..+A[r−1]+A[r] `such that `0≤l≤r<N`.
First, figure what needs to be stored in the Segment Tree's node. The question asks for **summation in the interval from l to r**, so in each node, **sum of all the elements in that interval represented by the node**. Next, build the Segment Tree. The implementation with comments below explains the building process.
```
void build(int node, int start, int end)
{
if(start == end)
{
// Leaf node will have a single element
tree[node] = A[start];
}
else
{
int mid = (start + end) / 2;
// Recurse on the left child
build(2*node, start, mid);
// Recurse on the right child
build(2*node+1, mid+1, end);
// Internal node will have the sum of both of its children
tree[node] = tree[2*node] + tree[2*node+1];
}
}
```
As shown in the code above, start from the **root** and recurse on the **left** and the **right child** until a leaf node is reached. From the leaves, go back to the root and update all the nodes in the path. `node` represents the current node that is being processed. Since Segment Tree is a binary tree. `2×node` will represent the left node and `2×node+1` will represent the right node. `start` and `end` represents the interval represented by the `node`. Complexity of **build()** is **O(N).**
To update an element, look at the interval in which the element is present and recurse accordingly on the left or the right child.
```
void update(int node, int start, int end, int idx, int val)
{
if(start == end)
{
// Leaf node
A[idx] += val;
tree[node] += val;
}
else
{
int mid = (start + end) / 2;
if(start <= idx and idx <= mid)
{
// If idx is in the left child, recurse on the left child
update(2*node, start, mid, idx, val);
}
else
{
// if idx is in the right child, recurse on the right child
update(2*node+1, mid+1, end, idx, val);
}
// Internal node will have the sum of both of its children
tree[node] = tree[2*node] + tree[2*node+1];
}
}
```
Complexity of update will be **O(logN).**
To query on a given range, check 3 conditions.
1. Range represented by a node is **completely inside** the given range.
2. Range represented by a node is **completely outside** the given range.
3. Range represented by a node is **partially inside and partially outside** the given range.
If the range represented by a node is completely outside the given range, simply `return 0`. If the range represented by a node is completely within the given range, return the value of the node which is the sum of all the elements in the range represented by the node. And if the range represented by a node is partially inside and partially outside the given range, return sum of the left child and the right child. Complexity of query will be **O(logN).**
```
int query(int node, int start, int end, int l, int r)
{
if(r < start or end < l)
{
// range represented by a node is completely outside the given range
return 0;
}
if(l <= start and end <= r)
{
// range represented by a node is completely inside the given range
return tree[node];
}
// range represented by a node is partially inside and partially outside the given range
int mid = (start + end) / 2;
int p1 = query(2*node, start, mid, l, r);
int p2 = query(2*node+1, mid+1, end, l, r);
return (p1 + p2);
}
```
You can now check out the complete code for **Segment Trees** in this same folder.
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/lazy_segment_tree.java | // Java program to demonstrate lazy propagation in segment tree
// Part of Cosmos by OpenGenus Foundation
class LazySegmentTree
{
final int MAX = 1000; // Max tree size
int tree[] = new int[MAX]; // To store segment tree
int lazy[] = new int[MAX]; // To store pending updates
/* index -> index of current node in segment tree
sstart and send -> Starting and ending indexes of elements for
which current nodes stores sum.
ustart and uend -> starting and ending indexes of update query
val -> which we need to add in the range ustart to uend */
void updateRangeUtil(int index, int sstart, int send, int ustart, int uend, int val)
{
// If lazy value is non-zero for current node of segment
// tree, then there are some pending updates. So we need
// to make sure that the pending updates are done before
// making new updates. Because this value may be used by
// parent after recursive calls (See last line of this
// function)
if (lazy[index] != 0)
{
// Make pending updates using value stored in lazy array
tree[index] += (send - sstart + 1) * lazy[index];
// checking if it is not leaf node because if
// it is leaf node then we cannot go further
if (sstart != send)
{
// We can postpone updating children we don't
// need their new values now.
// Since we are not yet updating children of index,
// we need to set lazy flags for the children
lazy[index * 2 + 1] += lazy[index]; //left child
lazy[index * 2 + 2] += lazy[index]; //right child
}
// Set the lazy value for current node as 0 as it
// has been updated
lazy[index] = 0;
}
// out of range
if (sstart > send || sstart > uend || send < ustart)
return;
// Current segment is fully in range
if (sstart >= ustart && send <= uend)
{
// Add val to current node
tree[index] += (send - sstart + 1) * val;
// same logic for checking leaf node or not
if (sstart != send)
{
// This is where we store values in lazy nodes,
// rather than updating the segment tree itelf
// Since we don't need these updated values now
// we postpone updates by storing values in lazy[]
lazy[index * 2 + 1] += val;
lazy[index * 2 + 2] += val;
}
return;
}
// If not completely in range, but overlaps, recur for children,
int mid = (sstart + send) / 2;
updateRangeUtil(index * 2 + 1, sstart, mid, ustart, uend, val);
updateRangeUtil(index * 2 + 2, mid + 1, send, ustart, uend, val);
// Use the result of children calls to update this node
tree[index] = tree[index * 2 + 1] + tree[index * 2 + 2];
}
// Function to update a range of values in segment tree
void updateRange(int n, int ustart, int uend, int val) {
updateRangeUtil(0, 0, n - 1, ustart, uend, val);
}
/* A recursive function to get the sum of values in given
range of the array. The following are parameters for
this function.
index --> Index of current node in the segment tree.
Initially 0 is passed as root is always at'
index 0
sstart & send --> Starting and ending indexes of the
segment represented by current node,
i.e., tree[index]
qstart & qend --> Starting and ending indexes of query
range */
int getSumUtil(int sstart, int send, int qstart, int qend, int index)
{
// If lazy flag is set for current node of segment tree,
// then there are some pending updates. So we need to
// make sure that the pending updates are done before
// processing the sub sum query
if (lazy[index] != 0)
{
// Make pending updates to this node. Note that this
// node represents sum of elements in arr[sstart..send] and
// all these elements must be increased by lazy[index]
tree[index] += (send - sstart + 1) * lazy[index];
// checking if it is not leaf node because if
// it is leaf node then we cannot go further
if (sstart != send)
{
// Since we are not yet updating children of index,
// we need to set lazy values for the children
lazy[index * 2 + 1] += lazy[index];
lazy[index * 2 + 2] += lazy[index];
}
// update the lazy value for current node as it has
// been updated
lazy[index] = 0;
}
// Out of range
if (sstart > send || sstart > qend || send < qstart)
return 0;
// At this point, pending lazy updates are done
// for current node. So we can return value
// If this segment lies in range
if (sstart >= qstart && send <= qend)
return tree[index];
// If a part of this segment overlaps with the given range
int mid = (sstart + send) / 2;
return getSumUtil(sstart, mid, qstart, qend, 2 * index + 1) + getSumUtil(mid + 1, send, qstart, qend, 2 * index + 2);
}
// Return sum of elements in range from index qstart (query start)
// to qend (query end). It mainly uses getSumUtil()
int getSum(int n, int qstart, int qend)
{
// Check for erroneous input values
if (qstart < 0 || qend > n - 1 || qstart > qend)
{
System.out.println("Invalid Input");
return -1;
}
return getSumUtil(0, n - 1, qstart, qend, 0);
}
/* A recursive function that constructs Segment Tree for
array[sstart..send]. index is index of current node in segment
tree st. */
void constructSTUtil(int arr[], int sstart, int send, int index)
{
// out of range as sstart can never be greater than send
if (sstart > send)
return;
/* If there is one element in array, store it in
current node of segment tree and return */
if (sstart == send)
{
tree[index] = arr[sstart];
return;
}
/* If there are more than one elements, then recur
for left and right subtrees and store the sum
of values in this node */
int mid = (sstart + send) / 2;
constructSTUtil(arr, sstart, mid, index * 2 + 1);
constructSTUtil(arr, mid + 1, send, index * 2 + 2);
tree[index] = tree[index * 2 + 1] + tree[index * 2 + 2];
}
/* Function to construct segment tree from given array.
This function allocates memory for segment tree and
calls constructSTUtil() to fill the allocated memory */
void constructST(int arr[], int n)
{
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, 0);
}
// The Main function
public static void main(String args[])
{
int arr[] = {1, 3, 5, 7, 9, 11};
int n = arr.length;
LazySegmentTree tree = new LazySegmentTree();
// Build segment tree from given array
tree.constructST(arr, n);
// Print sum of values in array from index 1 to 3
System.out.println("Sum of values in given range = " + tree.getSum(n, 1, 3));
// Add 10 to all nodes at indexes from 1 to 5.
tree.updateRange(n, 1, 5, 10);
// Find sum after the value is updated
System.out.println("Updated sum of values in given range = " + tree.getSum(n, 1, 3));
}
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/persistent_segment_tree_sum.cpp | // Fully persistent Segment tree with spaces. Allows to find sum in O(log size) time in any version. Uses O(n log size) memory.
#include <iostream>
#include <string>
const int size = 1000000000;
const int versionCount = 100000;
struct node
{
int leftBound, rightBound;
node *leftChild, *rightChild;
int value;
node (int LeftBound, int RightBound)
{
leftBound = LeftBound;
rightBound = RightBound;
value = 0;
leftChild = rightChild = 0;
}
node (node *vertexToClone)
{
leftBound = vertexToClone->leftBound;
rightBound = vertexToClone->rightBound;
value = vertexToClone->value;
leftChild = vertexToClone->leftChild;
rightChild = vertexToClone->rightChild;
}
} *root[versionCount];
void add (node *vertex, int destination, int value)
{
if (vertex->leftBound == destination && vertex->rightBound == destination + 1)
{
vertex->value += value;
return;
}
vertex->value += value;
int middle = (vertex->leftBound + vertex->rightBound) / 2;
if (destination < middle)
{
if (vertex->leftChild == 0)
vertex->leftChild = new node (vertex->leftBound, middle);
else
vertex->leftChild = new node (vertex->leftChild);
add (vertex->leftChild, destination, value);
}
else
{
if (vertex->rightChild == 0)
vertex->rightChild = new node (middle, vertex->rightBound);
else
vertex->rightChild = new node (vertex->rightChild);
add (vertex->rightChild, destination, value);
}
}
int ask (node *vertex, int leftBound, int rightBound)
{
if (vertex == 0)
return 0;
if (vertex->leftBound >= leftBound && vertex->rightBound <= rightBound)
return vertex->value;
if (vertex->leftBound >= rightBound && vertex->rightBound <= leftBound)
return 0;
return ask (vertex->leftChild, leftBound, rightBound) + ask (vertex->rightChild, leftBound,
rightBound);
}
int main ()
{
root[0] = new node (-size, size); // Actually allows negative numbers
std::cout << "Print number of queries!\n";
int q;
std::cin >> q;
int currentVersion = 1;
for (int _ = 0; _ < q; _++)
{
std::string type;
std::cin >> type;
if (type == "add")
{
int version, destination, value;
std::cin >> version >> destination >> value;
root[currentVersion] = new node (root[version]);
add (root[currentVersion], destination, value);
std::cout << "Version " << currentVersion << " created succesfully!\n";
++currentVersion;
}
else if (type == "ask")
{
int version, leftBound, rightBound;
std::cin >> version >> leftBound >> rightBound;
std::cout << ask (root[version], leftBound, rightBound) << "\n";
}
else
std::cout << "Unknown Type! Only add and ask allowed\n";
}
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree.java | // Part of Cosmos by OpenGenus Foundation
// Java Program to show segment tree operations like construction, query and update
class SegmentTree {
int st[]; // The array that stores segment tree nodes
SegmentTree(int arr[], int n) {
// Allocate memory for segment tree
//Height of segment tree
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
//Maximum size of segment tree
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // Memory allocation
constructSTUtil(arr, 0, n - 1, 0);
}
// A utility function to get the middle index from corner indexes.
int getMid(int s, int e) {
return s + (e - s) / 2;
}
int getSumUtil(int ss, int se, int qs, int qe, int si) {
// If segment of this node is a part of given range, then return
// the sum of the segment
if (qs <= ss && qe >= se)
return st[si];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return getSumUtil(ss, mid, qs, qe, 2 * si + 1) +
getSumUtil(mid + 1, se, qs, qe, 2 * si + 2);
}
void updateValueUtil(int ss, int se, int i, int diff, int si) {
// Base Case: If the input index lies outside the range of
// this segment
if (i < ss || i > se)
return;
// If the input index is in range of this node, then update the
// value of the node and its children
st[si] = st[si] + diff;
if (se != ss) {
int mid = getMid(ss, se);
updateValueUtil(ss, mid, i, diff, 2 * si + 1);
updateValueUtil(mid + 1, se, i, diff, 2 * si + 2);
}
}
void updateValue(int arr[], int n, int i, int new_val) {
// Check for erroneous input index
if (i < 0 || i > n - 1) {
System.out.println("Invalid Input");
return;
}
// Get the difference between new value and old value
int diff = new_val - arr[i];
// Update the value in array
arr[i] = new_val;
// Update the values of nodes in segment tree
updateValueUtil(0, n - 1, i, diff, 0);
}
// Return sum of elements in range from index qs (quey start) to
// qe (query end). It mainly uses getSumUtil()
int getSum(int n, int qs, int qe) {
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
return -1;
}
return getSumUtil(0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for array[ss..se].
// si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int si) {
// If there is one element in array, store it in current node of
// segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the sum of values in this node
int mid = getMid(ss, se);
st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) +
constructSTUtil(arr, mid + 1, se, si * 2 + 2);
return st[si];
}
// Driver program to test above functions
public static void main(String args[]) {
int arr[] = {1, 3, 5, 7, 9, 11};
int n = arr.length;
SegmentTree tree = new SegmentTree(arr, n);
// Build segment tree from given array
// Print sum of values in array from index 1 to 3
System.out.println("Sum of values in given range = " + tree.getSum(n, 1, 3));
// Update: set arr[1] = 10 and update corresponding segment
// tree nodes
tree.updateValue(arr, n, 1, 10);
// Find sum after the value is updated
System.out.println("Updated sum of values in given range = " +
tree.getSum(n, 1, 3));
}
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree.scala | import scala.reflect.ClassTag
case class SegmentTree[T: ClassTag](input: Array[T], aggregator: (T, T) => T) {
val maxArraySize = Math.pow(2.0, Math.ceil(Math.log(input.length) / Math.log(2.0))).toInt * 2 - 1
val treeArray = populateTree((0, input.length - 1), Array.ofDim[T](maxArraySize), 0)
def leftChild(index: Int) = index * 2 + 1
def rightChild(index: Int) = index * 2 + 2
def midIndex(left: Int, right: Int) = left + (right - left) / 2
def populateTree(inputRange: (Int, Int), treeArray: Array[T], treeIndex: Int): Array[T] = {
assert(inputRange._1 <= inputRange._2)
if (inputRange._1 == inputRange._2) {
treeArray(treeIndex) = input(inputRange._1)
}
else {
val mid = midIndex(inputRange._1, inputRange._2)
populateTree((inputRange._1, mid), treeArray, leftChild(treeIndex))
populateTree((mid + 1, inputRange._2), treeArray, rightChild(treeIndex))
treeArray(treeIndex) = aggregator(treeArray(leftChild(treeIndex)), treeArray(rightChild(treeIndex)))
}
treeArray
}
def getAggregate(start: Int, end: Int): T = {
assert(start <= end)
getAggregate(0, input.length - 1, start, end, 0)
}
def getAggregate(start: Int, end: Int, queryStart: Int, queryEnd: Int, treeIndex: Int): T = {
// Query range entirely inside of range
// println(s"segment range: ${start}, ${end}")
// println(s"query range: ${queryStart}, ${queryEnd}")
if (queryStart <= start && queryEnd >= end) {
// println("returning single node value")
treeArray(treeIndex)
}
else {
val mid = midIndex(start, end)
// println(s"${start}, ${mid}, ${end}")
if (mid < queryStart) {
// Query range starts after mid, throw out left half
getAggregate(mid + 1, end, queryStart, queryEnd, rightChild(treeIndex))
}
else if (queryEnd < mid + 1) {
// Query range ends beefore mid, throw out right half
getAggregate(start, mid, queryStart, queryEnd, leftChild(treeIndex))
}
else {
aggregator(
getAggregate(start, mid, queryStart, queryEnd, leftChild(treeIndex)),
getAggregate(mid + 1, end, queryStart, queryEnd, rightChild(treeIndex)))
}
}
}
def update(index: Int, value: T): Unit = {
update((0, treeArray.length - 1), index, value, 0)
}
def update(inputRange: (Int, Int), index: Int, value: T, treeIndex: Int): Unit = {
if (inputRange._1 == inputRange._2) {
assert(index == inputRange._1)
treeArray(treeIndex) = value
}
else {
val mid = midIndex(inputRange._1, inputRange._2)
if (index <= mid) {
update((inputRange._1, mid), index, value, leftChild(treeIndex))
}
else {
update((mid + 1, inputRange._2), index, value, rightChild(treeIndex))
}
treeArray(treeIndex) = aggregator(treeArray(leftChild(treeIndex)), treeArray(rightChild(treeIndex)))
}
}
}
object Main {
def main(args: Array[String]): Unit = {
val segTree = SegmentTree[Int](Array(1, 2, -3, 4, 5), (x: Int, y: Int) => Math.min(x, y))
println(segTree.getAggregate(0, 13))
val sumTree = SegmentTree[Int](Array(1, 2, -3, 4, 5), (x: Int, y: Int) => x + y)
println(sumTree.getAggregate(1, 3))
}
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_kth_statistics_on_segment.cpp | #include <cassert>
#include <iostream>
#include <vector>
using namespace std;
const int lb = -1e9, rb = 1e9;
struct node
{
int val;
node *l, *r;
node()
{
val = 0;
l = r = nullptr;
}
node(int x)
{
val = x;
l = r = nullptr;
}
node(node* vl, node* vr)
{
l = vl;
r = vr;
if (l)
val += l->val;
if (r)
val += r->val;
}
};
vector<node*> tr;
int cnt(node* v)
{
return v ? v->val : 0;
}
node* add_impl(node* v, int tl, int tr, int x)
{
if (tl == tr)
return new node(cnt(v) + 1);
else
{
int tm = (tl + tr) / 2;
if (x <= tm)
return new node(add_impl(v ? v->l : v, tl, tm, x), v ? v->r : v);
else
return new node(v ? v->l : v,
add_impl(v ? v->r : v, tm + 1, tr, x));
}
}
void add(int x)
{
node* v = tr.back();
tr.push_back(add_impl(v, lb, rb, x));
}
int order_of_key_impl(node* v, int tl, int tr, int l, int r)
{
if (!v)
return 0;
if (l == tl && r == tr)
return v->val;
int tm = (tl + tr) / 2;
if (r <= tm)
return order_of_key_impl(v->l, tl, tm, l, r);
else
return order_of_key_impl(v->l, tl, tm, l, tm) +
order_of_key_impl(v->r, tm + 1, tr, tm + 1, r);
}
int order_of_key(int l, int r, int x)
{
int ans = order_of_key_impl(tr[r], lb, rb, lb, x - 1) -
order_of_key_impl(tr[l - 1], lb, rb, lb, x - 1) + 1;
return ans;
}
int find_by_order_impl(node* l, node* r, int tl, int tr, int x)
{
if (tl == tr)
return tl;
int tm = (tl + tr) / 2;
if (cnt(r ? r->l : r) - cnt(l ? l->l : l) >= x)
return find_by_order_impl(l ? l->l : l, r ? r->l : r, tl, tm, x);
else
return find_by_order_impl(l ? l->r : l, r ? r->r : r, tm + 1, tr,
x - (cnt(r ? r->l : r) - cnt(l ? l->l : l)));
}
int find_by_order(int l, int r, int x)
{
assert(r - l + 1 >= x && x > 0);
return find_by_order_impl(tr[l - 1], tr[r], lb, rb, x);
}
int main()
{
tr.push_back(nullptr);
vector<int> a;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
a.push_back(x);
add(x);
}
int q;
cin >> q;
for (int i = 0; i < q; i++)
{
int t; // type of question: 1 - order of key, 2 - find by order
cin >> t;
int l, r, x; // 1 <= l <= r <= n
cin >> l >> r >> x;
if (t == 1)
cout << order_of_key(l, r, x) << endl;
else
cout << find_by_order(l, r, x) << endl;
}
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_lazy_propagation.cpp | // Part of Cosmos by OpenGenus Foundation
#include <iostream>
using namespace std;
#define N 10000000
int tree[N + 1], lazy[N + 1], A[N];
void build(int node, int start, int end)
{
if (start == end)
// Leaf node will have a single element
tree[node] = A[start];
else
{
int mid = (start + end) / 2;
// Recurse on the left child
build(2 * node, start, mid);
// Recurse on the right child
build(2 * node + 1, mid + 1, end);
// Internal node will have the sum of both of its children
tree[node] = tree[2 * node] + tree[2 * node + 1];
}
}
void updateRange(int node, int start, int end, int l, int r, int val)
{
if (lazy[node] != 0)
{
// This node needs to be updated
tree[node] += (end - start + 1) * lazy[node]; // Update it
if (start != end)
{
lazy[node * 2] += lazy[node]; // Mark child as lazy
lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy
}
lazy[node] = 0; // Reset it
}
if (start > end or start > r or end < l) // Current segment is not within range [l, r]
return;
if (start >= l and end <= r)
{
// Segment is fully within range
tree[node] += (end - start + 1) * val;
if (start != end)
{
// Not leaf node
lazy[node * 2] += val;
lazy[node * 2 + 1] += val;
}
return;
}
int mid = (start + end) / 2;
updateRange(node * 2, start, mid, l, r, val); // Updating left child
updateRange(node * 2 + 1, mid + 1, end, l, r, val); // Updating right child
tree[node] = tree[node * 2] + tree[node * 2 + 1]; // Updating root with max value
}
int queryRange(int node, int start, int end, int l, int r)
{
//cout<<endl<<node<<" "<<start<<" "<<end; For Debuging Purpose
if (start > end or start > r or end < l)
return 0; // Out of range
if (lazy[node] != 0)
{
// This node needs to be updated
tree[node] += (end - start + 1) * lazy[node]; // Update it
if (start != end)
{
lazy[node * 2] += lazy[node]; // Mark child as lazy
lazy[node * 2 + 1] += lazy[node]; // Mark child as lazy
}
lazy[node] = 0; // Reset it
}
if (start >= l and end <= r) // Current segment is totally within range [l, r]
//cout<<"tree"<<node<<" "<<tree[node]<<" ";
return tree[node];
int mid = (start + end) / 2;
int p1 = queryRange(node * 2, start, mid, l, r); // Query left child
int p2 = queryRange(node * 2 + 1, mid + 1, end, l, r); // Query right child
return p1 + p2;
}
int main()
{
fill(lazy, lazy + N + 1, 0);
fill(tree, tree + N + 1, 0);
for (int i = 0; i < 10; i++)
A[i] = 1;
build(1, 0, 9);
cout << queryRange(1, 0, 9, 3, 9);
updateRange(1, 0, 9, 3, 7, 1);
cout << endl
<< queryRange(1, 0, 9, 3, 9);
return 0;
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.adb | with Ada.Integer_Text_IO, Ada.Text_IO;
use Ada.Integer_Text_IO, Ada.Text_IO;
-- Compile:
-- gnatmake segment_Tree_rmq
procedure segment_Tree_rmq is
INT_MAX: constant integer := 999999;
MAXN : constant integer := 100005;
v : array(0..MAXN) of integer;
tree: array(0..4*MAXN) of integer;
n : integer;
q : integer;
a : integer;
b : integer;
c : integer;
function min(a: integer; b: integer) return integer is
begin
if a < b then return a;
else return b;
end if;
end min;
procedure build(node: integer; l: integer; r: integer) is
mid: integer;
begin
mid := (l + r)/2;
if l = r then
tree(node) := v(l);
return;
end if;
build(2 * node, l, mid);
build(2*node+1,mid+1,r);
tree(node) := min( tree(2*node), tree(2*node + 1));
end build;
--Update procedure
procedure update(node: integer; l: integer; r: integer; pos: integer; val: integer) is
mid: integer := (l + r)/2;
begin
if l > pos or r < pos or l > r then
return;
end if;
if(l = r) then
tree(node) := val;
return;
end if;
if pos <= mid then
update(2*node,l,mid,pos,val);
else
update(2*node+1,mid+1,r,pos,val);
end if;
tree(node) := min( tree(2*node), tree(2*node + 1));
end update;
--Query function
function query(node : integer; l: integer; r: integer; x: integer; y: integer) return integer is
mid: integer := (l + r)/2;
p1: integer;
p2: integer;
begin
if l > r or l > y or r < x then
return INT_MAX;
end if;
if x <= l and r <= y then
return tree(node);
end if;
p1 := query(2*node,l,mid,x,y);
p2 := query(2*node+1,mid+1,r,x,y);
if p1 = INT_MAX then
return p2;
end if;
if p2 = INT_MAX then
return p1;
end if;
return min(p1, p2);
end query;
begin
Put_Line("Input the array range");
Get(n);
Put_Line("Input the values");
for i in 1..n loop
Get(v(i));
end loop;
build(1,0,n-1);
Put_Line("Input the number of operations");
Get(q);
while q > 0 loop
Put_Line("Input 0 to query and 1 to update");
Get(a);
Put_Line("Input the STARTING index of the query range");
Get(b);
Put_Line("Input the ENDING index of the query range");
Get(c);
if a = 0 then
Put_Line("Minimum value of the given range");
Put(query(1,1,n,b,c));
Put_Line("");
elsif a = 1 then
update(1,1,n,b,c);
else
Put_Line("Invalid Operation");
q := q + 1;
end if;
q := q - 1;
end loop;
end segment_Tree_rmq;
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.cpp | /* Name: Mohit Khare
* B.Tech 2nd Year
* Computer Science and Engineering
* MNNIT Allahabad
*/
#include <cstdio>
#include <climits>
#define min(a, b) ((a) < (b) ? (a) : (b))
using namespace std;
typedef long long int ll;
#define mod 1000000007
const int maxn = 1e5 + 1;
void build(ll segtree[], ll arr[], int low, int high, int pos)
{
if (low == high)
{
segtree[pos] = arr[low];
return;
}
int mid = (low + high) / 2;
build(segtree, arr, low, mid, 2 * pos + 1);
build(segtree, arr, mid + 1, high, 2 * pos + 2);
segtree[pos] = min(segtree[2 * pos + 2], segtree[2 * pos + 1]);
}
ll query(ll segtree[], ll arr[], int low, int high, int qs, int qe, int pos)
{
if (qe < low || qs > high)
return LLONG_MAX;
if (qs <= low && high <= qe)
return segtree[pos];
int mid = (low + high) / 2;
ll left = query(segtree, arr, low, mid, qs, qe, 2 * pos + 1);
ll right = query(segtree, arr, mid + 1, high, qs, qe, 2 * pos + 2);
return min(right, left);
}
int main()
{
int n, m;
printf("Input no of input elements and no. of queries\n");
scanf("%d %d", &n, &m);
ll segtree[4 * n], arr[n];
printf("Input Array elements\n");
for (int i = 0; i < n; i++)
scanf("%lld", &arr[i]);
build(segtree, arr, 0, n - 1, 0);
for (int i = 0; i < m; i++)
{
int l, r;
printf("Enter range - l and r\n");
scanf("%d %d", &l, &r);
l--; r--;
printf("Result is :%lld\n", query(segtree, arr, 0, n - 1, l, r, 0));
}
return 0;
}
/* Test Case
*
* 5 2
* Input Array elements
* 3 4 2 1 5
* 1 2
* Result is :3
* 2 5
* Result is :1
*
*/
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.go | /*
* Segment Tree
* Update: 1 point
* Query: Range
* Query Type: Range Minimum Query
*/
package main
import "fmt"
type SegmentTree struct {
N int
tree []int
}
func Min(x int, y int) int {
if x < y {
return x
}
return y
}
func (stree *SegmentTree) Initialize(n int) {
stree.N = n
stree.tree = make([]int, 4*n)
}
func (stree *SegmentTree) build(arr []int, idx int, l int, r int) {
if l == r {
stree.tree[idx] = arr[l]
return
}
mid := (l + r) / 2
stree.build(arr, 2*idx+1, l, mid)
stree.build(arr, 2*idx+2, mid+1, r)
stree.tree[idx] = Min(stree.tree[2*idx+1], stree.tree[2*idx+2])
}
func (stree *SegmentTree) Build(arr []int) {
stree.build(arr, 0, 0, stree.N-1)
}
func (stree *SegmentTree) update(idx int, l int, r int, pos int, val int) {
if l == r {
stree.tree[idx] = val
return
}
mid := (l + r) / 2
if pos <= mid {
stree.update(2*idx+1, l, mid, pos, val)
} else {
stree.update(2*idx+2, mid+1, r, pos, val)
}
stree.tree[idx] = Min(stree.tree[2*idx+1], stree.tree[2*idx+2])
}
func (stree *SegmentTree) Update(pos int, val int) {
stree.update(0, 0, stree.N-1, pos, val)
}
func (stree *SegmentTree) query(idx int, l int, r int, ql int, qr int) int {
if ql <= l && r <= qr {
return stree.tree[idx]
}
mid := (l + r) / 2
minLeft := 1<<31 - 1
minRight := 1<<31 - 1
if ql <= mid {
minLeft = stree.query(2*idx+1, l, mid, ql, qr)
}
if qr > mid {
minRight = stree.query(2*idx+2, mid+1, r, ql, qr)
}
return Min(minLeft, minRight)
}
func (stree *SegmentTree) Query(ql int, qr int) int {
return stree.query(0, 0, stree.N-1, ql, qr)
}
func main() {
arr := []int{1, 2, 3, 4, 5}
n := len(arr)
var stree SegmentTree
stree.Initialize(n)
stree.Build(arr)
fmt.Printf("RMQ from 2 to 4: %v\n", stree.Query(1, 3))
fmt.Printf("RMQ from 1 to 5: %v\n", stree.Query(0, 4))
stree.Update(2, 7)
fmt.Println("Change to 7")
fmt.Printf("RMQ from 3 to 5: %v\n", stree.Query(2, 4))
fmt.Printf("RMQ from 1 to 5: %v\n", stree.Query(0, 4))
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.py | import math
def update(tree, l, r, node, index, diff):
if l == r:
tree[node] = diff
return tree[l]
mid = l + (r - l) // 2
if index <= mid:
update(tree, l, mid, (2 * node) + 1, index, diff)
tree[node] = min(tree[node * 2 + 2], tree[node * 2 + 1])
return diff
else:
update(tree, mid + 1, r, (2 * node) + 2, index, diff)
tree[node] = min(tree[node * 2 + 2], tree[node * 2 + 1])
def query(tree, l, r, x, y, node):
if l == x and r == y:
return tree[node]
mid = l + (r - l) // 2
if x <= mid and y <= mid:
return query(tree, l, mid, x, y, (2 * node) + 1)
elif x > mid and y > mid:
return query(tree, mid + 1, r, x, y, (2 * node) + 2)
elif x <= mid and y > mid:
left = query(tree, l, mid, x, mid, (2 * node) + 1)
right = query(tree, mid + 1, r, mid + 1, y, (2 * node) + 2)
return min(left, right)
def buildtree(tree, l, r, arr, node):
if l == r:
tree[node] = arr[l]
return arr[l]
mid = l + (r - l) // 2
left = buildtree(tree, l, mid, arr, (2 * node) + 1)
right = buildtree(tree, mid + 1, r, arr, (2 * node) + 2)
tree[node] = min(left, right)
return tree[node]
n, que = map(
int, input("Input total no. elements in array and No. of query :").split(" ")
)
print("Input elements of the array : ")
arr = list(map(int, input().split(" ")))
x = math.ceil(math.log(n, 2))
totnodes = (2 * (2 ** (x + 1))) - 1
tree = [None for i in range(totnodes)]
buildtree(tree, 0, n - 1, arr, 0)
for i in range(que):
print("If you want to find query press 'q' with left and right index.")
print(
"If you want to update the array, press 'u' with index and value for the update."
)
q, x, y = input().split(" ")
x = int(x) - 1
y = int(y) - 1
if q == "q":
print("Minimum in the given range is " + str(query(tree, 0, n - 1, x, y, 0)))
elif q == "u":
y += 1
diff = arr[x]
arr[x] = y
update(tree, 0, n - 1, 0, x, y)
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq_with_update.cpp | /* Part of Cosmos by OpenGenus Foundation */
/*
* Processes range minimum query.
* Query function returns index of minimum element in given interval.
* Code assumes that length of array can be contained into integer.
*/
#include <iostream>
#include <utility>
#include <vector>
struct Node
{
// store the data in variable value
int index;
// store the interval in a pair of integers
std::pair<int, int> interval;
Node *left;
Node *right;
};
// update adds new value to array[x] rather than replace it
class SegmentTree {
private:
Node *root;
int build(std::vector<int> &array, Node *node, int L, int R)
{
node->interval = std::make_pair(L, R);
if (L == R)
{
node->index = L;
return node->index;
}
node->left = new Node;
node->right = new Node;
int leftIndex = build(array, node->left, L, (L + R) / 2);
int rightIndex = build(array, node->right, (L + R) / 2 + 1, R);
node->index = (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex;
return node->index;
}
// returns the index of smallest element in the range [start, end]
int query(Node *node, int start, int end)
{
if (start > end)
return -1;
int L = node->interval.first;
int R = node->interval.second;
if (R < start || L > end)
return -1;
if (start <= L && end >= R)
return node->index;
int leftIndex = query(node->left, start, end);
int rightIndex = query(node->right, start, end);
if (leftIndex == -1)
return rightIndex;
if (rightIndex == -1)
return leftIndex;
return (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex;
}
void update(Node *node, int x, int value)
{
int L = node->interval.first;
int R = node->interval.second;
if (L == R)
{
array[L] += value;
return;
}
if (L <= x && (L + R) / 2 >= x)
// x is in left subtree
update(node->left, x, value);
else
// x is in right subtree
update(node->right, x, value);
int leftIndex = node->left->index;
int rightIndex = node->right->index;
//update current node
node->index = (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex;
}
// To clear allocated memory at end of program
void clearMem(Node *node)
{
int L = node->interval.first;
int R = node->interval.second;
if (L != R)
{
clearMem(node->left);
clearMem(node->right);
}
delete node;
}
public:
std::vector<int> array;
SegmentTree(std::vector<int> &ar)
{
array = ar;
root = new Node;
build(ar, root, 0, ar.size() - 1);
}
int query(int L, int R)
{
return query(root, L, R);
}
void update(int pos, int value)
{
return update(root, pos, value);
}
~SegmentTree()
{
clearMem(root);
}
};
int main()
{
// define n and array
int n = 8;
std::vector<int> array = {5, 4, 3, 2, 1, 0, 7, 0};
SegmentTree st(array);
std::cout << "Array:\n";
for (int i = 0; i < n; ++i)
std::cout << st.array[i] << ' ';
std::cout << '\n';
// sample query
std::cout << "The smallest element in the interval [1, 6] is "
<< array[st.query(0, 5)] << '\n'; // since array is 0 indexed.
// change 0 at index 5 to 8
st.update(5, 8);
array[5] += 8;
std::cout << "After update, array:\n";
for (int i = 0; i < n; ++i)
std::cout << st.array[i] << ' ';
std::cout << '\n';
std::cout << "The smallest element in the interval [1, 6] after update is "
<< array[st.query(0, 5)] << '\n';
return 0;
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_sum.cpp | // Segment tree with spaces. Allows to find sum in O(log size) time. Uses O(n log size) memory.
#include <iostream>
#include <string>
const int size = 1000000000;
struct node
{
int leftBound, rightBound;
node *leftChild, *rightChild;
int value;
node (int LeftBound, int RightBound)
{
leftBound = LeftBound;
rightBound = RightBound;
value = 0;
leftChild = rightChild = 0;
}
} *root;
void add (node *vertex, int destination, int value)
{
if (vertex->leftBound == destination && vertex->rightBound == destination + 1)
{
vertex->value += value;
return;
}
vertex->value += value;
int middle = (vertex->leftBound + vertex->rightBound) / 2;
if (destination < middle)
{
if (vertex->leftChild == 0)
vertex->leftChild = new node (vertex->leftBound, middle);
add (vertex->leftChild, destination, value);
}
else
{
if (vertex->rightChild == 0)
vertex->rightChild = new node (middle, vertex->rightBound);
add (vertex->rightChild, destination, value);
}
}
int ask (node *vertex, int leftBound, int rightBound)
{
if (vertex == 0)
return 0;
if (vertex->leftBound >= leftBound && vertex->rightBound <= rightBound)
return vertex->value;
if (vertex->leftBound >= rightBound && vertex->rightBound <= leftBound)
return 0;
return ask (vertex->leftChild, leftBound, rightBound) + ask (vertex->rightChild, leftBound,
rightBound);
}
int main ()
{
root = new node (-size, size); // Actually allows negative numbers
std::cout << "Print number of queries!\n";
int q;
std::cin >> q;
for (int _ = 0; _ < q; _++)
{
std::string type;
std::cin >> type;
if (type == "add")
{
int destination, value;
std::cin >> destination >> value;
add (root, destination, value);
std::cout << "Added succesfully!\n";
}
else if (type == "ask")
{
int leftBound, rightBound;
std::cin >> leftBound >> rightBound;
std::cout << ask (root, leftBound, rightBound) << "\n";
}
else
std::cout << "Unknown Type! Only add and ask allowed\n";
}
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_sum.go | /*
* Segment Tree
* Update: 1 point
* Query: Range
* Query Type: Range Sum Query
*/
package main
import "fmt"
type SegmentTree struct {
N int
tree []int
}
func (stree *SegmentTree) Initialize(n int) {
stree.N = n
stree.tree = make([]int, 4*n)
}
func (stree *SegmentTree) build(arr []int, idx int, l int, r int) {
if l == r {
stree.tree[idx] = arr[l]
return
}
mid := (l + r) / 2
stree.build(arr, 2*idx+1, l, mid)
stree.build(arr, 2*idx+2, mid+1, r)
stree.tree[idx] = stree.tree[2*idx+1] + stree.tree[2*idx+2]
}
func (stree *SegmentTree) Build(arr []int) {
stree.build(arr, 0, 0, stree.N-1)
}
func (stree *SegmentTree) update(idx int, l int, r int, pos int, val int) {
if l == r {
stree.tree[idx] = val
return
}
mid := (l + r) / 2
if pos <= mid {
stree.update(2*idx+1, l, mid, pos, val)
} else {
stree.update(2*idx+2, mid+1, r, pos, val)
}
stree.tree[idx] = stree.tree[2*idx+1] + stree.tree[2*idx+2]
}
func (stree *SegmentTree) Update(pos int, val int) {
stree.update(0, 0, stree.N-1, pos, val)
}
func (stree *SegmentTree) query(idx int, l int, r int, ql int, qr int) int {
if ql <= l && r <= qr {
return stree.tree[idx]
}
mid := (l + r) / 2
left := 0
right := 0
if ql <= mid {
left = stree.query(2*idx+1, l, mid, ql, qr)
}
if qr > mid {
right = stree.query(2*idx+2, mid+1, r, ql, qr)
}
return left + right
}
func (stree *SegmentTree) Query(ql int, qr int) int {
return stree.query(0, 0, stree.N-1, ql, qr)
}
func main() {
arr := []int{1, 2, 3, 4, 5}
n := len(arr)
var stree SegmentTree
stree.Initialize(n)
stree.Build(arr)
fmt.Printf("RSQ from 2 to 4: %v\n", stree.Query(1, 3))
fmt.Printf("RSQ from 1 to 5: %v\n", stree.Query(0, 4))
stree.Update(2, 7)
fmt.Println("Change to 7")
fmt.Printf("RSQ from 3 to 5: %v\n", stree.Query(2, 4))
fmt.Printf("RSQ from 1 to 5: %v\n", stree.Query(0, 4))
}
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_sum.py | # Part of Cosmos by OpenGenus Foundation
class SegmentTree:
def __init__(self, arr):
self.n = len(arr) # number of elements in array
self.arr = arr # stores given array
self.segtree = [0] * (
4 * self.n
) # stores segment tree, space required is 4 * (number of elements in array)
self.build(0, 0, self.n - 1)
def build(self, node, i, j): # Time Complexity: O(n)
if i == j:
# Leaf node
self.segtree[node] = self.arr[i]
return
# Recurse on left and right children
mid = i + (j - i) / 2
left = 2 * node + 1 # left child index
right = 2 * node + 2 # right child index
self.build(left, i, mid)
self.build(right, mid + 1, j)
# Internal node will be the sum of its two children
self.segtree[node] = self.segtree[left] + self.segtree[right]
def queryHelper(self, node, i, j, lo, hi):
if j < lo or i > hi:
# range represented by a node is completely outside the given range
return 0
if lo <= i and j <= hi:
# range represented by a node is completely inside the given range
return self.segtree[node]
# range represented by a node is partially inside and partially outside the given range
mid = i + (j - i) / 2
left = 2 * node + 1 # left child index
right = 2 * node + 2 # right child index
q1 = self.queryHelper(left, i, mid, lo, hi)
q2 = self.queryHelper(right, mid + 1, j, lo, hi)
return q1 + q2
# wrapper to queryHelper
def query(self, i, j): # Time Complexity: O(log n)
return self.queryHelper(0, 0, self.n - 1, i, j)
def updateHelper(self, node, i, j, idx, val):
if i == j:
# Leaf Node
self.arr[i] += val
self.segtree[node] += val
return
mid = i + (j - i) / 2
left = 2 * node + 1 # left child index
right = 2 * node + 2 # right child index
if i <= idx and idx <= mid:
# update in left child
self.updateHelper(left, i, mid, idx, val)
else:
# update in right child
self.updateHelper(right, mid + 1, j, idx, val)
# update internal nodes
self.segtree[node] = self.segtree[left] + self.segtree[right]
# wrapper to updateHelper
def update(self, idx, val): # Time Complexity: O(log n)
self.updateHelper(0, 0, self.n - 1, idx, val)
arr = [1, 2, 3, -1, 5]
tree = SegmentTree(arr)
tree.update(3, 5) # arr[3] = 4
print(tree.query(0, 3))
|
code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_sum.rb | # Part of Cosmos by OpenGenus Foundation
class SegTree
def initialize(arr)
@arr = arr
@end = arr.length - 1
@tree = Array.new(arr.length * 4, 0)
start(0, 0, @end)
end
def start(root, left, right)
if left == right
@tree[root] = @arr[left]
return 0
end
mid = (left + right) / 2
node_left = 2 * root + 1
node_right = node_left + 1
start(node_left, left, mid)
start(node_right, mid + 1, right)
@tree[root] = @tree[node_right] + @tree[node_left]
end
def query_helper(root, q_left, q_right, left, right)
if (q_left > right) || (q_right < left)
# range represented by a node is completely outside the given range
return 0
end
if (q_left <= left) && (q_right >= right)
# range represented by a node is completely inside the given range
return @tree[root]
end
mid = (left + right) / 2
left_node = 2 * root + 1
right_node = left_node + 1
left_sum = query_helper(left_node, q_left, q_right, left, mid)
right_sum = query_helper(right_node, q_left, q_right, mid + 1, right)
left_sum + right_sum
end
# wrapper to queryHelper
def query(query_left, query_right)
query_helper(0, query_left, query_right, 0, @end)
end
def update_helper(root, pos, value, left, right)
return if (pos < left) || (pos > right)
if left == right
@tree[root] = value
return
end
mid = (left + right) / 2
left_node = 2 * root + 1
right_node = left_node + 1
update_helper(left_node, pos, value, left, mid)
update_helper(right_node, pos, value, mid + 1, right)
# recursive update
@tree[root] = @tree[left_node] + @tree[right_node]
nil
end
# update wrapper
def update(pos, value)
update_helper(0, pos, value, 0, @end)
end
private :start, :query_helper, :update_helper
end
arr = [1, 2, -1, 4, 5]
seg_tree = SegTree.new arr
seg_tree.update 2, 3 # arr[2] = 5
p seg_tree.query 0, 4
|
code/data_structures/src/tree/tree/suffix_array/suffix_array.cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#define ll size_t
using namespace std;
struct ranking
{
ll index;
ll first;
ll second;
};
bool comp(ranking a, ranking b)
{
if (a.first == b.first)
return a.second < b.second;
return a.first < b.first;
}
vector<ll> build_suffix_array(string s)
{
const ll n = s.length();
const ll lgn = ceil(log2(n));
// vector to hold final suffix array result
vector<ll> sa(n);
// P[i][j] holds the ranking of the j-th suffix
// after comparing the first 2^i characters
// of that suffix
ll P[lgn][n];
// vector to store ranking tuples of suffixes
vector<ranking> ranks(n);
ll i, j, step = 1;
for (j = 0; j < n; j++)
P[0][j] = s[j] - 'a';
for (i = 1; i <= lgn; i++, step++)
{
for (j = 0; j < n; j++)
{
ranks[j].index = j;
ranks[j].first = P[i - 1][j];
ranks[j].second = (j + std::pow(2, i - 1) < n) ? P[i - 1][j + (ll)(pow(2, i - 1))] : -1;
}
std::sort(ranks.begin(), ranks.end(), comp);
for (j = 0; j < n; j++)
P[i][ranks[j].index] =
(j > 0 && ranks[j].first == ranks[j - 1].first &&
ranks[j].second == ranks[j - 1].second) ? P[i][ranks[j - 1].index] : j;
}
step -= 1;
for (i = 0; i < n; i++)
sa[P[step][i]] = i;
return sa;
}
int main()
{
string s;
cin >> s;
vector<ll> sa = build_suffix_array(s);
for (ll i = 0; i < s.length(); i++)
cout << i << " : " << sa[i] << endl;
return 0;
}
|
code/data_structures/src/tree/tree/trie/README.md | # Trie
Description
---
In computer science, also called digital tree and sometimes radix tree or prefix tree
(as they can be searched by prefixes),
is a kind of search tree -- an ordered tree data structure that is used to store a
dynamic set or associative array where the keys are usually strings.
Trie API
---
- insert(text): Insert a text node into the trie.
- contains(text) or search(text): Return true trie contains text otherwise return false
- delete(text): Insert a text node from the trie if exists.
Complexity
---
Insert and search costs O(key_length),
however the memory requirements of Trie is
O(ALPHABET_SIZE * key_length * N)
where N is number of keys in Trie.
|
code/data_structures/src/tree/tree/trie/trie.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// Part of Cosmos by OpenGenus Foundation
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#define ALPHABET_SIZE (26)
#define INDEX(c) ((int)c - (int)'a')
#define FREE(p) \
free(p); \
p = NULL;
typedef struct trie_node trie_node_t;
struct trie_node
{
int value; // non zero if leaf
trie_node_t *children[ALPHABET_SIZE];
};
typedef struct trie trie_t;
struct trie
{
trie_node_t *root;
int count;
};
trie_node_t *getNode(void)
{
trie_node_t *pNode = NULL;
pNode = (trie_node_t *)malloc(sizeof(trie_node_t));
if( pNode )
{
int i;
pNode->value = 0;
for(i = 0; i < ALPHABET_SIZE; i++)
{
pNode->children[i] = NULL;
}
}
return pNode;
}
void initialize(trie_t *pTrie)
{
pTrie->root = getNode();
pTrie->count = 0;
}
void insert(trie_t *pTrie, char key[])
{
int level;
int length = strlen(key);
int index;
trie_node_t *pCrawl;
pTrie->count++;
pCrawl = pTrie->root;
for( level = 0; level < length; level++ )
{
index = INDEX(key[level]);
if( pCrawl->children[index] )
{
// Skip current node
pCrawl = pCrawl->children[index];
}
else
{
// Add new node
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
}
// mark last node as leaf (non zero)
pCrawl->value = pTrie->count;
}
int search(trie_t *pTrie, char key[])
{
int level;
int length = strlen(key);
int index;
trie_node_t *pCrawl;
pCrawl = pTrie->root;
for( level = 0; level < length; level++ )
{
index = INDEX(key[level]);
if( !pCrawl->children[index] )
{
return 0;
}
pCrawl = pCrawl->children[index];
}
return (0 != pCrawl && pCrawl->value);
}
int leafNode(trie_node_t *pNode)
{
return (pNode->value != 0);
}
int isItFreeNode(trie_node_t *pNode)
{
int i;
for(i = 0; i < ALPHABET_SIZE; i++)
{
if( pNode->children[i] )
return 0;
}
return 1;
}
bool deleteHelper(trie_node_t *pNode, char key[], int level, int len)
{
if( pNode )
{
// Base case
if( level == len )
{
if( pNode->value )
{
// Unmark leaf node
pNode->value = 0;
// If empty, node to be deleted
if( isItFreeNode(pNode) )
{
return true;
}
return false;
}
}
else // Recursive case
{
int index = INDEX(key[level]);
if( deleteHelper(pNode->children[index], key, level+1, len) )
{
// last node marked, delete it
FREE(pNode->children[index]);
// recursively climb up, and delete eligible nodes
return ( !leafNode(pNode) && isItFreeNode(pNode) );
}
}
}
return false;
}
void deleteKey(trie_t *pTrie, char key[])
{
int len = strlen(key);
if( len > 0 )
{
deleteHelper(pTrie->root, key, 0, len);
}
}
int main()
{
char keys[][8] = {"cat", "case", "deaf", "dear", "a", "an", "the"};
trie_t trie;
initialize(&trie);
for(int i = 0; i < ARRAY_SIZE(keys); i++)
{
insert(&trie, keys[i]);
}
deleteKey(&trie, keys[0]);
printf("%s %s\n", "cat", search(&trie, "cat") ? "Present in trie" : "Not present in trie");
return 0;
}
|
code/data_structures/src/tree/tree/trie/trie.cpp | #include <cstdio>
#include <string>
#include <iostream>
// Part of Cosmos by OpenGenus
using namespace std;
#define mod 1000000007
#define all(v) v.begin(), v.end_()
#define rep(i, a, b) for (i = (ll)a; i < (ll)b; i++)
#define revrep(i, a, b) for (i = (ll)a; i >= (ll)b; i--)
#define strep(it, v) for (it = v.begin(); it != v.end_(); ++it)
#define ii pair<ll, ll>
#define MP make_pair
#define pb push_back
#define f first
#define se second
#define ll long long int
#define vi vector<ll>
ll modexp(ll a, ll b)
{
ll res = 1; while (b > 0)
{
if (b & 1)
res = (res * a);
a = (a * a); b /= 2;
}
return res;
}
#define rs resize
long long readLI()
{
register char c; for (c = getchar(); !(c >= '0' && c <= '9'); c = getchar())
{
}
register long long a = c - '0';
for (c = getchar(); c >= '0' && c <= '9'; c = getchar())
a = (a << 3) + (a << 1) + c - '0';
return a;
}
const ll N = 100009;
int n, i, j, sz;
string a;
ll next_[27][N], end_[N];
void add(string a)
{
int v = 0;
for (int i = 0; i < (int)a.size(); i++)
{
int c = a[i] - 'a';
if (next_[c][v] == -1)
v = next_[c][v] = ++sz;
else
v = next_[c][v];
}
++end_[v];
}
bool search(string a)
{
int v = 0;
for (i = 0; i < (int)a.size(); i++)
{
int c = a[i] - 'a';
if (next_[c][v] == -1)
return false;
v = next_[c][v];
}
return end_[v] > 0;
}
int main()
{
std::ios_base::sync_with_stdio(false); cin.tie(NULL);
cin >> n;
rep(i, 0, 27) for (int j = 0; j < N; j++)
next_[i][j] = -1;
rep(i, 0, n) cin >> a, add(a);
cin >> n;
while (n--)
{
cin >> a;
cout << search(a) << endl;
}
return 0;
}
|
code/data_structures/src/tree/tree/trie/trie.cs | using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Abstractions;
namespace Cosmos
{
// XUnit test to test Trie data structure.
public class TriestTest
{
private readonly TrieBuilder _trieBuilder = new TrieBuilder();
public TriestTest(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void TestCreation()
{
//var words = new[] {"abc", "abgl", "cdf", "abcd", "lmn"};
var words = new[] {"abc", "abgl"};
TrieNode root = _trieBuilder.BuildTrie(words);
Console.WriteLine(root);
}
[Theory]
[MemberData(nameof(GetCompleteWordData))]
public void TestCompleteWordSearch(bool expected, string word, string[] source)
{
var trieNode = _trieBuilder.BuildTrie(source);
var sut = new Trie(trieNode);
var actual = sut.SearchCompleteWord(word);
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(GetPrefixData))]
public void TestPrefixWordSearch(bool expected, string prefix, string[] source)
{
var trieNode = _trieBuilder.BuildTrie(source);
var trie = new Trie(trieNode);
var actual = trie.SearchPrefix(prefix);
Assert.Equal(expected, actual);
}
public static IEnumerable<object[]> GetPrefixData()
{
yield return new object[] { true, "abc", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "ab", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "a", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "cdf", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "cd", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "c", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "x", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "abd", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "abx", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "cda", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "swyx", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
}
public static IEnumerable<object[]> GetCompleteWordData()
{
yield return new object[] { true, "abc", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "abgl", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "cdf", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "abcd", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { true, "lmn", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "ab", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "abg", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "cd", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "abcx", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "abglx", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "cdfx", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "abcdx", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
yield return new object[] { false, "lmnx", new[] { "abc", "abgl", "cdf", "abcd", "lmn" } };
}
}
public class Trie
{
public TrieNode Root { get; set; }
public Trie(TrieNode root)
{
Root = root;
}
/// <summary>
/// Search for a complete word, not a prefix search.
/// </summary>
public bool SearchCompleteWord(string word)
{
var current = Root;
foreach (char c in word)
{
if (current.Children.TryGetValue(c, out TrieNode node))
current = node;
else
return false;
}
return current.IsCompleteWord;
}
public bool SearchPrefix(string prefix)
{
if (string.IsNullOrWhiteSpace(prefix)) return false;
var current = Root;
foreach (char c in prefix)
{
if (current.Children.TryGetValue(c, out TrieNode node))
current = node;
else
return false;
}
return true;
}
}
public class TrieNode
{
public bool IsCompleteWord { get; set; } = false;
public Dictionary<char, TrieNode> Children { get; } = new Dictionary<char, TrieNode>();
}
/// <summary>
/// Based on https://www.youtube.com/watch?v=AXjmTQ8LEoI by Tushar Roy
/// </summary>
public class TrieBuilder
{
public TrieNode BuildTrie(IEnumerable<string> words)
{
TrieNode root = new TrieNode();
foreach (var word in words)
{
Insert(root, word);
}
return root;
}
private void Insert(TrieNode current, string word)
{
foreach (char c in word)
{
current.Children.TryGetValue(c, out TrieNode node);
if (node == null)
{
node = new TrieNode();
current.Children.Add(c, node);
}
current = node;
}
current.IsCompleteWord = true;
}
}
} |
code/data_structures/src/tree/tree/trie/trie.go | package main
import "fmt"
// TrieNode has a value and a pointer to another TrieNode
type TrieNode struct {
children map[rune]*TrieNode
value interface{}
}
// New allocates and returns a new *TrieNode.
func New() *TrieNode {
return &TrieNode{
children: make(map[rune]*TrieNode),
}
}
// Contains returns true trie contains text otherwise return false
func (trie *TrieNode) Contains(key string) bool {
node := trie
for _, ch := range key {
node = node.children[ch]
if node == nil {
return false
}
}
return node.value != nil
}
func (trie *TrieNode) Insert(key string, value int) bool {
node := trie
for _, ch := range key {
child, _ := node.children[ch]
if child == nil {
child = New()
node.children[ch] = child
}
node = child
}
isNewVal := node.value == nil
node.value = value
return isNewVal
}
// PathTrie node and the part string key of the child the path descends into.
type nodeStr struct {
node *TrieNode
part rune
}
func (trie *TrieNode) Delete(key string) bool {
var path []nodeStr // record ancestors to check later
node := trie
for _, ch := range key {
path = append(path, nodeStr{part: ch, node: node})
node = node.children[ch]
if node == nil {
// node does not exist
return false
}
}
// delete the node value
node.value = nil
// if leaf, remove it from its parent's children map. Repeat for ancestor path.
if len(node.children) == 0 {
// iterate backwards over path
for i := len(path) - 1; i >= 0; i-- {
parent := path[i].node
part := path[i].part
delete(parent.children, part)
if parent.value != nil || !(len(parent.children) == 0) {
// parent has a value or has other children, stop
break
}
}
}
return true
}
func main() {
keys := []string{"cat", "case", "deaf", "dear", "a", "an", "the"}
tr := New()
for i, key := range keys {
tr.Insert(key, i)
}
tr.Delete("dear")
var contains string
if tr.Contains("dear") {
contains = "contains"
} else {
contains = "does not contain"
}
fmt.Printf("Trie %v %v\n", contains, "dear")
if tr.Contains("case") {
contains = "contains"
} else {
contains = "does not contain"
}
fmt.Printf("Trie %v %v\n", contains, "case")
}
|
code/data_structures/src/tree/tree/trie/trie.java | // Part of Cosmos by OpenGenus Foundation
class TrieNode {
char c;
HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
boolean isEnd;
public TrieNode() {}
public TrieNode(char c){ this.c = c; }
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (!node.children.containsKey(c)) {
node.children.put(c,new TrieNode(c));
}
node = node.children.get(c);
}
node.isEnd = true;
}
// Returns true if the word is in the trie.
public boolean search(String word) {
TrieNode node = searchNode(word);
return (node == null) ? false : node.isEnd;
}
// Returns true if there is any word in the trie that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode node = searchNode(prefix);
return (node == null) ? false : true;
}
public TrieNode searchNode(String s) {
TrieNode node = root;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (node.children.containsKey(c)) {
node = node.children.get(c);
} else {
return null;
}
}
if (node == root) return null;
return node;
}
}
|
code/data_structures/src/tree/tree/trie/trie.js | /* Part of Cosmos by OpenGenus Foundation */
class Node {
constructor() {
this.keys = new Map();
this.end = false;
}
setEnd() {
this.end = true;
}
isEnd() {
return this.end;
}
}
class Trie {
constructor() {
this.root = new Node();
}
add(input, node = this.root) {
if (input.length === 0) {
node.setEnd();
return;
} else if (!node.keys.has(input[0])) {
node.keys.set(input[0], new Node());
return this.add(input.substr(1), node.keys.get(input[0]));
} else {
return this.add(input.substr(1), node.keys.get(input[0]));
}
}
isWord(word) {
let node = this.root;
while (word.length > 1) {
if (!node.keys.has(word[0])) {
return false;
} else {
node = node.keys.get(word[0]);
word = word.substr(1);
}
}
return node.keys.has(word) && node.keys.get(word).isEnd() ? true : false;
}
print() {
let words = [];
const search = function(node, string) {
if (node.keys.size !== 0) {
for (let letter of node.keys.keys()) {
search(node.keys.get(letter), string.concat(letter));
}
if (node.isEnd()) {
words.push(string);
}
} else {
string.length > 0 ? words.push(string) : undefined;
return;
}
};
search(this.root, "");
return words.length > 0 ? words : mo;
}
}
// Trie Examples
myTrie.add("cat");
myTrie.add("catch");
myTrie.add("dog");
myTrie.add("good");
myTrie.add("goof");
myTrie.add("jest");
myTrie.add("come");
myTrie.add("comedy");
myTrie.isWord("catc");
myTrie.isWord("jest");
myTrie.isWord("come");
myTrie.print();
|
code/data_structures/src/tree/tree/trie/trie.py | # An efficient information reTRIEval data structure
class TrieNode(object):
def __init__(self):
self.children = {}
def __repr__(self):
return str(self.children)
def insert(root_node, word):
n = root_node
for character in word:
t = n.children.get(character)
if not t:
t = TrieNode()
n.children[character] = t
n = t
def search(root_node, search_string):
node = root_node
for character in search_string:
c = node.children.get(character)
if not c:
return False
node = c
return True
root = TrieNode()
insert(root, "abc")
insert(root, "pqrs")
print(search(root, "abc")) # will print True
print(search(root, "xyz")) # will print False
|
code/data_structures/src/tree/tree/trie/trie.rb | class Trie
def insert(word)
return if word.empty?
first, rest = word.split(''.freeze, 2)
children[first].insert(rest)
end
def search(word)
return true if word.empty?
first, rest = word.split(''.freeze, 2)
children.key?(first) && children[first].search(rest)
end
private
def children
@children ||= Hash.new do |hash, character|
hash[character] = Trie.new
end
end
end
root = Trie.new
root.insert 'abc'
root.insert 'pqrs'
puts root.search('abc') # => true
puts root.search('xyz') # => false
|
code/data_structures/src/tree/tree/trie/trie.scala | import collection.immutable.IntMap
object Trie {
def apply(text: String): Trie = {
if (text == "") {
return new Trie(IntMap(), true)
} else {
return new Trie(IntMap(text.charAt(0).asInstanceOf[Int] -> apply(text.substring(1))), false)
}
}
}
case class Trie(kids: IntMap[Trie], isTerminalNode: Boolean) {
def insert(text: String): Trie = {
if (text == "") {
this.copy(isTerminalNode = true)
} else {
val firstLetterInt = text.charAt(0).asInstanceOf[Int]
val restOfText = text.substring(1)
val newKid =
if (kids.contains(firstLetterInt))
kids(firstLetterInt).insert(restOfText)
else
Trie(restOfText)
this.copy(kids = kids + (firstLetterInt -> newKid))
}
}
def hasText(text: String): Boolean = {
if (text == "") {
this.isTerminalNode
} else {
val firstLetterInt = text.charAt(0).asInstanceOf[Int]
kids.contains(firstLetterInt) && kids(firstLetterInt).hasText(text.substring(1))
}
}
def hasPrefix(prefix: String): Boolean = {
if (prefix == "") {
true
} else {
val firstLetterInt = prefix.charAt(0).asInstanceOf[Int]
kids.contains(firstLetterInt) && kids(firstLetterInt).hasPrefix(prefix.substring(1))
}
}
}
|
code/data_structures/src/tree/tree/trie/trie.swift | // Part of Cosmos by OpenGenus Foundation
import Foundation
class TrieNode<T: Hashable> {
var value: T?
weak var parentNode: TrieNode?
var children: [T: TrieNode] = [:]
var isTerminating = false
var isLeaf: Bool {
return children.count == 0
}
init(value: T? = nil, parentNode: TrieNode? = nil) {
self.value = value
self.parentNode = parentNode
}
func add(value: T) {
guard children[value] == nil else {
return
}
children[value] = TrieNode(value: value, parentNode: self)
}
}
class Trie: NSObject, NSCoding {
typealias Node = TrieNode<Character>
public var count: Int {
return wordCount
}
public var isEmpty: Bool {
return wordCount == 0
}
public var words: [String] {
return wordsInSubtrie(rootNode: root, partialWord: "")
}
fileprivate let root: Node
fileprivate var wordCount: Int
override init() {
root = Node()
wordCount = 0
super.init()
}
required convenience init?(coder decoder: NSCoder) {
self.init()
let words = decoder.decodeObject(forKey: "words") as? [String]
for word in words! {
self.insert(word: word)
}
}
func encode(with coder: NSCoder) {
coder.encode(self.words, forKey: "words")
}
}
extension Trie {
func insert(word: String) {
guard !word.isEmpty else {
return
}
var currentNode = root
for character in word.lowercased().characters {
if let childNode = currentNode.children[character] {
currentNode = childNode
} else {
currentNode.add(value: character)
currentNode = currentNode.children[character]!
}
}
guard !currentNode.isTerminating else {
return
}
wordCount += 1
currentNode.isTerminating = true
}
func contains(word: String) -> Bool {
guard !word.isEmpty else {
return false
}
var currentNode = root
for character in word.lowercased().characters {
guard let childNode = currentNode.children[character] else {
return false
}
currentNode = childNode
}
return currentNode.isTerminating
}
private func findLastNodeOf(word: String) -> Node? {
var currentNode = root
for character in word.lowercased().characters {
guard let childNode = currentNode.children[character] else {
return nil
}
currentNode = childNode
}
return currentNode
}
private func findTerminalNodeOf(word: String) -> Node? {
if let lastNode = findLastNodeOf(word: word) {
return lastNode.isTerminating ? lastNode : nil
}
return nil
}
private func deleteNodesForWordEndingWith(terminalNode: Node) {
var lastNode = terminalNode
var character = lastNode.value
while lastNode.isLeaf, let parentNode = lastNode.parentNode {
lastNode = parentNode
lastNode.children[character!] = nil
character = lastNode.value
if lastNode.isTerminating {
break
}
}
}
func remove(word: String) {
guard !word.isEmpty else {
return
}
guard let terminalNode = findTerminalNodeOf(word: word) else {
return
}
if terminalNode.isLeaf {
deleteNodesForWordEndingWith(terminalNode: terminalNode)
} else {
terminalNode.isTerminating = false
}
wordCount -= 1
}
fileprivate func wordsInSubtrie(rootNode: Node, partialWord: String) -> [String] {
var subtrieWords = [String]()
var previousLetters = partialWord
if let value = rootNode.value {
previousLetters.append(value)
}
if rootNode.isTerminating {
subtrieWords.append(previousLetters)
}
for childNode in rootNode.children.values {
let childWords = wordsInSubtrie(rootNode: childNode, partialWord: previousLetters)
subtrieWords += childWords
}
return subtrieWords
}
func findWordsWithPrefix(prefix: String) -> [String] {
var words = [String]()
let prefixLowerCased = prefix.lowercased()
if let lastNode = findLastNodeOf(word: prefixLowerCased) {
if lastNode.isTerminating {
words.append(prefixLowerCased)
}
for childNode in lastNode.children.values {
let childWords = wordsInSubtrie(rootNode: childNode, partialWord: prefixLowerCased)
words += childWords
}
}
return words
}
}
|
code/data_structures/src/tree/van_emde_boas_tree/van_emde_boas_tree.cpp | #include <bits/stdc++.h>
using namespace std;
class veb
{
int u;
int *min;
int *max;
veb *summary;
veb **cluster;
public:
veb(int u);
void insert(int x);
void remove(int x);
int* pred(int x);
int minimum();
int maximum();
};
veb :: veb(int u)
{
this->u = u;
this->min = NULL;
this->max = NULL;
if (u == 2)
{
this->summary = NULL;
this->cluster = NULL;
}
else
{
int sub_size = sqrt(u);
this->summary = new veb(sub_size);
this->cluster = new veb*[sub_size];
}
}
void veb::insert(int x)
{
if (u == 2)
{
if (x == 0)
{
if (max == NULL)
{
max = new int;
min = new int;
*max = x;
*min = x;
}
else
*min = x;
}
else if (x == 1)
{
if (min == NULL)
{
max = new int;
min = new int;
*max = x;
*min = x;
}
else
*max = x;
}
}
else
{
if (min == NULL)
{
min = new int;
max = new int;
*max = x;
*min = x;
this->insert(x);
}
else
{
if ((*min) > x)
{
*min = x;
this->insert(x);
}
else
{
int subsize = sqrt(u);
int high = x / subsize, low = x % subsize;
if (cluster[high] == NULL)
{
cluster[high] = new veb(subsize);
cluster[high]->insert(low);
summary->insert(high);
}
else
cluster[high]->insert(low);
if ((*max) < x)
*max = x;
}
}
}
}
void veb::remove(int x)
{
if (u == 2)
{
if (x == 0)
{
if (min != NULL)
{
if (*max == 0)
{
min = NULL;
max = NULL;
}
else
*min = 1;
}
}
else if (max != NULL)
{
if (*min == 1)
{
min = NULL;
max = NULL;
}
else
*max = 0;
}
}
else
{
int subsize = sqrt(u);
int high = x / subsize, low = x % subsize;
if (min == NULL || cluster[high] == NULL)
return;
if (x == *min)
{
if (x == *max)
{
min = NULL;
max = NULL;
cluster[high]->remove(low);
return;
}
cluster[high]->remove(low);
if (cluster[high]->min == NULL)
{
delete cluster[high];
cluster[high] = NULL;
summary->remove(high);
}
int newminhigh = summary->minimum();
int newminlow = cluster[newminhigh]->minimum();
*min = newminhigh * subsize + newminlow;
}
else
{
cluster[high]->remove(low);
if (cluster[high]->min == NULL)
{
delete cluster[high];
cluster[high] = NULL;
summary->remove(high);
}
if (x == *max)
{
int newmaxhigh = summary->maximum();
int newmaxlow = cluster[newmaxhigh]->maximum();
*max = newmaxhigh * subsize + newmaxlow;
}
}
}
}
int* veb::pred(int x)
{
if (u == 2)
{
if (x == 0)
return NULL;
else if (x == 1)
{
if (min == NULL)
return NULL;
else if ((*min) == 1)
return NULL;
else
return min;
}
else
return NULL;
}
else
{
if (min == NULL)
return NULL;
if ((*min) >= x)
return NULL;
if (x > (*max))
return max;
int subsize = sqrt(u);
int high = x / subsize;
int low = x % subsize;
if (cluster[high] == NULL)
{
int *pred = summary->pred(high);
int *ans = new int;
*ans = (*pred) * subsize + *(cluster[*pred]->max);
return ans;
}
else
{
int *ans_high = new int;
int *ans_low = new int;
if (low > *(cluster[high]->min))
{
*ans_high = high;
ans_low = cluster[high]->pred(low);
}
else
{
ans_high = summary->pred(high);
ans_low = cluster[(*ans_high)]->max;
}
int *ans = new int;
*ans = (*ans_high) * subsize + (*ans_low);
return ans;
}
}
}
int veb::minimum()
{
return *min;
}
int veb::maximum()
{
return *max;
}
void findpred(veb *x, int y)
{
int *temp = x->pred(y);
if (temp == NULL)
cout << "no predecesor" << endl;
else
cout << "predecesor of " << y << " is " << *temp << endl;
}
int main()
{
veb *x = new veb(16);
x->insert(2);
x->insert(3);
x->insert(4);
x->insert(5);
x->insert(7);
x->insert(14);
x->insert(15);
cout << x->minimum() << endl << x->maximum() << endl;
findpred(x, 0);
findpred(x, 1);
findpred(x, 2);
findpred(x, 3);
findpred(x, 4);
findpred(x, 5);
findpred(x, 6);
findpred(x, 7);
findpred(x, 8);
findpred(x, 9);
findpred(x, 10);
findpred(x, 11);
findpred(x, 12);
findpred(x, 13);
findpred(x, 14);
findpred(x, 15);
findpred(x, 16);
findpred(x, 7);
x->remove(15);
x->remove(5);
findpred(x, 0);
findpred(x, 1);
findpred(x, 2);
findpred(x, 3);
findpred(x, 4);
findpred(x, 5);
findpred(x, 6);
findpred(x, 7);
findpred(x, 8);
findpred(x, 9);
findpred(x, 10);
findpred(x, 11);
findpred(x, 12);
findpred(x, 13);
findpred(x, 14);
findpred(x, 15);
findpred(x, 16);
findpred(x, 7);
}
|
code/data_structures/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/data_structures/test/bag/test_bag.cpp | //Needed for random and vector
#include <vector>
#include <string>
#include <cstdlib>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
using std::vector;
//Bag Class Declaration
class Bag
{
private:
vector<string> items;
int bagSize;
public:
Bag();
void add(string);
bool isEmpty();
int sizeOfBag();
string remove();
};
Bag::Bag()
{
bagSize = 0;
}
void Bag::add(string item)
{
//Store item in last element of vector
items.push_back(item);
//Increase the size
bagSize++;
}
bool Bag::isEmpty(){
//True
if(bagSize == 0){
return true;
}
//False
else{
return false;
}
}
int Bag::sizeOfBag(){
return bagSize;
}
string Bag::remove(){
//Get random item
int randIndx = rand() % bagSize;
string removed = items.at(randIndx);
//Remove from bag
items.erase(items.begin() + randIndx);
bagSize--;
//Return removed item
return removed;
}
int main()
{
//Create bag
Bag bag;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
//Add some items
cout << "Adding red..." << endl;
bag.add("red");
cout << "Bag size: " << bag.sizeOfBag() << endl;
cout << "Adding blue..." << endl;
bag.add("blue");
cout << "Bag size: " << bag.sizeOfBag() << endl;
cout << "Adding yellow..." << endl;
bag.add("yellow");
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Remove an item
cout << "Removed " << bag.remove() << " from bag." << endl;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
//Remove an item
cout << "Removed " << bag.remove() << " from bag." << endl;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
//Remove last item
cout << "Removed " << bag.remove() << " from bag." << endl;
//Get current size
cout << "Bag size: " << bag.sizeOfBag() << endl;
//Bag empty?
cout << "Is bag empty? " << bag.isEmpty() << endl;
}
|
code/data_structures/test/list/test_list.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* test lists for std::list-like
*/
#define CATCH_CONFIG_MAIN
#ifndef XOR_LINKED_LIST_TEST_CPP
#define XOR_LINKED_LIST_TEST_CPP
#include "../../../../test/c++/catch.hpp"
#include "../../src/list/xor_linked_list/xor_linked_list.cpp"
#include <iostream>
#include <list>
#include <vector>
using vectorContainer = std::vector<int>;
using expectListContainer = std::list<int>;
using actualListContainer = XorLinkedList<int>;
static size_t RandomSize;
static size_t SmallRandomSize;
TEST_CASE("init")
{
srand(static_cast<unsigned int>(clock()));
RandomSize = 100000 + rand() % 2;
SmallRandomSize = RandomSize / rand() % 100 + 50;
}
vectorContainer getRandomValueContainer(size_t sz = RandomSize)
{
// init
vectorContainer container(sz);
size_t i = 0 - 1;
while (++i < sz)
container.at(i) = static_cast<int>(i);
// randomize
i = 0 - 1;
while (++i < sz)
{
auto r = rand() % container.size();
auto temp = container.at(i);
container.at(i) = container.at(r);
container.at(r) = temp;
}
return container;
}
actualListContainer copyContainerToList(const vectorContainer &container)
{
actualListContainer actual;
std::for_each(container.begin(), container.end(), [&](int v)
{
actual.push_back(v);
});
return actual;
}
void copyRandomPartContainerToLists(const vectorContainer &container,
expectListContainer &expect,
actualListContainer &actual)
{
std::for_each(container.begin(), container.end(), [&](int v)
{
if (rand() % 2)
{
expect.push_back(v);
actual.push_back(v);
}
});
auto begin = container.begin();
while (expect.size() < 10)
{
expect.push_back(*begin);
actual.push_back(*begin++);
}
}
void isSame(expectListContainer expect, actualListContainer actual)
{
CHECK(expect.size() == actual.size());
CHECK(expect.empty() == actual.empty());
auto expectIt = expect.begin();
auto actualIt = actual.begin();
while (expectIt != expect.end())
CHECK(*expectIt++ == *actualIt++);
}
TEST_CASE("-ctors converts and its types")
{
expectListContainer expect;
actualListContainer actual;
const expectListContainer cExpect;
const actualListContainer cActual;
SECTION("iterator")
{
SECTION("begin")
{
expectListContainer::iterator expectIt1(expect.begin());
expectListContainer::const_iterator expectIt2(expect.begin());
expectListContainer::reverse_iterator expectIt3(expect.begin());
expectListContainer::const_reverse_iterator expectIt4(expect.begin());
expectListContainer::const_iterator expectCIt2(expect.cbegin());
expectListContainer::const_reverse_iterator expectCIt4(expect.cbegin());
expectListContainer::reverse_iterator expectRIt3(expect.rbegin());
expectListContainer::const_reverse_iterator expectRIt4(expect.rbegin());
expectListContainer::const_reverse_iterator expectCRIt4(expect.crbegin());
actualListContainer::iterator actualIt1(actual.begin());
actualListContainer::const_iterator actualIt2(actual.begin());
actualListContainer::reverse_iterator actualIt3(actual.begin());
actualListContainer::const_reverse_iterator actualIt4(actual.begin());
actualListContainer::const_iterator actualCIt2(actual.cbegin());
actualListContainer::const_reverse_iterator actualCIt4(actual.cbegin());
actualListContainer::reverse_iterator actualRIt3(actual.rbegin());
actualListContainer::const_reverse_iterator actualRIt4(actual.rbegin());
actualListContainer::const_reverse_iterator actualCRIt4(actual.crbegin());
}
SECTION("begin errors")
{
// expectListContainer::iterator expectCIt1(expect.cbegin());
// expectListContainer::reverse_iterator expectCIt3(expect.cbegin());
//
// expectListContainer::iterator expectRIt1(expect.rbegin());
// expectListContainer::const_iterator expectRIt2(expect.rbegin());
//
// expectListContainer::iterator expectCRIt1(expect.crbegin());
// expectListContainer::const_iterator expectCRIt2(expect.crbegin());
// expectListContainer::reverse_iterator expectCRIt3(expect.crbegin());
// actualListContainer::iterator actualCIt1(actual.cbegin());
// actualListContainer::reverse_iterator actualCIt3(actual.cbegin());
// actualListContainer::iterator actualRIt1(actual.rbegin());
// actualListContainer::const_iterator actualRIt2(actual.rbegin());
// actualListContainer::iterator actualCRIt1(actual.crbegin());
// actualListContainer::const_iterator actualCRIt2(actual.crbegin());
// actualListContainer::reverse_iterator actualCRIt3(actual.crbegin());
}
SECTION("end")
{
expectListContainer::iterator expectIt1(expect.end());
expectListContainer::const_iterator expectIt2(expect.end());
expectListContainer::reverse_iterator expectIt3(expect.end());
expectListContainer::const_reverse_iterator expectIt4(expect.end());
expectListContainer::const_iterator expectCIt2(expect.cend());
expectListContainer::const_reverse_iterator expectCIt4(expect.cend());
expectListContainer::reverse_iterator expectRIt3(expect.rend());
expectListContainer::const_reverse_iterator expectRIt4(expect.rend());
expectListContainer::const_reverse_iterator expectCRIt4(expect.crend());
actualListContainer::iterator actualIt1(actual.end());
actualListContainer::const_iterator actualIt2(actual.end());
actualListContainer::reverse_iterator actualIt3(actual.end());
actualListContainer::const_reverse_iterator actualIt4(actual.end());
actualListContainer::const_iterator actualCIt2(actual.cend());
actualListContainer::const_reverse_iterator actualCIt4(actual.cend());
actualListContainer::reverse_iterator actualRIt3(actual.rend());
actualListContainer::const_reverse_iterator actualRIt4(actual.rend());
actualListContainer::const_reverse_iterator actualCRIt4(actual.crend());
}
SECTION("end error")
{
// expectListContainer::iterator expectCIt1(expect.cend());
// expectListContainer::reverse_iterator expectCIt3(expect.cend());
//
// expectListContainer::iterator expectRIt1(expect.rend());
// expectListContainer::const_iterator expectRIt2(expect.rend());
//
// expectListContainer::iterator expectCRIt1(expect.crend());
// expectListContainer::const_iterator expectCRIt2(expect.crend());
// expectListContainer::reverse_iterator expectCRIt3(expect.crend());
// actualListContainer::iterator actualCIt1(actual.cend());
// actualListContainer::reverse_iterator actualCIt3(actual.cend());
//
// actualListContainer::iterator actualRIt1(actual.rend());
// actualListContainer::const_iterator actualRIt2(actual.rend());
//
// actualListContainer::iterator actualCRIt1(actual.crend());
// actualListContainer::const_iterator actualCRIt2(actual.crend());
// actualListContainer::reverse_iterator actualCRIt3(actual.crend());
}
SECTION("const begin")
{
const expectListContainer::const_iterator expectIt2(cExpect.begin());
const expectListContainer::const_reverse_iterator expectIt4(cExpect.begin());
const expectListContainer::const_iterator expectCIt2(cExpect.cbegin());
const expectListContainer::const_reverse_iterator expectCIt4(cExpect.cbegin());
const expectListContainer::const_reverse_iterator expectRIt4(cExpect.rbegin());
const expectListContainer::const_reverse_iterator expectCRIt4(cExpect.crbegin());
const actualListContainer::const_iterator actualIt2(cActual.begin());
const actualListContainer::const_reverse_iterator actualIt4(cActual.begin());
const actualListContainer::const_iterator actualCIt2(cActual.cbegin());
const actualListContainer::const_reverse_iterator actualCIt4(cActual.cbegin());
const actualListContainer::const_reverse_iterator actualRIt4(cActual.rbegin());
const actualListContainer::const_reverse_iterator actualCRIt4(cActual.crbegin());
}
SECTION("const begin errors")
{
// const expectListContainer::iterator expectIt1(cExpect.begin());
// const expectListContainer::reverse_iterator expectIt3(cExpect.begin());
//
// const expectListContainer::iterator expectCIt1(cExpect.cbegin());
// const expectListContainer::reverse_iterator expectCIt3(cExpect.cbegin());
//
// const expectListContainer::iterator expectRIt1(cExpect.rbegin());
// const expectListContainer::const_iterator expectRIt2(cExpect.rbegin());
// const expectListContainer::reverse_iterator expectRIt3(cExpect.rbegin());
//
// const expectListContainer::iterator expectCRIt1(cExpect.crbegin());
// const expectListContainer::const_iterator expectCRIt2(cExpect.crbegin());
// const expectListContainer::reverse_iterator expectCRIt3(cExpect.crbegin());
// const actualListContainer::iterator actualIt1(cActual.begin());
// const actualListContainer::reverse_iterator actualIt3(cActual.begin());
//
// const actualListContainer::iterator actualCIt1(cActual.cbegin());
// const actualListContainer::reverse_iterator actualCIt3(cActual.cbegin());
//
// const actualListContainer::iterator actualRIt1(cActual.rbegin());
// const actualListContainer::const_iterator actualRIt2(cActual.rbegin());
// const actualListContainer::reverse_iterator actualRIt3(cActual.rbegin());
//
// const actualListContainer::iterator actualCRIt1(cActual.crbegin());
// const actualListContainer::const_iterator actualCRIt2(cActual.crbegin());
// const actualListContainer::reverse_iterator actualCRIt3(cActual.crbegin());
}
SECTION("const end")
{
const expectListContainer::const_iterator expectIt2(cExpect.end());
const expectListContainer::const_reverse_iterator expectIt4(cExpect.end());
const expectListContainer::const_iterator expectCIt2(cExpect.cend());
const expectListContainer::const_reverse_iterator expectCIt4(cExpect.cend());
const expectListContainer::const_reverse_iterator expectRIt4(cExpect.rend());
const expectListContainer::const_reverse_iterator expectCRIt4(cExpect.crend());
const actualListContainer::const_iterator actualIt2(cActual.end());
const actualListContainer::const_reverse_iterator actualIt4(cActual.end());
const actualListContainer::const_iterator actualCIt2(cActual.cend());
const actualListContainer::const_reverse_iterator actualCIt4(cActual.cend());
const actualListContainer::const_reverse_iterator actualRIt4(cActual.rend());
const actualListContainer::const_reverse_iterator actualCRIt4(cActual.crend());
}
SECTION("const end error")
{
// const expectListContainer::iterator expectIt1(cExpect.end());
// const expectListContainer::reverse_iterator expectIt3(cExpect.end());
//
// const expectListContainer::iterator expectCIt1(cExpect.cend());
// const expectListContainer::reverse_iterator expectCIt3(cExpect.cend());
//
// const expectListContainer::iterator expectRIt1(cExpect.rend());
// const expectListContainer::const_iterator expectRIt2(cExpect.rend());
// const expectListContainer::reverse_iterator expectRIt3(cExpect.rend());
//
// const expectListContainer::iterator expectCRIt1(cExpect.crend());
// const expectListContainer::const_iterator expectCRIt2(cExpect.crend());
// const expectListContainer::reverse_iterator expectCRIt3(cExpect.crend());
// const actualListContainer::iterator actualIt1(cActual.end());
// const actualListContainer::reverse_iterator actualIt3(cActual.end());
//
// const actualListContainer::iterator actualCIt1(cActual.cend());
// const actualListContainer::reverse_iterator actualCIt3(cActual.cend());
//
// const actualListContainer::iterator actualRIt1(cActual.rend());
// const actualListContainer::const_iterator actualRIt2(cActual.rend());
// const actualListContainer::reverse_iterator actualRIt3(cActual.rend());
//
// const actualListContainer::iterator actualCRIt1(cActual.crend());
// const actualListContainer::const_iterator actualCRIt2(cActual.crend());
// const actualListContainer::reverse_iterator actualCRIt3(cActual.crend());
}
}
SECTION("container")
{
expectListContainer expect1;
expectListContainer expect2(expect1);
expectListContainer expect3{1, 2, 3};
actualListContainer actual1;
actualListContainer actual2(actual1);
actualListContainer actual3{1, 2, 3};
}
}
TEST_CASE("const semantic")
{
expectListContainer expect;
actualListContainer actual;
const expectListContainer cExpect;
const actualListContainer cActual;
using std::is_const;
SECTION("iterators")
{
SECTION("non-const")
{
CHECK(is_const<decltype(actual.begin())>() == is_const<decltype(expect.begin())>());
CHECK(is_const<decltype(actual.begin().operator->())>()
== is_const<decltype(expect.begin().operator->())>());
CHECK(is_const<decltype(*actual.begin())>() == is_const<decltype(*expect.begin())>());
CHECK(is_const<decltype(actual.end())>() == is_const<decltype(expect.end())>());
CHECK(is_const<decltype(actual.end().operator->())>()
== is_const<decltype(expect.end().operator->())>());
CHECK(is_const<decltype(*actual.end())>() == is_const<decltype(*expect.end())>());
CHECK(is_const<decltype(actual.cbegin())>() == is_const<decltype(expect.cbegin())>());
CHECK(is_const<decltype(actual.cbegin().operator->())>()
== is_const<decltype(expect.cbegin().operator->())>());
CHECK(is_const<decltype(*actual.cbegin())>()
== is_const<decltype(*expect.cbegin())>());
CHECK(is_const<decltype(actual.cend())>() == is_const<decltype(expect.cend())>());
CHECK(is_const<decltype(actual.cend().operator->())>()
== is_const<decltype(expect.cend().operator->())>());
CHECK(is_const<decltype(*actual.cend())>() == is_const<decltype(*expect.cend())>());
CHECK(is_const<decltype(actual.rbegin())>() == is_const<decltype(expect.rbegin())>());
CHECK(is_const<decltype(actual.rbegin().operator->())>()
== is_const<decltype(expect.rbegin().operator->())>());
CHECK(is_const<decltype(*actual.rbegin())>()
== is_const<decltype(*expect.rbegin())>());
CHECK(is_const<decltype(actual.rend())>() == is_const<decltype(expect.rend())>());
CHECK(is_const<decltype(actual.rend().operator->())>()
== is_const<decltype(expect.rend().operator->())>());
CHECK(is_const<decltype(*actual.rend())>() == is_const<decltype(*expect.rend())>());
CHECK(is_const<decltype(actual.crbegin())>()
== is_const<decltype(expect.crbegin())>());
CHECK(is_const<decltype(actual.crbegin().operator->())>()
== is_const<decltype(expect.crbegin().operator->())>());
CHECK(is_const<decltype(*actual.crbegin())>()
== is_const<decltype(*expect.crbegin())>());
CHECK(is_const<decltype(actual.crend())>() == is_const<decltype(expect.crend())>());
CHECK(is_const<decltype(actual.crend().operator->())>()
== is_const<decltype(expect.crend().operator->())>());
CHECK(is_const<decltype(*actual.crend())>() == is_const<decltype(*expect.crend())>());
CHECK(is_const<decltype(actual.rbegin().base())>()
== is_const<decltype(expect.rbegin().base())>());
CHECK(is_const<decltype(actual.rbegin().base().operator->())>()
== is_const<decltype(expect.rbegin().base().operator->())>());
CHECK(is_const<decltype(*actual.rbegin().base())>()
== is_const<decltype(*expect.rbegin().base())>());
CHECK(is_const<decltype(actual.rend().base())>()
== is_const<decltype(expect.rend().base())>());
CHECK(is_const<decltype(actual.rend().base().operator->())>()
== is_const<decltype(expect.rend().base().operator->())>());
CHECK(is_const<decltype(*actual.rend().base())>()
== is_const<decltype(*expect.rend().base())>());
CHECK(is_const<decltype(actual.crbegin().base())>()
== is_const<decltype(expect.crbegin().base())>());
CHECK(is_const<decltype(actual.crbegin().base().operator->())>()
== is_const<decltype(expect.crbegin().base().operator->())>());
CHECK(is_const<decltype(actual.crend().base())>()
== is_const<decltype(expect.crend().base())>());
CHECK(is_const<decltype(*actual.crbegin().base())>()
== is_const<decltype(*expect.crbegin().base())>());
CHECK(is_const<decltype(*actual.crbegin().base().operator->())>()
== is_const<decltype(*expect.crbegin().base().operator->())>());
CHECK(is_const<decltype(*actual.crend().base())>()
== is_const<decltype(*expect.crend().base())>());
}
SECTION("const")
{
CHECK(is_const<decltype(cActual.begin())>() == is_const<decltype(cExpect.begin())>());
CHECK(is_const<decltype(cActual.begin().operator->())>()
== is_const<decltype(cExpect.begin().operator->())>());
CHECK(is_const<decltype(*cActual.begin())>() == is_const<decltype(*cExpect.begin())>());
CHECK(is_const<decltype(cActual.end())>() == is_const<decltype(cExpect.end())>());
CHECK(is_const<decltype(cActual.end().operator->())>()
== is_const<decltype(cExpect.end().operator->())>());
CHECK(is_const<decltype(*cActual.end())>() == is_const<decltype(*cExpect.end())>());
CHECK(is_const<decltype(cActual.cbegin())>() == is_const<decltype(cExpect.cbegin())>());
CHECK(is_const<decltype(cActual.cbegin().operator->())>()
== is_const<decltype(cExpect.cbegin().operator->())>());
CHECK(is_const<decltype(*cActual.cbegin())>()
== is_const<decltype(*cExpect.cbegin())>());
CHECK(is_const<decltype(cActual.cend())>() == is_const<decltype(cExpect.cend())>());
CHECK(is_const<decltype(cActual.cend().operator->())>()
== is_const<decltype(cExpect.cend().operator->())>());
CHECK(is_const<decltype(*cActual.cend())>() == is_const<decltype(*cExpect.cend())>());
CHECK(is_const<decltype(cActual.rbegin())>() == is_const<decltype(cExpect.rbegin())>());
CHECK(is_const<decltype(cActual.rbegin().operator->())>()
== is_const<decltype(cExpect.rbegin().operator->())>());
CHECK(is_const<decltype(*cActual.rbegin())>()
== is_const<decltype(*cExpect.rbegin())>());
CHECK(is_const<decltype(cActual.rend())>() == is_const<decltype(cExpect.rend())>());
CHECK(is_const<decltype(cActual.rend().operator->())>()
== is_const<decltype(cExpect.rend().operator->())>());
CHECK(is_const<decltype(*cActual.rend())>() == is_const<decltype(*cExpect.rend())>());
CHECK(is_const<decltype(cActual.crbegin())>()
== is_const<decltype(cExpect.crbegin())>());
CHECK(is_const<decltype(cActual.crbegin().operator->())>()
== is_const<decltype(cExpect.crbegin().operator->())>());
CHECK(is_const<decltype(*cActual.crbegin())>()
== is_const<decltype(*cExpect.crbegin())>());
CHECK(is_const<decltype(cActual.crend())>() == is_const<decltype(cExpect.crend())>());
CHECK(is_const<decltype(cActual.crend().operator->())>()
== is_const<decltype(cExpect.crend().operator->())>());
CHECK(is_const<decltype(*cActual.crend())>() == is_const<decltype(*cExpect.crend())>());
CHECK(is_const<decltype(cActual.rbegin().base())>()
== is_const<decltype(cExpect.rbegin().base())>());
CHECK(is_const<decltype(cActual.rbegin().base().operator->())>()
== is_const<decltype(cExpect.rbegin().base().operator->())>());
CHECK(is_const<decltype(*cActual.rbegin().base())>()
== is_const<decltype(*cExpect.rbegin().base())>());
CHECK(is_const<decltype(cActual.rend().base())>()
== is_const<decltype(cExpect.rend().base())>());
CHECK(is_const<decltype(cActual.rend().base().operator->())>()
== is_const<decltype(cExpect.rend().base().operator->())>());
CHECK(is_const<decltype(*cActual.rend().base())>()
== is_const<decltype(*cExpect.rend().base())>());
CHECK(is_const<decltype(cActual.crbegin().base())>()
== is_const<decltype(cExpect.crbegin().base())>());
CHECK(is_const<decltype(cActual.crbegin().base().operator->())>()
== is_const<decltype(cExpect.crbegin().base().operator->())>());
CHECK(is_const<decltype(cActual.crend().base())>()
== is_const<decltype(cExpect.crend().base())>());
CHECK(is_const<decltype(*cActual.crbegin().base())>()
== is_const<decltype(*cExpect.crbegin().base())>());
CHECK(is_const<decltype(*cActual.crbegin().base().operator->())>()
== is_const<decltype(*cExpect.crbegin().base().operator->())>());
CHECK(is_const<decltype(*cActual.crend().base())>()
== is_const<decltype(*cExpect.crend().base())>());
}
}
SECTION("element access")
{
SECTION("non-const")
{
CHECK(is_const<decltype(actual.front())>() == is_const<decltype(expect.front())>());
CHECK(is_const<decltype(actual.back())>() == is_const<decltype(expect.back())>());
}
SECTION("const")
{
CHECK(is_const<decltype(cActual.front())>() == is_const<decltype(cExpect.front())>());
CHECK(is_const<decltype(cActual.back())>() == is_const<decltype(cExpect.back())>());
}
}
}
TEST_CASE("element access rely on [push]")
{
actualListContainer actual;
SECTION("push one node")
{
actual.push_back(1);
CHECK(actual.front() == 1);
CHECK(actual.back() == 1);
}
SECTION("push two nodes")
{
actual.push_back(1);
actual.push_back(2);
CHECK(actual.front() == 1);
CHECK(actual.back() == 2);
actual.push_front(3);
CHECK(actual.front() == 3);
CHECK(actual.back() == 2);
}
}
TEST_CASE("modifiers")
{
auto randomContainer = getRandomValueContainer();
auto randomSmallContainer = getRandomValueContainer(SmallRandomSize);
std::initializer_list<int> randomIlist{rand(), rand(), rand(), rand(), rand()};
expectListContainer expect;
actualListContainer actual;
expectListContainer::iterator expectReturnPos;
actualListContainer::iterator actualReturnPos;
int randomValue{};
size_t sz{};
SECTION("empty list")
{
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("[clear] rely on [push_back]")
{
SECTION("while empty")
{
actual.clear();
}
SECTION("after actions")
{
actual.push_back(1);
actual.push_back(2);
actual.clear();
actual.push_back(3);
}
SECTION("before destruct")
{
actual.push_back(1);
actual.push_back(2);
actual.push_back(3);
actual.clear();
}
SECTION("while destruct")
{
actual.push_back(1);
actual.push_back(2);
actual.push_back(3);
}
}
SECTION("[erase] rely on [push_back/begin/end/op/size]")
{
SECTION("erase(const_iterator)")
{
SECTION("from empty")
{
/*
* erase(end()) is undefined, refer to:
* http://en.cppreference.com/w/cpp/container/list/erase
*/
}
SECTION("first one")
{
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
expectReturnPos = expect.erase(expect.begin());
actualReturnPos = actual.erase(actual.begin());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("random size")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
expectReturnPos = expect.erase(expect.begin());
actualReturnPos = actual.erase(actual.begin());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("last one")
{
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
expectReturnPos = expect.erase(expect.begin());
actualReturnPos = actual.erase(actual.begin());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("random size")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
expectReturnPos = expect.erase(--expect.end());
actualReturnPos = actual.erase(--actual.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
expectReturnPos = expect.erase(---- expect.end());
actualReturnPos = actual.erase(---- actual.end());
CHECK(expectReturnPos == --expect.end());
CHECK(actualReturnPos == --actual.end());
isSame(expect, actual);
}
}
SECTION("erase(const_iterator, const_iterator)")
{
SECTION("from empty")
{
/*
* erase(end(), end()) is undefined, refer to:
* http://en.cppreference.com/w/cpp/container/list/erase
*/
}
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
expectReturnPos = expect.erase(expect.begin(), expect.end());
actualReturnPos = actual.erase(actual.begin(), actual.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("random size")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
SECTION("[begin : end)")
{
expectReturnPos = expect.erase(expect.begin(), ++++++ expect.begin());
actualReturnPos = actual.erase(actual.begin(), ++++++ actual.begin());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("(begin : end)")
{
expectReturnPos = expect.erase(++++++ expect.begin(), ------ expect.end());
actualReturnPos = actual.erase(++++++ actual.begin(), ------ actual.end());
CHECK(expectReturnPos == ------ expect.end());
CHECK(actualReturnPos == ------ actual.end());
isSame(expect, actual);
}
SECTION("(begin : end]")
{
expectReturnPos = expect.erase(++++++ expect.begin(), expect.end());
actualReturnPos = actual.erase(++++++ actual.begin(), actual.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
}
}
}
SECTION("[insert] rely on [op/begin/end/size/push_back/clear]")
{
SECTION("insert(const_iterator, const value_type &)")
{
SECTION("to empty")
{
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), randomValue);
actualReturnPos = actual.insert(actual.end(), randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before begin")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.begin(), randomValue);
actualReturnPos = actual.insert(actual.begin(), randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), randomValue);
actualReturnPos = actual.insert(actual.end(), randomValue);
CHECK(expectReturnPos == --expect.end());
CHECK(actualReturnPos == --actual.end());
isSame(expect, actual);
}
SECTION("between of begin and end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(++expect.begin(), randomValue);
actualReturnPos = actual.insert(++actual.begin(), randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, value_type &&)")
{
SECTION("to empty")
{
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), std::move(randomValue));
actualReturnPos = actual.insert(actual.end(), std::move(randomValue));
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before begin")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.begin(), std::move(randomValue));
actualReturnPos = actual.insert(actual.begin(), std::move(randomValue));
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("before end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(expect.end(), std::move(randomValue));
actualReturnPos = actual.insert(actual.end(), std::move(randomValue));
CHECK(expectReturnPos == --expect.end());
CHECK(actualReturnPos == --actual.end());
isSame(expect, actual);
}
SECTION("between of begin and end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expectReturnPos = expect.insert(++expect.begin(), std::move(randomValue));
actualReturnPos = actual.insert(++actual.begin(), std::move(randomValue));
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, size_type, const value_type &)")
{
SECTION("to empty")
{
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
auto expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
auto tempe = expect.end();
auto tempa = actual.end();
++sz;
while (--sz)
{
--tempe;
--tempa;
}
CHECK(expectReturnPos == tempe);
CHECK(actualReturnPos == tempa);
isSame(expect, actual);
}
}
SECTION("before begin")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
expectReturnPos = expect.insert(expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(actual.begin(), sz, randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(actual.begin(), sz, randomValue);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(expect.end(), sz, randomValue);
actualReturnPos = actual.insert(actual.end(), sz, randomValue);
auto tempe = expect.end();
auto tempa = actual.end();
++sz;
while (--sz)
{
--tempe;
--tempa;
}
CHECK(expectReturnPos == tempe);
CHECK(actualReturnPos == tempa);
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("size is 0")
{
randomValue = rand();
sz = 0;
expectReturnPos = expect.insert(++expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(++actual.begin(), sz, randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
SECTION("size is non-zero")
{
randomValue = rand();
sz = rand() % 10 + SmallRandomSize;
expectReturnPos = expect.insert(++expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(++actual.begin(), sz, randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("size is 1")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
sz = 1;
expectReturnPos = expect.insert(++expect.begin(), sz, randomValue);
actualReturnPos = actual.insert(++actual.begin(), sz, randomValue);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, initilizer_list)")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("to empty")
{
expect.clear();
actual.clear();
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before begin")
{
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(expect.begin(), randomIlist);
actualReturnPos = actual.insert(actual.begin(), randomIlist);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(expect.begin(), randomIlist);
actualReturnPos = actual.insert(actual.begin(), randomIlist);
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before end")
{
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(expect.end(), randomIlist);
actualReturnPos = actual.insert(actual.end(), randomIlist);
CHECK(expectReturnPos == ++++ expect.begin());
CHECK(actualReturnPos == ++++ actual.begin());
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
SECTION("initializer_list is empty")
{
randomIlist = {};
expectReturnPos = expect.insert(++expect.begin(), randomIlist);
actualReturnPos = actual.insert(++actual.begin(), randomIlist);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
SECTION("initializer_list is non-empty")
{
expectReturnPos = expect.insert(++expect.begin(), randomIlist);
actualReturnPos = actual.insert(++actual.begin(), randomIlist);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("size of initializer is 1")
{
randomIlist = {rand()};
expectReturnPos = expect.insert(++expect.begin(), randomIlist);
actualReturnPos = actual.insert(++actual.begin(), randomIlist);
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("insert(const_iterator, iterator, iterator)")
{
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
randomValue = rand();
expect.push_back(randomValue);
actual.push_back(randomValue);
SECTION("to empty")
{
expect.clear();
actual.clear();
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before begin")
{
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.begin());
CHECK(actualReturnPos == actual.begin());
isSame(expect, actual);
}
}
SECTION("before end")
{
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == expect.end());
CHECK(actualReturnPos == actual.end());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(expect.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(actual.end(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++++ expect.begin());
CHECK(actualReturnPos == ++++ actual.begin());
isSame(expect, actual);
}
}
SECTION("between of begin and end")
{
SECTION("container is empty")
{
randomSmallContainer = {};
expectReturnPos = expect.insert(++expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(++actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
SECTION("container is non-empty")
{
expectReturnPos = expect.insert(++expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(++actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
SECTION("size of iterator is 1")
{
randomSmallContainer = {rand()};
expectReturnPos = expect.insert(++expect.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
actualReturnPos = actual.insert(++actual.begin(),
randomSmallContainer.begin(),
randomSmallContainer.end());
CHECK(expectReturnPos == ++expect.begin());
CHECK(actualReturnPos == ++actual.begin());
isSame(expect, actual);
}
}
}
SECTION("pop rely on [push_back/front/back]")
{
// std not throws exception while invoke pop on empty list
SECTION("pop_front")
{
actual.push_back(111);
CHECK_NOTHROW(actual.pop_front());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(actual.pop_front());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
actual.push_back(333);
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(actual.pop_front());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
}
SECTION("pop_back")
{
actual.push_back(111);
CHECK_NOTHROW(actual.pop_back());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(actual.pop_back());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
actual.push_back(111);
actual.push_back(222);
actual.push_back(333);
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(actual.pop_back());
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
}
SECTION("random pop")
{
copyRandomPartContainerToLists(randomContainer, expect, actual);
while (!expect.empty())
{
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
if (rand() % 2)
{
actual.pop_back();
expect.pop_back();
}
else
{
actual.pop_front();
expect.pop_front();
}
}
}
}
SECTION("[push] rely on [clear/begin/end/front/back]")
{
SECTION("push front")
{
actual.push_front(111);
CHECK(actual.front() == 111);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 111);
CHECK(*--actual.end() == 111);
actual.push_front(222);
CHECK(actual.front() == 222);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 222);
CHECK(*++actual.begin() == 111);
CHECK(*--actual.end() == 111);
CHECK(*---- actual.end() == 222);
actual.push_front(333);
CHECK(actual.front() == 333);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 333);
CHECK(*++actual.begin() == 222);
CHECK(*++++ actual.begin() == 111);
CHECK(*--actual.end() == 111);
CHECK(*---- actual.end() == 222);
CHECK(*------ actual.end() == 333);
}
SECTION("push back")
{
actual.push_back(111);
CHECK(actual.front() == 111);
CHECK(actual.back() == 111);
CHECK(*actual.begin() == 111);
CHECK(*--actual.end() == 111);
actual.push_back(222);
CHECK(actual.front() == 111);
CHECK(actual.back() == 222);
CHECK(*actual.begin() == 111);
CHECK(*++actual.begin() == 222);
CHECK(*--actual.end() == 222);
CHECK(*---- actual.end() == 111);
actual.push_back(333);
CHECK(actual.front() == 111);
CHECK(actual.back() == 333);
CHECK(*actual.begin() == 111);
CHECK(*++actual.begin() == 222);
CHECK(*++++ actual.begin() == 333);
CHECK(*--actual.end() == 333);
CHECK(*---- actual.end() == 222);
CHECK(*------ actual.end() == 111);
}
SECTION("random push")
{
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
});
}
}
SECTION("random push/pop rely on [front/back]")
{
SECTION("push is more than pop")
{
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (rand() % 3)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
}
else
{
if (rand() % 2)
{
if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_back());
expect.pop_back();
}
}
else if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_front());
expect.pop_front();
}
}
if (!expect.empty())
{
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
}
});
}
SECTION("pop is more than push")
{
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (!(rand() % 3))
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
}
else
{
if (rand() % 2)
{
if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_back());
expect.pop_back();
}
}
else if (!expect.empty())
{
CHECK_NOTHROW(actual.pop_front());
expect.pop_front();
}
}
if (!expect.empty())
{
CHECK(actual.front() == expect.front());
CHECK(actual.back() == expect.back());
}
});
}
}
}
TEST_CASE("capcity rely on [push/pop]")
{
auto randomContainer = getRandomValueContainer();
actualListContainer actual;
CHECK(actual.empty());
CHECK(actual.size() == 0);
CHECK(actual.max_size() >= actual.size());
SECTION("random actions")
{
int expectSize = 0;
std::for_each(randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (!(rand() % 3))
{
if (rand() % 2)
actual.push_back(v);
else
actual.push_front(v);
++expectSize;
}
else
{
if (rand() % 2)
{
if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_back());
--expectSize;
}
}
else if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_front());
--expectSize;
}
}
CHECK(actual.size() == expectSize);
CHECK(actual.max_size() >= expectSize);
CHECK((expectSize ^ actual.empty()));
});
}
}
TEST_CASE("iterator rely on [push_back]")
{
auto expectRandomContainer = getRandomValueContainer();
auto actual = copyContainerToList(expectRandomContainer);
SECTION("random move (i++ more than i--) rely on [push_back]")
{
SECTION("iterator")
{
auto actualIt = actual.begin();
auto expectIt = expectRandomContainer.begin();
SECTION("++i/--i")
{
while (expectIt < expectRandomContainer.end())
{
if (expectIt < expectRandomContainer.begin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
{
auto temp = expectIt;
if (++temp < expectRandomContainer.end()) // is not lastest
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.begin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i--")
{
while (expectIt < expectRandomContainer.end())
{
if (expectIt < expectRandomContainer.begin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
CHECK(*(actualIt++) == *(expectIt++));
else if (expectIt > expectRandomContainer.begin())
CHECK(*(actualIt--) == *(expectIt--));
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
}
SECTION("reverse iterator")
{
auto actualIt = actual.rbegin();
auto expectIt = expectRandomContainer.rbegin();
SECTION("++i/--i")
{
while (expectIt < expectRandomContainer.rend())
{
if (expectIt < expectRandomContainer.rbegin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
{
auto temp = expectIt;
if (++temp < expectRandomContainer.rend()) // is not lastest
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i--")
{
while (expectIt < expectRandomContainer.rend())
{
if (expectIt < expectRandomContainer.rbegin())
{
++expectIt;
++actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (rand() % 3) // times: ++ > --
CHECK(*(actualIt++) == *(expectIt++));
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(actualIt--) == *(expectIt--));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
}
}
SECTION("random move (i-- more than i++) rely on [push_back]")
{
SECTION("iterator")
{
auto actualIt = --actual.end();
auto expectIt = --expectRandomContainer.end();
SECTION("++i/--i rely on [push_back]")
{
while (expectIt > expectRandomContainer.begin())
{
if (expectIt >= expectRandomContainer.end())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
{
auto temp = expectIt;
if (++temp < expectRandomContainer.end())
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.begin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i-- rely on [push_back]")
{
while (expectIt > expectRandomContainer.begin())
{
if (expectIt >= expectRandomContainer.end())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
CHECK(*actualIt++ == *expectIt++);
else if (expectIt > expectRandomContainer.begin())
CHECK(*actualIt-- == *expectIt--);
if (expectIt > --expectRandomContainer.begin() && expectIt
< expectRandomContainer.end())
CHECK(*actualIt == *expectIt);
}
}
}
SECTION("reverse iterator")
{
auto actualIt = actual.rbegin();
auto expectIt = expectRandomContainer.rbegin();
SECTION("++i/--i rely on [push_back]")
{
while (expectIt > expectRandomContainer.rbegin())
{
if (expectIt >= expectRandomContainer.rend())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
{
auto expectItTemp = expectIt;
if (++expectItTemp < expectRandomContainer.rend())
CHECK(*(++actualIt) == *(++expectIt));
else
{
++actualIt;
++expectIt;
break;
}
}
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(--actualIt) == *(--expectIt));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
SECTION("i++/i-- rely on [push_back]")
{
while (expectIt > expectRandomContainer.rbegin())
{
if (expectIt >= expectRandomContainer.rend())
{
--expectIt;
--actualIt;
}
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
if (!(rand() % 3)) // times: ++ < --
CHECK(*(actualIt++) == *(expectIt++));
else if (expectIt > expectRandomContainer.rbegin())
CHECK(*(actualIt--) == *(expectIt--));
if (expectIt > --expectRandomContainer.rbegin() && expectIt
< expectRandomContainer.rend())
CHECK(*actualIt == *expectIt);
}
}
}
}
SECTION("[reverse iterator: base] rely on [++/--]")
{
auto expectRandomContainer = getRandomValueContainer();
actualListContainer actual = copyContainerToList(expectRandomContainer);
vectorContainer::reverse_iterator expectReverseBegin(expectRandomContainer.begin());
actualListContainer::const_reverse_iterator actualReverseBegin(actual.begin());
auto expectBaseBegin = expectReverseBegin.base();
auto actualBaseBegin = actualReverseBegin.base();
while (expectBaseBegin != expectRandomContainer.end())
{
CHECK(*expectBaseBegin == *actualBaseBegin);
++expectBaseBegin;
++actualBaseBegin;
}
}
}
TEST_CASE("operations")
{
auto randomContainer = getRandomValueContainer();
expectListContainer expect;
actualListContainer actual;
SECTION("[reverse] rely on [empty/size/begin/end/front/back/push_back/push_front]")
{
SECTION("empty")
{
CHECK(actual.empty());
CHECK(actual.size() == 0);
CHECK(actual.begin() == actual.end());
actual.reverse();
CHECK(actual.empty());
CHECK(actual.size() == 0);
CHECK(actual.begin() == actual.end());
}
SECTION("one nodes")
{
actual.push_back(1);
CHECK(actual.front() == 1);
CHECK(actual.back() == 1);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.reverse();
CHECK(actual.front() == 1);
CHECK(actual.back() == 1);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("two nodes")
{
actual.push_back(1);
actual.push_back(2);
CHECK(actual.front() == 1);
CHECK(actual.back() == 2);
CHECK(actual.size() == 2);
CHECK_FALSE(actual.empty());
actual.reverse();
CHECK(actual.front() == 2);
CHECK(actual.back() == 1);
CHECK(actual.size() == 2);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK(actual.front() == 2);
CHECK(actual.back() == 2);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("three nodes")
{
actual.push_back(1);
actual.push_back(2);
actual.push_back(3);
CHECK(actual.front() == 1);
CHECK(actual.back() == 3);
CHECK(actual.size() == 3);
CHECK_FALSE(actual.empty());
actual.reverse();
CHECK(actual.front() == 3);
CHECK(actual.back() == 1);
CHECK(actual.size() == 3);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK(actual.front() == 3);
CHECK(actual.back() == 2);
CHECK(actual.size() == 2);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK(actual.front() == 3);
CHECK(actual.back() == 3);
CHECK(actual.size() == 1);
CHECK_FALSE(actual.empty());
actual.pop_back();
CHECK_THROWS_AS(actual.front(), std::out_of_range);
CHECK_THROWS_AS(actual.back(), std::out_of_range);
CHECK(actual.size() == 0);
CHECK(actual.empty());
}
SECTION("random nodes")
{
while (!randomContainer.empty())
{
auto v = randomContainer.back();
if (rand() % 2)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
}
else
{
if (rand() % 2)
{
if (!expect.empty())
{
actual.pop_back();
expect.pop_back();
}
}
else if (!expect.empty())
{
actual.pop_front();
expect.pop_front();
}
}
if (!expect.empty())
{
actual.reverse();
reverse(actual.begin(), actual.end());
actual.reverse();
reverse(actual.begin(), actual.end());
actual.reverse();
reverse(expect.begin(), expect.end());
}
CHECK(actual.size() == expect.size());
CHECK((expect.size() ^ actual.empty()));
if (!expect.empty())
{
CHECK(expect.front() == actual.front());
CHECK(expect.back() == actual.back());
}
randomContainer.pop_back();
}
}
}
}
TEST_CASE("stl algorithm-compatible")
{
vectorContainer randomContainer = getRandomValueContainer();
expectListContainer expect;
actualListContainer actual;
expectListContainer::iterator expectPos;
actualListContainer::iterator actualPos;
int randomValue;
size_t sz;
auto randomSmallContainer = getRandomValueContainer(SmallRandomSize);
copyRandomPartContainerToLists(randomContainer, expect, actual);
SECTION("std::for_each")
{
expectPos = expect.begin();
std::for_each(actual.begin(), actual.end(), [&](int v)
{
CHECK(v == *expectPos++);
});
}
SECTION("std::find")
{
CHECK(*actual.begin() == *std::find(actual.begin(), actual.end(), *expect.begin()));
CHECK(*++actual.begin() == *std::find(actual.begin(), actual.end(), *++expect.begin()));
CHECK(*--actual.end() == *std::find(actual.begin(), actual.end(), *--expect.end()));
}
SECTION("std::equal")
{
CHECK(std::equal(expect.begin(), expect.end(), actual.begin()));
}
}
TEST_CASE("others")
{
SECTION("random nodes")
{
// todo: test more functions insert/find/unique/sort/erase
auto randomContainer = getRandomValueContainer();
actualListContainer actual;
int expectSize = 1;
expectListContainer expect;
expect.push_front(randomContainer.front());
actual.push_front(randomContainer.front());
std::for_each(++randomContainer.begin(), randomContainer.end(), [&](int v)
{
if (rand() % 2)
{
if (rand() % 2)
{
actual.push_back(v);
expect.push_back(v);
}
else
{
actual.push_front(v);
expect.push_front(v);
}
++expectSize;
}
else
{
if (rand() % 2)
{
if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_back());
CHECK_NOTHROW(expect.pop_back());
--expectSize;
}
}
else if (expectSize != 0)
{
CHECK_NOTHROW(actual.pop_front());
CHECK_NOTHROW(expect.pop_front());
--expectSize;
}
}
CHECK(actual.size() == expectSize);
CHECK((expectSize ^ actual.empty()));
if (!expect.empty())
{
CHECK(expect.front() == actual.front());
CHECK(expect.back() == actual.back());
}
});
}
SECTION("efficiency")
{
// todo
}
}
#endif // XOR_LINKED_LIST_TEST_CPP
|
code/data_structures/test/tree/binary_tree/binary_tree/diameter/test_diameter.cpp | #define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/diameter/diameter.cpp"
#include <string>
TEST_CASE("diameter of binary tree")
{
TreeSerializer ts;
std::string str;
SECTION("empty tree")
{
str = "#";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 0);
}
SECTION("one-node tree")
{
str = "1 # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 1);
}
SECTION("non-empty tree")
{
/*
* 1
* / \
* 2 2
* / \
* 3 3
* / \
* 4 4
* /
* 5
*/
str = "1 2 3 4 5 # # # # 3 # 4 # # 2 # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 6);
/*
* 1
* / \
* 2 2
* / \
* 3 3
* / \
* 4 4
* / \
* 5 5
*/
str = "1 2 3 4 5 # # # # 3 # 4 # 5 # # 2 # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 7);
/*
* 1
* / \
* 2 2
* / \ /
* 3 3 3
* / /\ /
* 4 4 4 4
* / /
* 5 5
*/
str = "1 2 3 4 5 # # # # 3 4 # # 4 # # 2 3 4 5 # # # # #";
CHECK(diameter<std::shared_ptr<TreeNode<int>>>(ts.deserialize(str)) == 9);
}
}
|
code/data_structures/test/tree/binary_tree/binary_tree/is_same/test_is_same.cpp | #define CATCH_CONFIG_MAIN
#ifndef TEST_TREE_COMPARER
#define TEST_TREE_COMPARER
#include <memory>
#include <functional>
#include <utility>
#include "../../../../../../../test/c++/catch.hpp"
#include "../../../../../src/tree/binary_tree/binary_tree/is_same/is_same.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
TEST_CASE("check two tree is same", "[isSameTree]") {
TreeSerializer serializer;
std::shared_ptr<TreeNode<int>> root_a, root_b;
TreeComparer<int> comparer;
SECTION("has empty tree") {
root_a = serializer.deserialize("# ");
root_b = serializer.deserialize("# ");
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # # ");
root_b = serializer.deserialize("1 # # ");
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("# ");
root_b = serializer.deserialize("1 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
}
SECTION("has same value") {
root_a = serializer.deserialize("1 # # ");
root_b = serializer.deserialize("1 # # ");
REQUIRE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # 2 # # ");
root_b = serializer.deserialize("1 # 2 # # ");
REQUIRE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 3 4 # # 5 # # # #");
root_b = serializer.deserialize("1 2 3 4 # # 5 # # # #");
REQUIRE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE(comparer.isSameTree(root_a, root_b));
}
SECTION("has not same value") {
root_a = serializer.deserialize("# ");
root_b = serializer.deserialize("1 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # # ");
root_b = serializer.deserialize("2 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 # 2 # # ");
root_b = serializer.deserialize("1 # 3 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 # # # ");
root_b = serializer.deserialize("1 3 # # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 3 4 # # 5 # # # #");
root_b = serializer.deserialize("1 2 3 4 # # 6 # # # #");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
}
SECTION("has reflex node") {
root_a = serializer.deserialize("1 2 # # 3 # # ");
root_b = serializer.deserialize("1 3 # # 2 # #");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 # 3 # # 4 # # ");
root_b = serializer.deserialize("1 4 # # 2 3 # # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
root_a = serializer.deserialize("1 2 3 # # # 4 # # ");
root_b = serializer.deserialize("1 4 # # 2 # 3 # # ");
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
std::swap(root_a, root_b);
REQUIRE_FALSE(comparer.isSameTree(root_a, root_b));
}
}
#endif // TEST_TREE_COMPARER
|
code/data_structures/test/tree/binary_tree/binary_tree/path_sum/test_path_sum_for_sum_of_part_paths.cpp | #define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include <vector>
#include <memory>
#include <queue>
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp"
using Node = TreeNode<int>;
using PNode = std::shared_ptr<Node>;
TEST_CASE("sum of paths between any node") {
PathSum<int> sol(PathSum<int>::PathType::Part);
size_t (PathSum<int>::* pf)(PNode, int) = &PathSum<int>::countPathsOfSum;
TreeSerializer ts;
PNode root = nullptr;
auto res = (sol.*pf)(root, 0);
SECTION("give empty tree") {
root = ts.deserialize("# ");
res = (sol.*pf)(root, 0);
CHECK(res == 0);
}
SECTION("give one node") {
root = ts.deserialize("1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
}
SECTION("give balance tree") {
root = ts.deserialize("0 1 # # 1 # # ");
res = (sol.*pf)(root, 0);
CHECK(res == 1);
res = (sol.*pf)(root, 1);
CHECK(res == 4);
root = ts.deserialize("1 2 # # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 1);
root = ts.deserialize("0 1 1 # # # 1 1 # # # ");
res = (sol.*pf)(root, 0);
CHECK(res == 1);
res = (sol.*pf)(root, 1);
CHECK(res == 6);
res = (sol.*pf)(root, 2);
CHECK(res == 4);
root = ts.deserialize("0 1 # 1 # # 1 # 1 # # ");
res = (sol.*pf)(root, 0);
CHECK(res == 1);
res = (sol.*pf)(root, 1);
CHECK(res == 6);
res = (sol.*pf)(root, 2);
CHECK(res == 4);
root = ts.deserialize("1 2 4 # # # 3 5 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
root = ts.deserialize("1 2 4 # # # 3 # 5 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
root = ts.deserialize("1 2 # 4 # # 3 5 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
root = ts.deserialize("1 2 # 4 # # 3 # 5 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
res = (sol.*pf)(root, 8);
CHECK(res == 1);
res = (sol.*pf)(root, 9);
CHECK(res == 1);
}
SECTION("give unbalance tree") {
SECTION("left is more deep") {
root = ts.deserialize("1 2 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 2 3 # # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 2 # 3 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 1 1 # # # 1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 1 # 1 # # 1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 2 4 # # # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
root = ts.deserialize("1 2 # 4 # # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 6);
CHECK(res == 1);
}
SECTION("right is more deep") {
root = ts.deserialize("1 # 2 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 # 2 3 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 # 2 # 3 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 5);
CHECK(res == 1);
root = ts.deserialize("1 1 # # 1 1 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 1 # # 1 # 1 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 4);
res = (sol.*pf)(root, 2);
CHECK(res == 3);
res = (sol.*pf)(root, 3);
CHECK(res == 1);
root = ts.deserialize("1 2 # # 3 4 # # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
root = ts.deserialize("1 2 # # 3 # 4 # # ");
res = (sol.*pf)(root, 1);
CHECK(res == 1);
res = (sol.*pf)(root, 2);
CHECK(res == 1);
res = (sol.*pf)(root, 3);
CHECK(res == 2);
res = (sol.*pf)(root, 4);
CHECK(res == 2);
res = (sol.*pf)(root, 7);
CHECK(res == 1);
}
}
}
|
code/data_structures/test/tree/binary_tree/binary_tree/path_sum/test_path_sum_for_sum_of_whole_paths.cpp | #define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include <vector>
#include <memory>
#include <queue>
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp"
using Node = TreeNode<int>;
using PNode = std::shared_ptr<Node>;
TEST_CASE("sum of paths between root to bottom") {
PathSum<int> sol;
size_t (PathSum<int>::* pf)(PNode, int) = &PathSum<int>::countPathsOfSum;
TreeSerializer ts;
PNode root = nullptr;
auto res = (sol.*pf)(root, 0);
SECTION("give empty tree") {
root = ts.deserialize("# ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
CHECK(res == 0);
}
}
SECTION("give one node") {
root = ts.deserialize("1 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 1)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
SECTION("give balance tree") {
root = ts.deserialize("1 2 # # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3 || i == 4)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 4 # # # 3 5 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 4 # # # 3 # 5 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 4 # # 3 5 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 4 # # 3 # 5 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 7 || i == 9)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
SECTION("give unbalance tree") {
SECTION("left is more deep") {
root = ts.deserialize("1 2 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 3 # # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 3 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 4 # # # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 4 || i == 7)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # 4 # # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 4 || i == 7)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
SECTION("right is more deep") {
root = ts.deserialize("1 # 2 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 # 2 3 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 # 2 # 3 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 6)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # # 3 4 # # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3 || i == 8)
CHECK(res == 1);
else
CHECK(res == 0);
}
root = ts.deserialize("1 2 # # 3 # 4 # # ");
for (int i = -20; i < 20; ++i)
{
res = (sol.*pf)(root, i);
if (i == 3 || i == 8)
CHECK(res == 1);
else
CHECK(res == 0);
}
}
}
}
|
code/data_structures/test/tree/binary_tree/binary_tree/path_sum/test_path_sum_for_whole_paths.cpp | #define CATCH_CONFIG_MAIN
#include "../../../../../../../test/c++/catch.hpp"
#include <vector>
#include <memory>
#include <queue>
#include "../../../../../src/tree/binary_tree/binary_tree/node/node.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/serializer/serializer.cpp"
#include "../../../../../src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp"
using Node = TreeNode<int>;
using PNode = std::shared_ptr<Node>;
bool isSame(std::vector<std::vector<int>> &a, std::vector<std::vector<int>> &b)
{
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); ++i)
{
if (a.at(i).size() != b.at(i).size())
return false;
for (size_t j = 0; j < a.at(i).size(); ++j)
if (a.at(i).at(j) != b.at(i).at(j))
return false;
}
return true;
}
TEST_CASE("paths between root to leaf") {
PathSum<int> sol;
std::vector<std::vector<int>> (PathSum<int>::* pf)(PNode, int) = &PathSum<int>::getPathsOfSum;
TreeSerializer ts;
PNode root = nullptr;
auto res = (sol.*pf)(root, 0);
std::vector<std::vector<int>> expect{};
SECTION("give empty tree") {
root = ts.deserialize("# ");
res = (sol.*pf)(root, 0);
expect = {};
CHECK(isSame(res, expect));
}
SECTION("give one node") {
root = ts.deserialize("1 # # ");
res = (sol.*pf)(root, 0);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {{1}};
CHECK(isSame(res, expect));
}
SECTION("user define") {
root = ts.deserialize("5 4 11 7 # # 2 # # # 8 13 # # 4 5 # # 1 # # ");
res = (sol.*pf)(root, 22);
expect = {{5, 4, 11, 2}, {5, 8, 4, 5}};
CHECK(isSame(res, expect));
}
SECTION("give balance tree") {
root = ts.deserialize("1 2 # # 3 # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {{1, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 4 # # # 3 5 # # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 4 # # # 3 # 5 # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 4 # # 3 5 # # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 4 # # 3 # 5 # # ");
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 9);
expect = {{1, 3, 5}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {};
CHECK(isSame(res, expect));
}
SECTION("give unbalance tree") {
SECTION("left is more deep") {
root = ts.deserialize("1 2 # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 3 # # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 3 # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 4 # # # 3 # # ");
res = (sol.*pf)(root, 4);
expect = {{1, 3}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # 4 # # 3 # # ");
res = (sol.*pf)(root, 4);
expect = {{1, 3}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {{1, 2, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {};
CHECK(isSame(res, expect));
}
SECTION("right is more deep") {
root = ts.deserialize("1 # 2 # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 # 2 3 # # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 # 2 # 3 # # ");
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 3);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 6);
expect = {{1, 2, 3}};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # # 3 4 # # # ");
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {{1, 3, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {};
CHECK(isSame(res, expect));
root = ts.deserialize("1 2 # # 3 # 4 # # ");
res = (sol.*pf)(root, 3);
expect = {{1, 2}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 8);
expect = {{1, 3, 4}};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 1);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 2);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 4);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 5);
expect = {};
CHECK(isSame(res, expect));
res = (sol.*pf)(root, 7);
expect = {};
CHECK(isSame(res, expect));
}
}
}
|
code/data_structures/test/tree/multiway_tree/red_black_tree/test_red_black.c | /**
* author: JonNRb <[email protected]>
* license: GPLv3
* file: @cosmos//code/data_structures/red_black_tree/red_black_test.c
* info: red black tree
*/
#include "red_black_tree.h"
#include <assert.h>
#include <inttypes.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define red_printf(f, ...) printf("\x1b[31m" f "\x1b[0m", __VA_ARGS__)
extern int is_rb_correct(cosmos_red_black_tree_t tree);
typedef struct item {
char label;
cosmos_red_black_node_t node;
uint64_t sort_key;
} item_t;
typedef struct {
char text[8];
size_t depth;
int red;
} item_repr_t;
void iot_1(cosmos_red_black_tree_t tree, size_t* size) {
++*size;
if (tree != NULL) {
iot_1(tree->link[0], size);
iot_1(tree->link[1], size);
}
}
void iot_2(cosmos_red_black_tree_t tree, item_repr_t* arr, size_t* i,
size_t depth) {
if (tree == NULL) {
strncpy(arr[*i].text, "[ NIL ]", 8);
arr[*i].depth = depth;
arr[*i].red = 0;
++*i;
return;
}
iot_2(tree->link[0], arr, i, depth + 1);
item_t* item = container_of(tree, struct item, node);
snprintf(arr[*i].text, 8, "[%c,%03" PRIu64 "]", item->label, item->sort_key);
arr[*i].depth = depth;
arr[*i].red = tree->red;
++*i;
iot_2(tree->link[1], arr, i, depth + 1);
}
void print_tree(cosmos_red_black_tree_t tree) {
size_t size = 0;
iot_1(tree, &size);
item_repr_t* arr = (item_repr_t*)malloc(size * sizeof(item_repr_t));
size_t i = 0;
iot_2(tree, arr, &i, 0);
assert(i == size);
for (size_t depth = 0, i = 0; i < size; ++depth) {
for (size_t j = 0; j < size; ++j) {
if (arr[j].depth == depth) {
if (arr[j].red) {
red_printf("%s", arr[j].text);
} else {
printf("%s", arr[j].text);
}
++i;
} else {
printf(" ");
}
}
printf("\n");
}
}
void assert_tree_invalid() {
printf("checking we can check tree validity\n");
assert(is_rb_correct(NULL));
item_t items[7];
items[0] = (item_t){'A', {{NULL, NULL}, 1}, 1};
items[1] = (item_t){'B', {{&items[0].node, &items[2].node}, 1}, 2};
items[2] = (item_t){'C', {{NULL, NULL}, 1}, 3};
items[3] = (item_t){'D', {{&items[1].node, &items[5].node}, 1}, 4};
items[4] = (item_t){'E', {{NULL, NULL}, 1}, 5};
items[5] = (item_t){'F', {{&items[4].node, &items[6].node}, 1}, 6};
items[6] = (item_t){'G', {{NULL, NULL}, 1}, 7};
assert(!is_rb_correct(&items[3].node));
}
void print_sanity_tree() {
item_t items[7];
items[0] = (item_t){'A', {{NULL, NULL}, 0}, 1};
items[1] = (item_t){'B', {{&items[0].node, &items[2].node}, 1}, 2};
items[2] = (item_t){'C', {{NULL, NULL}, 0}, 3};
items[3] = (item_t){'D', {{&items[1].node, &items[5].node}, 0}, 4};
items[4] = (item_t){'E', {{NULL, NULL}, 0}, 5};
items[5] = (item_t){'F', {{&items[4].node, &items[6].node}, 1}, 6};
items[6] = (item_t){'G', {{NULL, NULL}, 0}, 7};
printf("printing sanity tree\n");
print_tree(&items[3].node);
}
void construct_and_insert(cosmos_red_black_tree_t* tree, item_t* item,
char label, uint64_t sort_key) {
item->label = label;
item->sort_key = sort_key;
cosmos_red_black_construct(&item->node);
cosmos_red_black_push(tree, &item->node);
if (!is_rb_correct(*tree)) {
printf("incorrect tree inserting %" PRIu64 ":\n", sort_key);
print_tree(*tree);
abort();
}
}
void build_and_print() {
cosmos_red_black_tree_t tree = NULL;
item_t items[7];
printf("no nodes\n");
print_tree(tree);
for (int i = 0; i < 7; ++i) {
printf("%d node%s\n", i + 1, i != 0 ? "s" : "");
construct_and_insert(&tree, items + i, 'A' + i, i + 1);
print_tree(tree);
}
}
static inline void swap(uint64_t* a, uint64_t* b) {
uint64_t temp = *a;
*a = *b;
*b = temp;
}
void stress() {
static const size_t num_nodes = 2 << 12;
uint64_t nums[num_nodes];
for (size_t i = 0; i < num_nodes; ++i) {
nums[i] = i;
}
// janky shuffle
srand(time(NULL));
for (size_t i = 0; i < num_nodes - 1; ++i) {
swap(nums + i, nums + i + 1 + (rand() % (num_nodes - i - 1)));
}
printf("stress adding %zu things in random order\n", num_nodes);
cosmos_red_black_tree_t tree = NULL;
item_t items[num_nodes];
for (size_t i = 0; i < num_nodes; ++i) {
construct_and_insert(&tree, items + i, 'X', nums[i]);
}
printf("stress popping %zu those things from front\n", num_nodes);
for (size_t i = 0; i < num_nodes; ++i) {
cosmos_red_black_node_t* popped = cosmos_red_black_pop_min(&tree);
assert(popped != NULL);
if (!is_rb_correct(tree)) {
printf("incorrect tree popping %" PRIu64 "\n",
container_of(popped, item_t, node)->sort_key);
print_tree(tree);
abort();
}
}
assert(tree == NULL);
}
void time_test() {
static const size_t max_num_nodes = 2 << 10;
uint64_t nums[max_num_nodes];
for (size_t num_nodes = 8; num_nodes < max_num_nodes; num_nodes <<= 1) {
for (size_t i = 0; i < num_nodes; ++i) {
nums[i] = i;
}
// janky shuffle
srand(time(NULL));
for (size_t i = 0; i < num_nodes - 1; ++i) {
swap(nums + i, nums + i + 1 + (rand() % (num_nodes - i - 1)));
}
clock_t start = clock();
cosmos_red_black_tree_t tree = NULL;
item_t items[num_nodes];
for (size_t i = 0; i < num_nodes; ++i) {
construct_and_insert(&tree, items + i, 'X', nums[i]);
}
clock_t t = clock() - start;
printf("adding %4zu things took %9" PRId64 " µs (log => %5.02f)\n",
num_nodes, ((uint64_t)t * 1000000) / CLOCKS_PER_SEC, log((double)t));
start = clock();
for (size_t i = 0; i < num_nodes; ++i) {
cosmos_red_black_node_t* popped = cosmos_red_black_pop_min(&tree);
assert(popped != NULL);
if (!is_rb_correct(tree)) {
printf("incorrect tree popping %" PRIu64 "\n",
container_of(popped, item_t, node)->sort_key);
print_tree(tree);
abort();
}
}
t = clock() - start;
printf("popping %4zu things took %9" PRId64 " µs (log => %5.02f)\n",
num_nodes, ((uint64_t)t * 1000000) / CLOCKS_PER_SEC, log((double)t));
assert(tree == NULL);
}
}
int main() {
print_sanity_tree();
assert_tree_invalid();
build_and_print();
stress();
time_test();
return 0;
}
|
code/data_structures/test/tree/multiway_tree/union_find/test_union_find.cpp | #include <iostream>
#include <cassert>
#include "../../../../src/tree/multiway_tree/union_find/union_find_dynamic.cpp"
int main()
{
UnionFind<int> unionFind;
unionFind.merge(3, 4);
unionFind.merge(3, 8);
unionFind.merge(0, 8);
unionFind.merge(1, 3);
unionFind.merge(7, 9);
unionFind.merge(5, 9);
// Now the components are:
// 0 1 3 4 8
// 5 7 9
assert(unionFind.connected(0, 1));
assert(unionFind.connected(0, 3));
assert(unionFind.connected(0, 4));
assert(unionFind.connected(0, 8));
assert(unionFind.connected(1, 3));
assert(unionFind.connected(1, 4));
assert(unionFind.connected(1, 8));
assert(unionFind.connected(3, 4));
assert(unionFind.connected(3, 8));
assert(unionFind.connected(4, 8));
assert(unionFind.connected(5, 7));
assert(unionFind.connected(5, 9));
assert(unionFind.connected(7, 9));
assert(!unionFind.connected(0, 5));
assert(!unionFind.connected(0, 7));
assert(!unionFind.connected(0, 9));
assert(!unionFind.connected(1, 5));
assert(!unionFind.connected(1, 7));
assert(!unionFind.connected(1, 9));
assert(!unionFind.connected(3, 5));
assert(!unionFind.connected(3, 7));
assert(!unionFind.connected(3, 9));
assert(!unionFind.connected(4, 5));
assert(!unionFind.connected(4, 7));
assert(!unionFind.connected(4, 9));
assert(!unionFind.connected(8, 5));
assert(!unionFind.connected(8, 7));
assert(!unionFind.connected(8, 9));
return 0;
}
|
code/data_structures/test/tree/segment_tree/test_generic_segment_tree.cpp | #include <algorithm>
#include <iostream>
#include <vector>
// Note that the below line includes a translation unit and not header file
#include "../../../src/tree/segment_tree/generic_segment_tree.cpp"
#define ASSERT(value, expected_value, message) \
{ \
if (value != expected_value) \
std::cerr << "[assertion failed]\n" \
<< " Line: " << __LINE__ << '\n' \
<< " File: " << __FILE__ << '\n' \
<< "Message: " << message << std::endl; \
else \
std::cerr << "[assertion passed]: " << message << std::endl; \
}
/**
* This program tests the generic segment tree implementation that can be found in the include location above.
* The implementation requires C++20 in order to compile.
*
* Compilation: g++ test_generic_segment_tree.cpp -o test_generic_segment_tree -Wall -Wextra -pedantic -std=c++20 -O3
*/
constexpr bool is_multitest = false;
constexpr int32_t inf32 = int32_t(1) << 30;
constexpr int64_t inf64 = int64_t(1) << 60;
void test () {
std::vector <int> values = { 1, 2, 3, 4, 5 };
int n = values.size();
arrow::SegmentTree <int> binaryTreeSum (n, values, [] (auto l, auto r) {
return l + r;
});
arrow::SegmentTree <int, arrow::TreeMemoryLayout::EulerTour> eulerTourTreeSum (n, values, [] (auto l, auto r) {
return l + r;
});
ASSERT(binaryTreeSum.rangeQuery(0, 4), 15, "binaryTreeSum.rangeQuery(0, 4) == 15");
ASSERT(binaryTreeSum.rangeQuery(1, 2), 5, "binaryTreeSum.rangeQuery(1, 2) == 5");
ASSERT(binaryTreeSum.rangeQuery(4, 4), 5, "binaryTreeSum.rangeQuery(4, 4) == 5");
ASSERT(binaryTreeSum.rangeQuery(2, 4), 12, "binaryTreeSum.rangeQuery(2, 4) == 12");
ASSERT(binaryTreeSum.rangeQuery(0, 3), 10, "binaryTreeSum.rangeQuery(0, 3) == 10");
ASSERT(eulerTourTreeSum.rangeQuery(0, 4), 15, "eulerTourTreeSum.rangeQuery(0, 4) == 15");
ASSERT(eulerTourTreeSum.rangeQuery(1, 2), 5, "eulerTourTreeSum.rangeQuery(1, 2) == 5");
ASSERT(eulerTourTreeSum.rangeQuery(4, 4), 5, "eulerTourTreeSum.rangeQuery(4, 4) == 5");
ASSERT(eulerTourTreeSum.rangeQuery(2, 4), 12, "eulerTourTreeSum.rangeQuery(2, 4) == 12");
ASSERT(eulerTourTreeSum.rangeQuery(0, 3), 10, "eulerTourTreeSum.rangeQuery(0, 3) == 10");
binaryTreeSum.pointUpdate(2, 10);
eulerTourTreeSum.pointUpdate(0, 8);
ASSERT(binaryTreeSum.pointQuery(2), 10, "binaryTreeSum.pointQuery(2) == 10");
ASSERT(binaryTreeSum.rangeQuery(1, 3), 16, "binaryTreeSum.rangeQuery(1, 3) == 16");
ASSERT(binaryTreeSum.rangeQuery(0, 4), 22, "binaryTreeSum.rangeQuery(0, 4) == 22");
ASSERT(eulerTourTreeSum.pointQuery(0), 8, "euler_tour_sum.pointQuery(0) == 8");
ASSERT(eulerTourTreeSum.rangeQuery(1, 3), 9, "euler_tour_sum.rangeQuery(1, 3) == 9");
ASSERT(eulerTourTreeSum.rangeQuery(0, 4), 22, "euler_tour_sum.rangeQuery(0, 4) == 22");
values = {
2, -4, 3, -1, 4, 1, -2, 5
};
n = values.size();
struct node {
int value;
int maxPrefix;
int maxSuffix;
int maxSubsegment;
node (int v = 0) {
int m = std::max(v, 0);
value = v;
maxPrefix = m;
maxSuffix = m;
maxSubsegment = m;
}
};
std::vector <node> node_values;
for (auto i: values) {
node_values.push_back(node(i));
}
arrow::SegmentTree <node> binaryTreeMaxSubsegment (n, node_values, [] (auto l, auto r) {
node result;
result.value = l.value + r.value;
result.maxPrefix = std::max(l.maxPrefix, l.value + r.maxPrefix);
result.maxSuffix = std::max(l.maxSuffix + r.value, r.maxSuffix);
result.maxSubsegment = std::max({l.maxSubsegment, r.maxSubsegment, l.maxSuffix + r.maxPrefix});
return result;
});
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 7).value, 8, "binaryTreeMaxSubsegment.rangeQuery(0, 7).value == 8");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(3, 5).value, 4, "binaryTreeMaxSubsegment.rangeQuery(3, 5).value == 4");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(2, 6).value, 5, "binaryTreeMaxSubsegment.rangeQuery(2, 6).value == 5");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(1, 4).value, 2, "binaryTreeMaxSubsegment.rangeQuery(1, 4).value == 2");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(7, 7).value, 5, "binaryTreeMaxSubsegment.rangeQuery(7, 7).value == 5");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 4).value, 4, "binaryTreeMaxSubsegment.rangeQuery(0, 4).value == 4");
binaryTreeMaxSubsegment.pointUpdate(5, 4);
binaryTreeMaxSubsegment.pointUpdate(3, -7);
binaryTreeMaxSubsegment.pointUpdate(1, 3);
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 7).value, 12, "binaryTreeMaxSubsegment.rangeQuery(0, 7).value == 12");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(3, 5).value, 1, "binaryTreeMaxSubsegment.rangeQuery(3, 5).value == 1");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(2, 6).value, 2, "binaryTreeMaxSubsegment.rangeQuery(2, 6).value == 2");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(1, 4).value, 3, "binaryTreeMaxSubsegment.rangeQuery(1, 4).value == 3");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(7, 7).value, 5, "binaryTreeMaxSubsegment.rangeQuery(7, 7).value == 5");
ASSERT(binaryTreeMaxSubsegment.rangeQuery(0, 4).value, 5, "binaryTreeMaxSubsegment.rangeQuery(0, 4).value == 5");
}
int main () {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
test();
return 0;
}
|
code/design_pattern/src/OOP_patterns/README.md | # cosmos
Your personal library of every design pattern code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/design_pattern/src/OOP_patterns/__init__.py | |
code/design_pattern/src/OOP_patterns/adapter/adaptor.java | package Adapter;
import Adapter.Soldiers.Adaptee;
import Adapter.Soldiers.General;
public class Adaptor implements Movement {
public Adaptee adaptee;
public General general;
public Adaptor(Adaptee adaptee, General general) {
this.adaptee = adaptee;
this.general = general;
}
@Override
public void walk() {
adaptee.changeWalkStyle(general.receiveOrder());
adaptee.walk();
}
}
|
code/design_pattern/src/OOP_patterns/adapter/civilian.java | package Adapter;
public class Civilian implements Movement {
@Override
public void walk() {
System.out.println("I'm having a beautiful stroll in my happy, little peaceful town.");
}
}
|
code/design_pattern/src/OOP_patterns/adapter/movement.java | package Adapter;
public interface Movement {
void walk();
}
|
code/design_pattern/src/OOP_patterns/adapter/soldiers/adaptee.java | package Adapter.Soldiers;
public interface Adaptee {
void walk();
void changeWalkStyle(Order newStyle);
}
|
code/design_pattern/src/OOP_patterns/adapter/soldiers/general.java | package Adapter.Soldiers;
import Adapter.Movement;
import java.util.List;
public class General {
private Order order;
public List<Adaptee> troopsUnderCommand;
public void setOrder(Order order) {
this.order = order;
}
public Order receiveOrder() {
if (order == null)
return Order.AT_EASE;
return order;
}
}
|
code/design_pattern/src/OOP_patterns/adapter/soldiers/order.java | package Adapter.Soldiers;
public enum Order {
WALKING, RUNNING, STROLLING, LIMPING, AT_EASE
}
|
code/design_pattern/src/OOP_patterns/adapter/soldiers/soldier.java | package Adapter.Soldiers;
public class Soldier implements Adaptee {
private Order order;
@Override
public void walk() {
System.out.println("IM " + order + ", SIR, YES, SIR!");
}
@Override
public void changeWalkStyle(Order newStyle) {
this.order = newStyle;
}
}
|
code/design_pattern/src/OOP_patterns/builder/builder/nationality.java | package builder;
public enum Nationality {
Ro, En, Gr, Br, Ru, Aus
}
|
code/design_pattern/src/OOP_patterns/builder/builder/person.java | package builder;
import java.util.Date;
public class Person {
private String firstname;
private String lastname;
private Date birthdate;
private Nationality nationality;
private boolean isProgrammer;
private Integer iq;
private boolean isPoor;
private boolean isPopular;
private boolean isEmployed;
Person(String firstname,
String lastname,
Date birthdate,
Nationality nationality,
boolean isProgrammer,
Integer iq,
boolean isPoor, boolean isPopular, boolean isEmployed) {
this.firstname = firstname;
this.lastname = lastname;
this.birthdate = birthdate;
this.nationality = nationality;
this.isProgrammer = isProgrammer;
this.iq = iq;
this.isPoor = isPoor;
this.isPopular = isPopular;
this.isEmployed = isEmployed;
}
@Override
public String toString() {
return "Person{" +
"firstname='" + this.firstname + '\'' +
", lastname='" + this.lastname + '\'' +
", birthdate=" + this.birthdate +
", nationality=" + this.nationality +
", isProgrammer=" + this.isProgrammer +
", iq=" + this.iq +
", isPoor=" + this.isPoor +
", isPopular=" + this.isPopular +
", isEmployed=" + this.isEmployed +
'}';
}
}
|
code/design_pattern/src/OOP_patterns/builder/builder/personbuilder.java | package builder;
import org.omg.CORBA.DynAnyPackage.InvalidValue;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Consumer;
public class PersonBuilder {
private String firstname;
private String lastname;
private Date birthdate;
private Nationality nationality = Nationality.Ro;
private boolean isProgrammer = false;
private Integer iq = 100;
private boolean isPoor = false;
private boolean isPopular = false;
private boolean isEmployed = true;
public PersonBuilder with(Consumer<PersonBuilder> builderFunction) {
builderFunction.accept(this);
return this;
}
public Person createPerson() {
return new Person(firstname, lastname, birthdate, nationality, isProgrammer, iq, isPoor,
isPopular, isEmployed);
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setBirthdate(String birthdate) throws InvalidValue, ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = sdf.parse("01-01-1950");
Date date = sdf.parse(birthdate);
if (date.after(d))
this.birthdate = date;
else throw new InvalidValue("You're too old!!");
}
public void setNationality(Nationality nationality) {
this.nationality = nationality;
}
public void setProgrammer(boolean isProgrammer) {
this.isProgrammer = isProgrammer;
}
public void setIq(Integer iq) throws InvalidValue {
if (iq < 30)
throw new InvalidValue("Don't try anything crazy.");
this.iq = iq;
}
public void setPoor(boolean isPoor) {
this.isPoor = isPoor;
}
public void setPopular(boolean isPopular) {
this.isPopular = isPopular;
}
public void setEmployed(boolean isEmployed) {
this.isEmployed = isEmployed;
}
}
|
code/design_pattern/src/OOP_patterns/builder/main.java | import builder.Nationality;
import builder.Person;
import builder.PersonBuilder;
import org.omg.CORBA.DynAnyPackage.InvalidValue;
import java.text.ParseException;
public class Main {
public static void main(String[] args) {
Person person = new PersonBuilder()
.with(personBuilder -> {
personBuilder.setFirstname("Mr.");
personBuilder.setLastname("John");
personBuilder.setNationality(Nationality.En);
personBuilder.setProgrammer(true);
try {
personBuilder.setBirthdate("01-01-1900");
} catch (InvalidValue | ParseException invalidValue) {
invalidValue.printStackTrace();
}
})
.createPerson();
System.out.println(person);
}
}
|
code/design_pattern/src/OOP_patterns/decorator/decorator.ts | interface Component {
operation(): string;
}
interface HelloWorldDecorator {
operation(): string;
}
class ComponentImpl implements Component {
public operation(): string {
return 'This method is decorated';
}
}
// This is the general way to implement decorators
class HelloWorldDecoratorImpl implements HelloWorldDecorator {
private _component: Component;
constructor(component: Component) {
this._component = component;
}
public operation(): string {
return `Hello world! ${this._component.operation()}`;
}
}
let testComponent = new ComponentImpl();
let decoratedTestComponent = new HelloWorldDecoratorImpl(testComponent);
console.log(decoratedTestComponent.operation());
// Here we use TypeScript's built in support for decorators
// What we are using here are class decorators.
// There are also: class property, class method, class accessor
// and class method parameter decorators
@helloWorldClassDecorator
class ComponentAltImpl implements Component {
public operation(): string {
return 'This message will be overriden';
}
}
function helloWorldClassDecorator<T extends { new (...args: any[]): {} }>(constructor: T) {
return class extends constructor implements HelloWorldDecorator {
operation() {
return `Hello world again! ${constructor.prototype.operation()}`;
}
};
}
let syntacticSugarDecorator = new ComponentAltImpl();
console.log(syntacticSugarDecorator.operation());
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/dailyroutinefacade.java | package daily.tasks;
import daily.tasks.evening.routine.EveningRoutineFacade;
import daily.tasks.gym.GymFacade;
import daily.tasks.job.JobFacade;
import daily.tasks.morning.routine.MorningRoutineFacade;
public class DailyRoutineFacade {
public DailyRoutineFacade() {
new MorningRoutineFacade();
new JobFacade();
new GymFacade();
new EveningRoutineFacade();
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/eat.java | package daily.tasks.evening.routine;
class Eat {
Eat() {
System.out.println("Dinner - or mostly not");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/eveningroutinefacade.java | package daily.tasks.evening.routine;
public class EveningRoutineFacade {
public EveningRoutineFacade() {
System.out.println("\n\n\t\tEvening Routine\n\n");
new Eat();
new TakeAShower();
new WriteCode();
new WatchYoutubeVideos();
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/takeashower.java | package daily.tasks.evening.routine;
class TakeAShower {
TakeAShower() {
System.out.println("Im taking a good ol' scrub");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/watchyoutubevideos.java | package daily.tasks.evening.routine;
class WatchYoutubeVideos {
WatchYoutubeVideos() {
System.out.println("Im watching some youtube videos");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/writecode.java | package daily.tasks.evening.routine;
class WriteCode {
WriteCode() {
System.out.println("Probably writing some Scala code");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/benchpress.java | package daily.tasks.gym;
class BenchPress {
BenchPress() {
System.out.println("Gotta bench 140 at least");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/deadlift.java | package daily.tasks.gym;
class Deadlift {
Deadlift() {
System.out.println("Deadlifting 100kg at least");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/gymfacade.java | package daily.tasks.gym;
public class GymFacade {
public GymFacade() {
System.out.println("\n\n\t\tGym Routine\n\n");
new Deadlift();
new BenchPress();
new Squat();
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/squat.java | package daily.tasks.gym;
class Squat {
Squat() {
System.out.println("Squatting is awesome");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/develop.java | package daily.tasks.job;
class Develop {
Develop() {
System.out.println("I'm writing some basic code");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/eatatwork.java | package daily.tasks.job;
class EatAtWork {
EatAtWork() {
System.out.println("This shaorma tastes great!");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/jobfacade.java | package daily.tasks.job;
public class JobFacade {
public JobFacade() {
System.out.println("\n\n\t\tJob Routine\n\n");
new Develop();
new WatchYoutubeVideos();
new PlayFifa();
new EatAtWork();
new Develop();
new Develop();
new WatchYoutubeVideos();
new Leave();
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/leave.java | package daily.tasks.job;
class Leave {
Leave() {
System.out.println("I'm leaving home");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/playfifa.java | package daily.tasks.job;
class PlayFifa {
PlayFifa() {
System.out.println("I'm playing fifa");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/watchyoutubevideos.java | package daily.tasks.job;
class WatchYoutubeVideos {
WatchYoutubeVideos() {
System.out.println("I'm watching Youtube videos");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/dress.java | package daily.tasks.morning.routine;
class Dress {
Dress() {
System.out.println("Dress");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/eat.java | package daily.tasks.morning.routine;
class Eat {
Eat() {
System.out.println("Im eating");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/leave.java | package daily.tasks.morning.routine;
class Leave {
Leave() {
System.out.println("Im leaving home");
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/morningroutinefacade.java | package daily.tasks.morning.routine;
public class MorningRoutineFacade {
public MorningRoutineFacade() {
System.out.println("\n\n\t\tMorning Routine\n\n");
new WakeUp();
new Eat();
new Dress();
new Leave();
}
}
|
code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/wakeup.java | package daily.tasks.morning.routine;
class WakeUp {
WakeUp() {
System.out.println("Woken up");
}
}
|
code/design_pattern/src/OOP_patterns/facade/facade | The whole purpose of Facade is to "aggregate" multiple classes and functionality into a single place, thus acting like
well... a Facade - beautiful on the outside, but hiding all the complexity of the "inside building". The example
is taken to the extreme to showcase it properly - imagine each class that is managed has a fuckton of logic behind it
that is quite specific and quite hard to understand.
By using the Facade design pattern, that logic is encapsulated in the Facade and easily used. |
code/design_pattern/src/OOP_patterns/facade/main.java | import daily.tasks.DailyRoutineFacade;
public class Main {
public static void main(String[] args) {
new DailyRoutineFacade();
}
}
|
code/design_pattern/src/OOP_patterns/factory/gifts/booze.java | package factory.gifts;
public class Booze implements Gift {
@Override
public String message() {
return "You won booze - get drunk";
}
}
|
code/design_pattern/src/OOP_patterns/factory/gifts/car.java | package factory.gifts;
public class Car implements Gift {
@Override
public String message() {
return "Nobody wins a car, it's a prank, bro";
}
}
|
code/design_pattern/src/OOP_patterns/factory/gifts/gift.java | package factory.gifts;
public interface Gift {
String message();
}
|
code/design_pattern/src/OOP_patterns/factory/gifts/nothing.java | package factory.gifts;
public class Nothing implements Gift {
@Override
public String message() {
return "YOU WON NOTHING!";
}
}
|
code/design_pattern/src/OOP_patterns/factory/gifts/toy.java | package factory.gifts;
public class Toy implements Gift {
@Override
public String message() {
return "You won a toy! Be happy";
}
}
|
code/design_pattern/src/OOP_patterns/factory/gifttype.java | package factory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public enum GiftType {
Nothing, Car, Toy, Booze, Error;
public GiftType fromString(String from) {
if (from.equalsIgnoreCase("nothing"))
return Nothing;
if (from.equalsIgnoreCase("car"))
return Car;
if (from.equalsIgnoreCase("toy"))
return Toy;
if (from.equalsIgnoreCase("booze"))
return Booze;
return Error;
}
private static final List<GiftType> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static GiftType randomGift() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
|
code/design_pattern/src/OOP_patterns/factory/roulette.java | package factory;
import factory.gifts.*;
import java.util.Scanner;
public class Roulette {
public void run() throws InterruptedException {
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Let's see what the russian roulette will give you");
System.out.println(generateGift(GiftType.randomGift()).message());
Thread.sleep(3000);
}
}
public Gift generateGift(GiftType gift) {
switch (gift) {
case Booze:
return new Booze();
case Car:
return new Car();
case Nothing:
return new Nothing();
case Toy:
return new Toy();
case Error:
throw new InvalidValue("Russian roulette is confused");
default:
return new Nothing();
}
}
}
|
code/design_pattern/src/OOP_patterns/observer_java/demo.java | import observer.Observer;
import observer.Subject;
import observer.network.Artist;
import observer.network.Fan;
public class Demo {
public void startDemo() {
Observer f1 = new Fan("Robert");
Observer f2 = new Fan("David");
Observer f3 = new Fan("Gangplank");
Subject<String> s1 = new Artist("Erik Mongrain");
Subject<String> s2 = new Artist("Antoine Dufour");
s1.subscribe(f1);
s1.subscribe(f2);
s2.subscribe(f2);
s2.subscribe(f3);
s1.addNotification("New album coming out!!");
s2.addNotification("I'll be having a concert in Romania!");
s1.addNotification("Im so happy!");
s2.addNotification("How does this work?");
}
}
|
code/design_pattern/src/OOP_patterns/observer_java/main.java | public class Main {
public static void main(String[] args) {
new Demo().startDemo();
}
}
|
code/design_pattern/src/OOP_patterns/observer_java/observer/network/artist.java | package observer.network;
import observer.Observer;
import observer.Subject;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Artist<T extends String> implements Subject {
private Set<Observer> observers;
private String name;
private List<String> updates;
public Artist(String name) {
this.name = name;
this.observers = new HashSet<>();
this.updates = new ArrayList<>();
}
public Artist(Set<Observer> observers) {
this.observers = observers;
this.updates = new ArrayList<>();
}
@Override
public String getLastNotification() {
return "[ " + this.name + " ] " + this.updates.get(this.updates.size() - 1);
}
@Override
public void addNotification(String notification) {
System.out.println("[ " + this.name + " ] " + notification);
updates.add(notification);
this.notifyObservers();
}
@Override
public void subscribe(Observer o) {
this.observers.add(o);
}
@Override
public void unsubscribe(Observer o) {
this.observers.remove(o);
}
@Override
public void notifyObservers() {
observers.forEach(o -> o.receiveNotification(this));
}
}
|
code/design_pattern/src/OOP_patterns/observer_java/observer/network/fan.java | package observer.network;
import observer.Observer;
import java.util.*;
public class Fan implements Observer {
private String name;
private Set<Artist> followedSubjects;
public Fan(String name) {
this.followedSubjects = new HashSet<>();
this.name = name;
}
public Fan(Set<Artist> subjectsToFollow) {
this.followedSubjects = subjectsToFollow;
}
public void addSubject(Artist subject) {
subject.subscribe(this);
this.followedSubjects.add(subject);
}
public Set<Artist> getFollowedSubjects() {
return new HashSet<>(followedSubjects);
}
@Override
public void receiveNotification(observer.Subject from) {
System.out.println("[" + this.name + "] " + from.getLastNotification());
}
}
|
code/design_pattern/src/OOP_patterns/observer_java/observer/observer.java | package observer;
public interface Observer {
void receiveNotification(Subject from);
}
|
code/design_pattern/src/OOP_patterns/observer_java/observer/subject.java | package observer;
public interface Subject<T extends String> {
void subscribe(Observer o);
void unsubscribe(Observer o);
void notifyObservers();
String getLastNotification();
void addNotification(T notification);
}
|
code/design_pattern/src/OOP_patterns/observer_pattern/__init__.py | from .observer_pattern import Notifier, Observer
|
code/design_pattern/src/OOP_patterns/observer_pattern/observer_pattern.cpp | /*
* observer_pattern.cpp
*
* Created on: 26 May 2017
* Author: yogeshb2
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class IWeatherChanger
{
public:
virtual ~IWeatherChanger()
{
}
virtual void onTemperatureChange(int temperature) = 0;
};
class ITemperature
{
public:
virtual ~ITemperature()
{
}
virtual void addSubscriber(IWeatherChanger* w) = 0;
virtual void removeSubscriber(IWeatherChanger* w) = 0;
virtual void notifyAllSubscriber() = 0;
};
class Weather : public ITemperature
{
public:
Weather() : temperature(0)
{
}
void addSubscriber(IWeatherChanger* w)
{
if (w)
subscriberlist.push_back(w);
}
void removeSubscriber(IWeatherChanger* w)
{
//TODO
if (w)
{
vector<IWeatherChanger*>::iterator it =
find(subscriberlist.begin(), subscriberlist.end(), w);
if (it != subscriberlist.end())
subscriberlist.erase(it);
else
cout << "Not a registered subscriber" << endl;
}
}
void notifyAllSubscriber()
{
if (!subscriberlist.empty())
{
vector<IWeatherChanger*>::iterator it;
for (it = subscriberlist.begin(); it != subscriberlist.end(); ++it)
(*it)->onTemperatureChange(temperature);
}
}
void changeTemperature(int temp)
{
temperature = temp;
notifyAllSubscriber();
}
private:
int temperature;
vector<IWeatherChanger*> subscriberlist;
};
class NewsChannel : public IWeatherChanger
{
public:
NewsChannel()
{
}
NewsChannel(string name)
{
this->name = name;
}
void onTemperatureChange(int temperature)
{
cout << "Channel name : " << name << " Temperature : " << temperature;
cout << "\n";
}
private:
string name;
};
int main()
{
Weather weather;
NewsChannel fox("Fox News");
NewsChannel times("Times News");
weather.addSubscriber(&fox);
weather.addSubscriber(×);
weather.changeTemperature(25);
weather.changeTemperature(20);
weather.removeSubscriber(&fox);
weather.changeTemperature(10);
return 0;
}
|
code/design_pattern/src/OOP_patterns/observer_pattern/observer_pattern.py | """
How to use observer:
1. Decorate your observed-class with the Observer class,
which observe some notifier.
2. Implement the update member-function in your the observed-class
which will be passed only one parameter: event and no return.
3. Decorate your notified-class with the Notifier class,
which notify each observer you registered.
example:
class Phone():
def update(self, event):
if event == "earthquake warning":
print("I need to run away.")
class App():
def update(self, event):
if event == "it will rain":
print("I need to buy an umbrella.")
class EmergencyCenter():
pass
class WeatherCenter():
pass
def main():
emergency_center = Notifier(EmergencyCenter())
weather_center = Notifier(WeatherCenter())
my_phone = Observer(Phone())
my_home_weather_app = Observer(App())
emergency_center.attach_observer(my_phone)
my_home_weather_app.attach_notifier(weather_center)
emergency_center.notify("earthquake warning")
weather_center.notify("it will rain")
note:
1. you can attach a notifier to an observer by itself
or attach an observer to a notifier.
"""
class Observer:
def __init__(self, decorator=None):
self._notifiers = {}
self._decorator = decorator
def __getattr__(self, name):
if self._decorator is not None:
return getattr(self._decorator, name)
else:
raise AttributeError
def attach_notifier(self, notifier):
"""
notifier: Notifier-liked instance
"""
self._notifiers[notifier] = notifier.attach_observer(self)
def detach_notifier(self, notifier):
"""
notifier: Notifier-liked instance
"""
notifier.detach_observer(self._notifiers[notifier])
del self._notifiers[notifier]
# class which be decorted needs to impelment this function
def update(self, event):
"""
event: object
"""
return self._decorator.update(event)
class Notifier:
def __init__(self, decorator=None):
self._observers = {}
self._decorator = decorator
def __getattr__(self, name):
if self._decorator is not None:
return getattr(self._decorator, name)
else:
raise AttributeError
def attach_observer(self, observer):
"""
observer: Observer-liked instance
return: int
identify the observer
"""
identifier = len(self._observers)
self._observers[identifier] = observer
return identifier
def detach_observer(self, identifier):
"""
identifier: int
which is returned by attach_observer member-function
"""
del self._observers[identifier]
def notify(self, event):
"""
event: object
"""
for observer in self._observers.values():
observer.update(event)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.