Josephus problem 0 1 2 3 4 0 1 2 3 (J(N-1, K) + K) mod N = J(N, K) J(1, K) = 0 N=5, K=3 Ak K=2 a N.

Slides:



Advertisements
Similar presentations
1 Linked Lists Continued Lecture 5 Copying and sorting singly linked lists Lists with head and last nodes Doubly linked lists ADS2 Lecture 5.
Advertisements

Queues and Linked Lists
Doubly Linked List This problem can be easily solved by using the double linked list. - Ed. 2 and 3.: Chapter 4 - Ed. 4: Chapter 3.
1 Array-based Implementation An array Q of maximum size N Need to keep track the front and rear of the queue: f: index of the front object r: index immediately.
Senem Kumova Metin Spring2009 STACKS AND QUEUES Chapter 10 in A Book on C.
Queues1 Part-B2 Queues. Queues2 The Queue ADT (§4.3) The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme.
© 2004 Goodrich, Tamassia Linked Lists1. © 2004 Goodrich, Tamassia Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data.
The Ranked Sequence ADT Definition A ranked sequence is a collection of items arranged in a linear order, where each item has a rank defining the relative.
3 May Linked Lists CSE 2011 Winter Linked Lists2 Singly Linked Lists (3.2) A singly linked list is a concrete data structure consisting of.
CSC 212 – Data Structures Lecture 22: PositionList.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
1 Queues (5.2) CSE 2011 Winter May Announcements York Programming Contest Link also available from.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
Queues. What is a queue? First-in first-out data structure (FIFO) New objects are placed at rear Removal restricted to front Examples?
Queues. What is a queue? First-in first-out data structure (FIFO) New objects are placed at rear Removal restricted to front Examples?
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
Linked Lists1 Part-B3 Linked Lists. Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data structure consisting of a sequence.
© 2004 Goodrich, Tamassia Linked Lists1. © 2004 Goodrich, Tamassia Linked Lists2 Singly Linked List (§ 4.4.1) A singly linked list is a concrete data.
Stacks, Queues & Deques CSC212.
Singly Linked Lists - Ed. 2, 3: Chapter 4 - Ed. 4.: Chapter 3.
CSC 212 Stacks & Queues. Announcement Daily quizzes accepted electronically only  Submit via one or other Dropbox  Cannot force you to compile & test.
Vectors, Lists, and Sequences - Ed. 2 and 3.: Chapter 5 - Ed. 4: Chapter 6.
CSC 212 – Data Structures Lecture 21: IndexList a/k/a Vector, ArrayList.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
Lists. The Position Abstract Data Type A positionp, which is associated with some elemente in a list S, does not change, even if the rank ofe changes.
TOP – DOWN Splay Trees Bottom-up splaying requires traversal from root to the node that is to be splayed, and then rotating back to the root – in other.
Stacks and Linked Lists. Abstract Data Types (ADTs) An ADT is an abstraction of a data structure that specifies – Data stored – Operations on the data.
Linear Data Structures
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
CS212D : DATA STRUCTURES 1 Week 5-6 Linked List. Outline 2  Singly Linked Lists  Doubly Linked Lists  Recursions.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Problem of the Day Bezout acquired 19 camels through his trading skill, “Of the collected camels,” it said in the late merchant’s will, “Exactly half go.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
STACKS AND QUEUES 1. Outline 2  Stacks  Queues.
Queue FIFO (First In First Out) Java Doc peek, element offer poll, add
Mohammad Amin Kuhail M.Sc. (York, UK) University of Palestine Faculty of Engineering and Urban planning Software Engineering Department Computer Science.
The List ADT Definition A list is a collection of objects, called nodes, connected in a chain by links. There may or may not be an ordering relationship.
Analysis of Midterm-Examination Sept. 2015ACS-2947 Yangjun Chen1 1.(a)How to define an abstract data type?(2) How to implement an abstract data type? (b)Describe.
Lecture 3 Queues Queues1. queue: – Retrieves elements in the order they were added. – First-In, First-Out ("FIFO") – Elements are stored in order of insertion.
Question of the Day  Two English words change their pronunciation when their first letter is capitalized. What are they?
LECTURE 27: DEQUES CSC 212 – Data Structures. Roses are red and violets are blue Implement push, pop, & top And you’re a Stack too! Stack & ADT Memory.
CS 367 Introduction to Data Structures Lecture 5.
Parasol Lab, Dept. CSE, Texas A&M University
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
1 COMP9024: Data Structures and Algorithms Week Four: Stacks and Queues Hui Wu Session 1, 2016
© 2004 Goodrich, Tamassia Queues. © 2004 Goodrich, Tamassia Stacks2 The Queue ADT The Queue ADT stores arbitrary objects Insertions and deletions follow.
Linked List, Stacks Queues
Elementary Data Structures
Queue FIFO (First In First Out) Java Doc peek, element poll, remove
Double-Ended Queues Chapter 5.
Linked List Stacks, Linked List Queues, Dequeues
COMP9024: Data Structures and Algorithms
COMP9024: Data Structures and Algorithms
CS212D: Data Structures Week 5-6 Linked List.
Stacks.
Sequences 8/2/ :13 AM Linked Lists Linked Lists.
Priority Queue.
CS212D: Data Structures Week 5-6 Linked List.
Stacks Linked Lists Queues Heaps Hashes
Sequences 12/8/2018 3:02 AM Linked Lists Linked Lists.
ADT list.
Stacks and Queues 1.
Copyright © Aiman Hanna All rights reserved
The List ADT Definition A list is a collection of objects, called nodes, connected in a chain by links. There may or may not be an ordering relationship.
Header and Trailer Sentinels
CS210- Lecture 6 Jun 13, 2005 Announcements
The Ranked Sequence ADT
Stacks and Linked Lists
Presentation transcript:

Josephus problem (J(N-1, K) + K) mod N = J(N, K) J(1, K) = 0 N=5, K=3 Ak K=2 a N = b0b1b2b3...bn J(N, 2) = b1b2b3...bnb0

Stack - interface public interface Stack { public int size(); public boolean isEmpty(); public E top() throws EmptyStackException; public void push (E element) throws FullStackException; public E pop() throws EmptyStackException; } ArrayStack A = new ArrayStack (100); A.push(7); o = A.pop();

public class ArrayStack implements Stack { protected int capacity; public static final int CAPACITY = 1000; protected E S[]; protected int top = -1; public ArrayStack(int cap) { capacity = cap; S = (E[]) new Object[capacity]; } public void push(E element) throws FullStackException { if (size() == capacity) throw new FullStackException(“full."); S[++top] = element; } public E pop() throws EmptyStackException { E element; if (isEmpty()) throw new EmptyStackException("empty."); element = S[top]; S[top--] = null; return element; } Stack – implementation

Queue - interface public interface Queue { public int size(); public boolean isEmpty(); public E front() throws EmptyQueueException; public void enqueue (E element); public E dequeue() throws EmptyQueueException; }

Node public class Node { private E element; private Node next; public Node() {this(null, null); } public Node(E e, Node n) { element = e; next = n; } public E getElement() { return element; } public Node getNext() { return next; } public void setElement(E newElem) { element = newElem; } public void setNext(Node newNext) { next = newNext; }

Queue public void enqueue(E elem) { Node node = new Node (); node.setElement(elem); node.setNext(null); if (size == 0) front = node; else rear.setNext(node); rear = node; size++; } public E dequeue() throws EmptyQueueException { if (size == 0) throw new EmptyQueueException("Queue is empty."); E tmp = front.getElement(); front = front.getNext(); size--; if (size == 0) rear = null; return tmp; }

Queue public void enqueue(E elem) { Node node = new Node (); node.setElement(elem); if (size == 0) node.setNext(node); else { node.setNext(rear.getNext()); rear.setNext(node); } rear = node; size++; } public E dequeue() throws EmptyQueueException { if (size == 0) throw new EmptyQueueException("Queue is empty."); size--; E tmp = rear.getNext().getElement(); if (size == 0) rear = null; else read.setNext(rear.getNext().getNext()); return tmp; }

Node - Stack public class NodeStack implements Stack { protected Node top; protected int size; public NodeStack() { top = null; size = 0; } public void push(E elem) { Node v = new Node (elem, top); top = v; size++; } public E top() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException("empty."); return top.getElement(); } public E pop() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException("empty."); E temp = top.getElement(); top = top.getNext(); size--; return temp; }

Balík - interface public interface Deque { public int size(); public boolean isEmpty(); public E getFirst() throws EmptyDequeException; public E getLast() throws EmptyDequeException; public void addFirst (E element); public void addLast (E element); public E removeFirst() throws EmptyDequeException; public E removeLast() throws EmptyDequeException; }

DLNode public class DLNode { private E element; private DLNode prev, next; public DLNode() { this(null, null, null); } public DLNode(E e, Node p, Node n) { element = e; next = n; prev = p; } public E getElement() { return element; } public Node getNext() { return next; } public void setElement(E newElem) { element = newElem; }..

Balík – implementácia public class NodeDeque implements Deque { protected DLNode header, trailer; protected int size; public NodeDeque() { header = new DLNode (); trailer = new DLNode (); header.setNext(trailer); trailer.setPrev(header); size = 0; } public E getFirst() throws EmptyDequeException { if (isEmpty()) throw new EmptyDequeException("Deque is empty."); return header.getNext().getElement(); }

Balík - implementácia public void addFirst(E o) { DLNode second = header.getNext(); DLNode first = new DLNode (o, header, second); second.setPrev(first); header.setNext(first); size++; } public E removeLast() throws EmptyDequeException { if (isEmpty()) throw new EmptyDequeException("Deque is empty."); DLNode last = trailer.getPrev(); E o = last.getElement(); DLNode secondtolast = last.getPrev(); trailer.setPrev(secondtolast); secondtolast.setNext(trailer); size--; return o; }

IndexList - interface public interface IndexList { public int size(); public boolean isEmpty(); public void add(int i, E e) throws IndexOutOfBoundsException; public E get(int i) throws IndexOutOfBoundsException; public E remove(int i)throws IndexOutOfBoundsException; public E set(int i, E e)throws IndexOutOfBoundsException; }

IndexList - implementation public class ArrayIndexList implements IndexList { private E[] A; private int capacity = 16; private int size = 0; public ArrayIndexList() { A = (E[]) new Object[capacity]; } public void add(int r, E e) throws IndexOutOfBoundsException { checkIndex(r, size() + 1); if (size == capacity) {// an overflow capacity *= 2; E[] B =(E[]) new Object[capacity]; for (int i=0; i<size; i++) B[i] = A[i]; A = B; } for (int i=size-1; i>=r; i--) A[i+1] = A[i]; A[r] = e; size++; } public E remove(int r) throws IndexOutOfBoundsException { checkIndex(r, size()); E temp = A[r]; for (int i=r; i<size-1; i++)// shift elements down A[i] = A[i+1]; size--; return temp; }

Skip list lepší ako red-black tree alebo hash tabluľky find, insert aj delete sú priemerne O(log n) insert je stabilný, t.j. zachováva pôvodné usporiadanie rôvnakých kľúčov in-place algoritmus – žiadna extra pamäť

SkipList node public class SkipNode { public int nodeHeight; public int key; public SkipNode[] Nodes; public SkipNode(int value,int h) { nodeHeight = h; key = value; Nodes = new SkipNode[h+1]; for (int i = 1; i <= h; i++) Nodes[i] = null; } public static final int MaxNodeValue = 65536; public static final int MinNodeValue = 0; }

SkipList find public int find(int key) { SkipNode tmp = head; for (int h = curHeight; h >= 1; h-- ) { while ( tmp.Nodes[h].key < key ) tmp = tmp.Nodes[h]; update[h] = tmp; if (tmp.Nodes[h].key == key) return key; } return SkipNode.MinNodeValue - 1; }

SkipList Insert

public boolean insert(int k) { int level = 0; SkipNode[] update = new SkipNode[maxHeight+1]; ……. // find k… if (tmp.Nodes[1].key == k ) return false;// duplicate key else { for(level = 1; (Math.random() < 0.5) && (level < maxHeight); level++) ; level = newLevel(); if ( level > curHeight ) { for ( int i = curHeight + 1; i <= level; i++ ) update[i] = head; curHeight = level; } tmp = new SkipNode(k,level); for ( int i = 1; i <= level; i++ ) { tmp.Nodes[i] = update[i].Nodes[i]; update[i].Nodes[i] = tmp; } return true; }

SkipList delete

Stromy AVL Tree (1962) B-Tree (Bayer,1971) 2-3 Red-Black (Sedgewick,1978) Splay Tree (Tarjan,1986) Tree-Forest

AVL Node class AVLNode { int x; AVLNode left, right; public AVLNode (int init) { x = init; left = null; right = null; } public int height () { int l = (left != null)?(left.height () + 1):0; int r = (right != null)?(right.height () + 1):0; return (l > r)?l:r; }

AVL Tree public AVLNode insert (int k) { if (k < x) if (left == null) left = new AVLNode (k); else left = left.insert (k); else if (right == null) right = new AVLNode (k); else right = right.insert (k); … pokračuje public int balance () { int l = (left != null)?(left.height () + 1):0; int r = (right != null)?(right.height () + 1):0; return (r - l); }

Rotate public AVLNode rotateLeft() { AVLNode tmp = right; right = tmp.left; tmp.left = this; return tmp; } public AVLNode rotateRight() { AVLNode tmp = left; left = tmp.right; tmp.right = this; return tmp; }

Balancing public AVLNode insert (int k) { if (k < x)... pokračovanie... if (balance () < -1) { if (k < left.x) return rotateRight (); else { left = left.rotateLeft (); return rotateRight (); } else if (balance () > 1) { if (k > right.x) return rotateLeft (); else { right = right.rotateRight (); return rotateLeft(); } return this;

Splay Trees Ak je spracovávaný uzol key, aplikuje sa metóda splay(key), Ak strom obsahuje key, splay(key) spôsobí, že vybuble do koreňa, Inak, koreň je najväčší kľúč key, Bublaním sa key približuje do koreňa transformáciami: –Zig-Zag, –Zig-Zig –Zig

Splay find/insert public int find(int key) { if (root == null) return -1; splay(key); if(root.key != key) return -1; return root.key; } public void insert(int key) { if (root == null) { root = new BinaryNode(key); return; } splay(key); if (key == root.key) return; // not found BinaryNode n = new BinaryNode(key); if (key < root.key) { n.left = root.left; n.right = root; root.left = null; } else { n.right = root.right; n.left = root; root.right = null; } root = n; }

private void moveToRoot(int key) { BinaryNode l, r, t; l = r = header; t = root; header.left = header.right = null; for (;;) { if (key < t.key) { if (t.left == null) break; r.left = t; /* link right */ r = t; t = t.left; } else if (key > t.key) { if (t.right == null) break; l.right = t; /* link left */ l = t; t = t.right; } else break; } l.right = t.left; /* assemble */ r.left = t.right; t.left = header.right; t.right = header.left; root = t; } Top-down T TLTR L R T L R TLTR

X Y YLYr XR LR LR X Y YLYr Zig

Zig-Zig X Y ZL Zr XR L R Z YR LR X XRYR Y ZL Zr Z

Zig-Zag X Y ZL Zr XR L R Z YL L R X XR Y ZL Zr Z YL

Assembling X XLXR L R X L R XLXR

private void splay(int key) { BinaryNode l, r, t, y; l = r = header; t = root; header.left = header.right = null; for (;;) { if (key < t.key) { if (t.left == null) break; if (key < t.left.key) { y = t.left; /* rotate right */ t.left = y.right; y.right = t; t = y; if (t.left == null) break; } r.left = t; /* link right */ r = t; t = t.left; } else if (key > t.key) {..... } else { break; } l.right = t.left; /* assemble */ r.left = t.right; t.left = header.right; t.right = header.left; root = t; } splay

Tree/Forest

import java.util.*; public class Forest { private List > broths; public Forest(List > broths) { this.broths = broths; } public String toString(){ String s = ""; char ch = '['; for(Tree e:broths) { s += ch + e.toString(); ch = ','; } s += "]"; return s; } public boolean find(E key) { for(Tree e:broths) { if (e.find(key)) return true; } return false; }

Tree/Forest public class Tree { private E elem; private Forest sons; public Tree(E elem) { this(elem,null); } public Tree(E elem, Forest sons) { this.elem = elem; this.sons = sons; } public String toString() { if (sons == null) return elem.toString(); else return "("+elem.toString()+":"+sons.toString()+")"; } public boolean find(E key) { if (elem.equals(key)) return true; else if (sons != null) return sons.find(key); else return false; }

Tree/Forest Tree t1 = new Tree (“system"); Tree t2 = new Tree ("system32"); Tree t3 = new Tree ("config"); Tree t123 = new Tree ("WINNT", new Forest (Arrays.asList(t1,t2,t3))); Tree u1 = new Tree ("Universal crack"); Tree u2 = new Tree ("java"); Tree u12 = new Tree ("Program Files", new Forest (Arrays.asList(u1,u2))); Forest disk = new Forest (Arrays.asList(t123,u12)); System.out.println(disk); System.out.println(disk.find("java")); System.out.println(disk.find("kava")); [(WINNT:[system,system32,config]),(Program Files:[Universal crack,java])] true false

Position List - interface public interface Position { E element(); } public interface PositionList { public int size(); public boolean isEmpty(); public Position first(); public Position last(); public Position next(Position p) throwsInvalidPositionException, BoundaryViolationException; public Position prev(Position p) throwsInvalidPositionException, BoundaryViolationException; public void addFirst(E e); public void addLast(E e); public void addAfter(Position p, E e) throwsInvalidPositionException, BoundaryViolationException; public void addBefore(Position p, E e) throwsInvalidPositionException, BoundaryViolationException; public E remove(Position p) throws InvalidPositionException; public E set(Position p, E e) throws InvalidPositionException; }

Position List - DNode public class DNode implements Position { private DNode prev, next; private E element; public DNode(DNode newPrev, DNode newNext, E elem) { prev = newPrev; next = newNext; element = elem; } public E element() throws InvalidPositionException { if ((prev == null) && (next == null)) throw new InvalidPositionException("Position is not in a list!"); return element; } public DNode getNext() { return next; } public DNode getPrev() { return prev; } public void setNext(DNode newNext) { next = newNext; } public void setPrev(DNode newPrev) { prev = newPrev; } public void setElement(E newElement) { element = newElement; } }

Position List – implementácia 1 public class NodePositionList implements PositionList { protected int numElts; protected DNode header, trailer; public NodePositionList() { numElts = 0; header = new DNode (null, null, null); trailer = new DNode (header, null, null); header.setNext(trailer); } protected DNode checkPosition(Position p) throws InvalidPositionException { if (p == null) throw new InvalidPositionException("Null position passed to NodeList"); if (p == header) throw new InvalidPositionException("The header node is not a valid position"); if (p == trailer) throw new InvalidPositionException("The trailer node is not a valid position"); try { DNode temp = (DNode ) p; if ((temp.getPrev() == null) || (temp.getNext() == null)) throw new InvalidPositionException("Position not belong to a valid NodeList"); return temp; } catch (ClassCastException e) { throw new InvalidPositionException("Position is of wrong type for this list"); }

public Position first() throws EmptyListException { if (isEmpty()) throw new EmptyListException("List is empty"); return header.getNext(); } public Position prev(Position p) throws InvalidPositionException, BoundaryViolationException { DNode v = checkPosition(p); DNode prev = v.getPrev(); if (prev == header) throw new BoundaryViolationException("Cannot advance past the beginning of list"); return prev; } public void addBefore(Position p, E element) throws InvalidPositionException { DNode v = checkPosition(p); numElts++; DNode newNode = new DNode (v.getPrev(), v, element); v.getPrev().setNext(newNode); v.setPrev(newNode); } public void addFirst(E element) { numElts++; DNode newNode = new DNode (header, header.getNext(), element); header.getNext().setPrev(newNode); header.setNext(newNode); } Position List – implementácia 2

public E remove(Position p) throws InvalidPositionException { DNode v = checkPosition(p); numElts--; DNode vPrev = v.getPrev(); DNode vNext = v.getNext(); vPrev.setNext(vNext); vNext.setPrev(vPrev); E vElem = v.element(); // unlink the position from the list and make it invalid v.setNext(null); v.setPrev(null); return vElem; } public E set(Position p, E element) throws InvalidPositionException { DNode v = checkPosition(p); E oldElt = v.element(); v.setElement(element); return oldElt; } Position List – implementácia 3