SlideShare a Scribd company logo
1 of 7
Download to read offline
Describe a data structure to represent sets of elements (each element with a unique key) that
would support the following operations: insert(x, A) - insert an element x into A (assume the key
of x is not in .4 yet) count (A, k) - return the number of elements in A with key at least k.
Solution
we can use Hashset for this.a simple code in hashset is given below
public class MyNode
{
...
}
public class MyDataStructure
{
private HashSet nodes = new HashSet();
///
/// Inserts an element to this data structure.
/// If the element already exists, returns false.
/// Complexity is averaged O(1).
///
public bool Add(MyNode node)
{
return node != null && this.nodes.Add(node);
}
///
/// Removes a random element from the data structure.
/// Returns the element if an element was found.
/// Returns null if the data structure is empty.
/// Complexity is averaged O(1).
///
public MyNode Pop()
{
// This loop can execute 1 or 0 times.
foreach (MyNode node in nodes)
{
this.nodes.Remove(node);
return node;
}
return null;
}
}
the unique key can also be achieved using dictioneries
hence code for this is given below:
public class FixedIntDictionary
{
// Our internal node structure.
// We use structs instead of objects to not add pressure to the garbage collector.
// We mantains our own way to manage garbage through the use of a free list.
private struct Entry
{
// The key of the node
internal int Key;
// Next index in pEntries array.
// This field is both used in the free list, if node was removed
// or in the table, if node was inserted.
// -1 means null.
internal int Next;
// The value of the node.
internal T Value;
}
// The actual hash table. Contains indices to pEntries array.
// The hash table can be seen as an array of singlt linked list.
// We store indices to pEntries array instead of objects for performance
// and to avoid pressure to the garbage collector.
// An index -1 means null.
private int[] pBuckets;
// This array contains the memory for the nodes of the dictionary.
private Entry[] pEntries;
// This is the first node of a singly linked list of free nodes.
// This data structure is called the FreeList and we use it to
// reuse removed nodes instead of allocating new ones.
private int pFirstFreeEntry;
// Contains simply the number of items in this dictionary.
private int pCount;
// Contains the number of used entries (both in the dictionary or in the free list) in pEntries
array.
// This field is going only to grow with insertions.
private int pEntriesCount;
///
/// Creates a new FixedIntDictionary.
/// tableBucketsCount should be a prime number
/// greater than the number of items that this
/// dictionary should store.
/// The performance of this hash table will be very bad
/// if you don't follow this rule!
///
public FixedIntDictionary(int tableBucketsCount)
{
// Our free list is initially empty.
this.pFirstFreeEntry = -1;
// Initializes the entries array with a minimal amount of items.
this.pEntries = new Entry[8];
// Allocate buckets and initialize every linked list as empty.
int[] buckets = new int[capacity];
for (int i = 0; i < buckets.Length; ++i)
buckets[i] = -1;
this.pBuckets = buckets;
}
///Gets the number of items in this dictionary. Complexity is O(1).
public int Count
{
get { return this.pCount; }
}
///
/// Adds a key value pair to the dictionary.
/// Complexity is averaged O(1).
/// Returns false if the key already exists.
///
public bool Add(int key, T value)
{
// The hash table can be seen as an array of linked list.
// We find the right linked list using hash codes.
// Since the hash code of an integer is the integer itself, we have a perfect hash.
// After we get the hash code we need to remove the sign of it.
// To do that in a fast way we and it with 0x7FFFFFFF, that means, we remove the sign bit.
// Then we have to do the modulus of the found hash code with the size of our buckets
array.
// For this reason the size of our bucket array should be a prime number,
// this because the more big is the prime number, the less is the chance to find an
// hash code that is divisible for that number. This reduces collisions.
// This implementation will not grow the buckets table when needed, this is the major
// problem with this implementation.
// Growing requires a little more code that i don't want to write now
// (we need a function that finds prime numbers, and it should be fast and we
// need to rehash everything using the new buckets array).
int bucketIndex = (key & 0x7FFFFFFF) % this.pBuckets.Length;
int bucket = this.pBuckets[bucketIndex];
// Now we iterate in the linked list of nodes.
// Since this is an hash table we hope these lists are very small.
// If the number of buckets is good and the hash function is good this will translate usually
// in a O(1) operation.
Entry[] entries = this.pEntries;
for (int current = entries[bucket]; current != -1; current = entries[current].Next)
{
if (entries[current].Key == key)
{
// Entry already exists.
return false;
}
}
// Ok, key not found, we can add the new key and value pair.
int entry = this.pFirstFreeEntry;
if (entry != -1)
{
// We found a deleted node in the free list.
// We can use that node without "allocating" another one.
this.pFirstFreeEntry = entries[entry].Next;
}
else
{
// Mhhh ok, the free list is empty, we need to allocate a new node.
// First we try to use an unused node from the array.
entry = this.pEntriesCount++;
if (entry >= this.pEntries)
{
// Mhhh ok, the entries array is full, we need to make it bigger.
// Here should go also the code for growing the bucket table, but i'm not writing it
here.
Array.Resize(ref this.pEntries, this.pEntriesCount * 2);
entries = this.pEntries;
}
}
// Ok now we can add our item.
// We just overwrite key and value in the struct stored in entries array.
entries[entry].Key = key;
entries[entry].Value = value;
// Now we add the entry in the right linked list of the table.
entries[entry].Next = this.pBuckets[bucketIndex];
this.pBuckets[bucketIndex] = entry;
// Increments total number of items.
++this.pCount;
return true;
}
///
/// Gets a value that indicates wether the specified key exists or not in this table.
/// Complexity is averaged O(1).
///
public bool Contains(int key)
{
// This translate in a simple linear search in the linked list for the right bucket.
// The operation, if array size is well balanced and hash function is good, will be almost
O(1).
int bucket = this.pBuckets[(key & 0x7FFFFFFF) % this.pBuckets.Length];
Entry[] entries = this.pEntries;
for (int current = entries[bucket]; current != -1; current = entries[current].Next)
{
if (entries[current].Key == key)
{
return true;
}
}
return false;
}
///
/// Removes the specified item from the dictionary.
/// Returns true if item was found and removed, false if item doesn't exists.
/// Complexity is averaged O(1).
///
public bool Remove(int key)
{
// Removal translate in a simple contains and removal from a singly linked list.
// Quite simple.
int bucketIndex = (key & 0x7FFFFFFF) % this.pBuckets.Length;
int bucket = this.pBuckets[bucketIndex];
Entry[] entries = this.pEntries;
int next;
int prev = -1;
int current = entries[bucket];
while (current != -1)
{
next = entries[current].Next;
if (entries[current].Key == key)
{
// Found! Remove from linked list.
if (prev != -1)
entries[prev].Next = next;
else
this.pBuckets[bucketIndex] = next;
// We now add the removed node to the free list,
// so we can use it later if we add new elements.
entries[current].Next = this.pFirstFreeEntry;
this.pFirstFreeEntry = current;
// Decrements total number of items.
--this.pCount;
return true;
}

More Related Content

Similar to Describe a data structure to represent sets of elements (each element.pdf

C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfcallawaycorb73779
 
Please complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxPlease complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxcgraciela1
 
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfHomework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfezzi97
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfmaheshkumar12354
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfamirthagiftsmadurai
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docxajoy21
 
Note- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdfNote- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdfStewart29UReesa
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdfdeepakangel
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfvishalateen
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfankit11134
 
To complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdfTo complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdfezycolours78
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
Objective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfObjective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfadvancethchnologies
 
Objective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfObjective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfgiriraj65
 
Linked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdfLinked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdfadityacomputers001
 
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdfDividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdftesmondday29076
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfConint29
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
 

Similar to Describe a data structure to represent sets of elements (each element.pdf (20)

C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
 
Please complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docxPlease complete all the code as per instructions in Java programming.docx
Please complete all the code as per instructions in Java programming.docx
 
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdfHomework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
Homework 05 - Linked Lists (C++)(1) Implement the concepts of a un.pdf
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdf
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdf
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docx
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
Note- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdfNote- Can someone help me with the Public boolean add(E value) method.pdf
Note- Can someone help me with the Public boolean add(E value) method.pdf
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdf
 
To complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdfTo complete the task, you need to fill in the missing code. I’ve inc.pdf
To complete the task, you need to fill in the missing code. I’ve inc.pdf
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
Objective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfObjective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdf
 
Objective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfObjective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdf
 
Linked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdfLinked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdf
 
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdfDividing a linked list into two sublists of almost equal sizesa. A.pdf
Dividing a linked list into two sublists of almost equal sizesa. A.pdf
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 

More from rajeshjain2109

Find the volume using the shaded base. T F The same volume can be fo.pdf
Find the volume using the shaded base.  T F The same volume can be fo.pdfFind the volume using the shaded base.  T F The same volume can be fo.pdf
Find the volume using the shaded base. T F The same volume can be fo.pdfrajeshjain2109
 
Explain how PCBs affect different trophic levels in fish, birds, and .pdf
Explain how PCBs affect different trophic levels in fish, birds, and .pdfExplain how PCBs affect different trophic levels in fish, birds, and .pdf
Explain how PCBs affect different trophic levels in fish, birds, and .pdfrajeshjain2109
 
During the global recession of 2008 and 2009, there were many accusa.pdf
During the global recession of 2008 and 2009, there were many accusa.pdfDuring the global recession of 2008 and 2009, there were many accusa.pdf
During the global recession of 2008 and 2009, there were many accusa.pdfrajeshjain2109
 
Discuss the assumption that explains why one subtracts one half of t.pdf
Discuss the assumption that explains why one subtracts one half of t.pdfDiscuss the assumption that explains why one subtracts one half of t.pdf
Discuss the assumption that explains why one subtracts one half of t.pdfrajeshjain2109
 
10) Which of the following best describes trend analysis A) calculat.pdf
10) Which of the following best describes trend analysis A) calculat.pdf10) Which of the following best describes trend analysis A) calculat.pdf
10) Which of the following best describes trend analysis A) calculat.pdfrajeshjain2109
 
A variety of peach, Desert Peach, has a uniformly skin that is mainly.pdf
A variety of peach, Desert Peach, has a uniformly skin that is mainly.pdfA variety of peach, Desert Peach, has a uniformly skin that is mainly.pdf
A variety of peach, Desert Peach, has a uniformly skin that is mainly.pdfrajeshjain2109
 
, not floatSolutionFloat -while doing programming you need .pdf
, not floatSolutionFloat -while doing programming you need .pdf, not floatSolutionFloat -while doing programming you need .pdf
, not floatSolutionFloat -while doing programming you need .pdfrajeshjain2109
 
b. Which of the following is a permanent account vi. Revenue vii. A.pdf
b. Which of the following is a permanent account vi. Revenue vii. A.pdfb. Which of the following is a permanent account vi. Revenue vii. A.pdf
b. Which of the following is a permanent account vi. Revenue vii. A.pdfrajeshjain2109
 
1. List two reasons why postmenopausal women are at higher risks for.pdf
1. List two reasons why postmenopausal women are at higher risks for.pdf1. List two reasons why postmenopausal women are at higher risks for.pdf
1. List two reasons why postmenopausal women are at higher risks for.pdfrajeshjain2109
 
AI short essay need help ASAPWhat are the professional, ethical, .pdf
AI short essay need help ASAPWhat are the professional, ethical, .pdfAI short essay need help ASAPWhat are the professional, ethical, .pdf
AI short essay need help ASAPWhat are the professional, ethical, .pdfrajeshjain2109
 
Content chapter 2 Serving time in virginia Pocabontas saved captain.pdf
Content chapter 2 Serving time in virginia Pocabontas saved captain.pdfContent chapter 2 Serving time in virginia Pocabontas saved captain.pdf
Content chapter 2 Serving time in virginia Pocabontas saved captain.pdfrajeshjain2109
 
1. Find a formula for the trigonometric function graphed below. Use .pdf
1. Find a formula for the trigonometric function graphed below. Use .pdf1. Find a formula for the trigonometric function graphed below. Use .pdf
1. Find a formula for the trigonometric function graphed below. Use .pdfrajeshjain2109
 
Why does Staphylococcus probably cause more contamination than even .pdf
Why does Staphylococcus probably cause more contamination than  even .pdfWhy does Staphylococcus probably cause more contamination than  even .pdf
Why does Staphylococcus probably cause more contamination than even .pdfrajeshjain2109
 
why is it that cholera and other fecal oral disease continue to be a.pdf
why is it that cholera and other fecal oral disease continue to be a.pdfwhy is it that cholera and other fecal oral disease continue to be a.pdf
why is it that cholera and other fecal oral disease continue to be a.pdfrajeshjain2109
 
Which standards organization defined the Ethernet standardA. IEEE.pdf
Which standards organization defined the Ethernet standardA. IEEE.pdfWhich standards organization defined the Ethernet standardA. IEEE.pdf
Which standards organization defined the Ethernet standardA. IEEE.pdfrajeshjain2109
 
Which of the following is UNLIKELY to be important for the generatio.pdf
Which of the following is UNLIKELY to be important for the generatio.pdfWhich of the following is UNLIKELY to be important for the generatio.pdf
Which of the following is UNLIKELY to be important for the generatio.pdfrajeshjain2109
 
Following WWII, a rift emerged between the capitalist nations of the.pdf
Following WWII, a rift emerged between the capitalist nations of the.pdfFollowing WWII, a rift emerged between the capitalist nations of the.pdf
Following WWII, a rift emerged between the capitalist nations of the.pdfrajeshjain2109
 
What are the benefits and costs of using a common currency for Germa.pdf
What are the benefits and costs of using a common currency for Germa.pdfWhat are the benefits and costs of using a common currency for Germa.pdf
What are the benefits and costs of using a common currency for Germa.pdfrajeshjain2109
 
What is the difference of the rational expression below 14x17-3x1.pdf
What is the difference of the rational expression below  14x17-3x1.pdfWhat is the difference of the rational expression below  14x17-3x1.pdf
What is the difference of the rational expression below 14x17-3x1.pdfrajeshjain2109
 
The enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdf
The enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdfThe enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdf
The enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdfrajeshjain2109
 

More from rajeshjain2109 (20)

Find the volume using the shaded base. T F The same volume can be fo.pdf
Find the volume using the shaded base.  T F The same volume can be fo.pdfFind the volume using the shaded base.  T F The same volume can be fo.pdf
Find the volume using the shaded base. T F The same volume can be fo.pdf
 
Explain how PCBs affect different trophic levels in fish, birds, and .pdf
Explain how PCBs affect different trophic levels in fish, birds, and .pdfExplain how PCBs affect different trophic levels in fish, birds, and .pdf
Explain how PCBs affect different trophic levels in fish, birds, and .pdf
 
During the global recession of 2008 and 2009, there were many accusa.pdf
During the global recession of 2008 and 2009, there were many accusa.pdfDuring the global recession of 2008 and 2009, there were many accusa.pdf
During the global recession of 2008 and 2009, there were many accusa.pdf
 
Discuss the assumption that explains why one subtracts one half of t.pdf
Discuss the assumption that explains why one subtracts one half of t.pdfDiscuss the assumption that explains why one subtracts one half of t.pdf
Discuss the assumption that explains why one subtracts one half of t.pdf
 
10) Which of the following best describes trend analysis A) calculat.pdf
10) Which of the following best describes trend analysis A) calculat.pdf10) Which of the following best describes trend analysis A) calculat.pdf
10) Which of the following best describes trend analysis A) calculat.pdf
 
A variety of peach, Desert Peach, has a uniformly skin that is mainly.pdf
A variety of peach, Desert Peach, has a uniformly skin that is mainly.pdfA variety of peach, Desert Peach, has a uniformly skin that is mainly.pdf
A variety of peach, Desert Peach, has a uniformly skin that is mainly.pdf
 
, not floatSolutionFloat -while doing programming you need .pdf
, not floatSolutionFloat -while doing programming you need .pdf, not floatSolutionFloat -while doing programming you need .pdf
, not floatSolutionFloat -while doing programming you need .pdf
 
b. Which of the following is a permanent account vi. Revenue vii. A.pdf
b. Which of the following is a permanent account vi. Revenue vii. A.pdfb. Which of the following is a permanent account vi. Revenue vii. A.pdf
b. Which of the following is a permanent account vi. Revenue vii. A.pdf
 
1. List two reasons why postmenopausal women are at higher risks for.pdf
1. List two reasons why postmenopausal women are at higher risks for.pdf1. List two reasons why postmenopausal women are at higher risks for.pdf
1. List two reasons why postmenopausal women are at higher risks for.pdf
 
AI short essay need help ASAPWhat are the professional, ethical, .pdf
AI short essay need help ASAPWhat are the professional, ethical, .pdfAI short essay need help ASAPWhat are the professional, ethical, .pdf
AI short essay need help ASAPWhat are the professional, ethical, .pdf
 
Content chapter 2 Serving time in virginia Pocabontas saved captain.pdf
Content chapter 2 Serving time in virginia Pocabontas saved captain.pdfContent chapter 2 Serving time in virginia Pocabontas saved captain.pdf
Content chapter 2 Serving time in virginia Pocabontas saved captain.pdf
 
1. Find a formula for the trigonometric function graphed below. Use .pdf
1. Find a formula for the trigonometric function graphed below. Use .pdf1. Find a formula for the trigonometric function graphed below. Use .pdf
1. Find a formula for the trigonometric function graphed below. Use .pdf
 
Why does Staphylococcus probably cause more contamination than even .pdf
Why does Staphylococcus probably cause more contamination than  even .pdfWhy does Staphylococcus probably cause more contamination than  even .pdf
Why does Staphylococcus probably cause more contamination than even .pdf
 
why is it that cholera and other fecal oral disease continue to be a.pdf
why is it that cholera and other fecal oral disease continue to be a.pdfwhy is it that cholera and other fecal oral disease continue to be a.pdf
why is it that cholera and other fecal oral disease continue to be a.pdf
 
Which standards organization defined the Ethernet standardA. IEEE.pdf
Which standards organization defined the Ethernet standardA. IEEE.pdfWhich standards organization defined the Ethernet standardA. IEEE.pdf
Which standards organization defined the Ethernet standardA. IEEE.pdf
 
Which of the following is UNLIKELY to be important for the generatio.pdf
Which of the following is UNLIKELY to be important for the generatio.pdfWhich of the following is UNLIKELY to be important for the generatio.pdf
Which of the following is UNLIKELY to be important for the generatio.pdf
 
Following WWII, a rift emerged between the capitalist nations of the.pdf
Following WWII, a rift emerged between the capitalist nations of the.pdfFollowing WWII, a rift emerged between the capitalist nations of the.pdf
Following WWII, a rift emerged between the capitalist nations of the.pdf
 
What are the benefits and costs of using a common currency for Germa.pdf
What are the benefits and costs of using a common currency for Germa.pdfWhat are the benefits and costs of using a common currency for Germa.pdf
What are the benefits and costs of using a common currency for Germa.pdf
 
What is the difference of the rational expression below 14x17-3x1.pdf
What is the difference of the rational expression below  14x17-3x1.pdfWhat is the difference of the rational expression below  14x17-3x1.pdf
What is the difference of the rational expression below 14x17-3x1.pdf
 
The enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdf
The enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdfThe enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdf
The enzyme KosI recognizes and cleaves the sequence GNNNNC (where N=.pdf
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 

Recently uploaded (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 

Describe a data structure to represent sets of elements (each element.pdf

  • 1. Describe a data structure to represent sets of elements (each element with a unique key) that would support the following operations: insert(x, A) - insert an element x into A (assume the key of x is not in .4 yet) count (A, k) - return the number of elements in A with key at least k. Solution we can use Hashset for this.a simple code in hashset is given below public class MyNode { ... } public class MyDataStructure { private HashSet nodes = new HashSet(); /// /// Inserts an element to this data structure. /// If the element already exists, returns false. /// Complexity is averaged O(1). /// public bool Add(MyNode node) { return node != null && this.nodes.Add(node); } /// /// Removes a random element from the data structure. /// Returns the element if an element was found. /// Returns null if the data structure is empty. /// Complexity is averaged O(1). /// public MyNode Pop() { // This loop can execute 1 or 0 times. foreach (MyNode node in nodes) { this.nodes.Remove(node); return node;
  • 2. } return null; } } the unique key can also be achieved using dictioneries hence code for this is given below: public class FixedIntDictionary { // Our internal node structure. // We use structs instead of objects to not add pressure to the garbage collector. // We mantains our own way to manage garbage through the use of a free list. private struct Entry { // The key of the node internal int Key; // Next index in pEntries array. // This field is both used in the free list, if node was removed // or in the table, if node was inserted. // -1 means null. internal int Next; // The value of the node. internal T Value; } // The actual hash table. Contains indices to pEntries array. // The hash table can be seen as an array of singlt linked list. // We store indices to pEntries array instead of objects for performance // and to avoid pressure to the garbage collector. // An index -1 means null. private int[] pBuckets; // This array contains the memory for the nodes of the dictionary. private Entry[] pEntries; // This is the first node of a singly linked list of free nodes. // This data structure is called the FreeList and we use it to // reuse removed nodes instead of allocating new ones. private int pFirstFreeEntry;
  • 3. // Contains simply the number of items in this dictionary. private int pCount; // Contains the number of used entries (both in the dictionary or in the free list) in pEntries array. // This field is going only to grow with insertions. private int pEntriesCount; /// /// Creates a new FixedIntDictionary. /// tableBucketsCount should be a prime number /// greater than the number of items that this /// dictionary should store. /// The performance of this hash table will be very bad /// if you don't follow this rule! /// public FixedIntDictionary(int tableBucketsCount) { // Our free list is initially empty. this.pFirstFreeEntry = -1; // Initializes the entries array with a minimal amount of items. this.pEntries = new Entry[8]; // Allocate buckets and initialize every linked list as empty. int[] buckets = new int[capacity]; for (int i = 0; i < buckets.Length; ++i) buckets[i] = -1; this.pBuckets = buckets; } ///Gets the number of items in this dictionary. Complexity is O(1). public int Count { get { return this.pCount; } } /// /// Adds a key value pair to the dictionary. /// Complexity is averaged O(1). /// Returns false if the key already exists. ///
  • 4. public bool Add(int key, T value) { // The hash table can be seen as an array of linked list. // We find the right linked list using hash codes. // Since the hash code of an integer is the integer itself, we have a perfect hash. // After we get the hash code we need to remove the sign of it. // To do that in a fast way we and it with 0x7FFFFFFF, that means, we remove the sign bit. // Then we have to do the modulus of the found hash code with the size of our buckets array. // For this reason the size of our bucket array should be a prime number, // this because the more big is the prime number, the less is the chance to find an // hash code that is divisible for that number. This reduces collisions. // This implementation will not grow the buckets table when needed, this is the major // problem with this implementation. // Growing requires a little more code that i don't want to write now // (we need a function that finds prime numbers, and it should be fast and we // need to rehash everything using the new buckets array). int bucketIndex = (key & 0x7FFFFFFF) % this.pBuckets.Length; int bucket = this.pBuckets[bucketIndex]; // Now we iterate in the linked list of nodes. // Since this is an hash table we hope these lists are very small. // If the number of buckets is good and the hash function is good this will translate usually // in a O(1) operation. Entry[] entries = this.pEntries; for (int current = entries[bucket]; current != -1; current = entries[current].Next) { if (entries[current].Key == key) { // Entry already exists. return false; } } // Ok, key not found, we can add the new key and value pair. int entry = this.pFirstFreeEntry; if (entry != -1) {
  • 5. // We found a deleted node in the free list. // We can use that node without "allocating" another one. this.pFirstFreeEntry = entries[entry].Next; } else { // Mhhh ok, the free list is empty, we need to allocate a new node. // First we try to use an unused node from the array. entry = this.pEntriesCount++; if (entry >= this.pEntries) { // Mhhh ok, the entries array is full, we need to make it bigger. // Here should go also the code for growing the bucket table, but i'm not writing it here. Array.Resize(ref this.pEntries, this.pEntriesCount * 2); entries = this.pEntries; } } // Ok now we can add our item. // We just overwrite key and value in the struct stored in entries array. entries[entry].Key = key; entries[entry].Value = value; // Now we add the entry in the right linked list of the table. entries[entry].Next = this.pBuckets[bucketIndex]; this.pBuckets[bucketIndex] = entry; // Increments total number of items. ++this.pCount; return true; } /// /// Gets a value that indicates wether the specified key exists or not in this table. /// Complexity is averaged O(1). /// public bool Contains(int key) { // This translate in a simple linear search in the linked list for the right bucket.
  • 6. // The operation, if array size is well balanced and hash function is good, will be almost O(1). int bucket = this.pBuckets[(key & 0x7FFFFFFF) % this.pBuckets.Length]; Entry[] entries = this.pEntries; for (int current = entries[bucket]; current != -1; current = entries[current].Next) { if (entries[current].Key == key) { return true; } } return false; } /// /// Removes the specified item from the dictionary. /// Returns true if item was found and removed, false if item doesn't exists. /// Complexity is averaged O(1). /// public bool Remove(int key) { // Removal translate in a simple contains and removal from a singly linked list. // Quite simple. int bucketIndex = (key & 0x7FFFFFFF) % this.pBuckets.Length; int bucket = this.pBuckets[bucketIndex]; Entry[] entries = this.pEntries; int next; int prev = -1; int current = entries[bucket]; while (current != -1) { next = entries[current].Next; if (entries[current].Key == key) { // Found! Remove from linked list. if (prev != -1) entries[prev].Next = next;
  • 7. else this.pBuckets[bucketIndex] = next; // We now add the removed node to the free list, // so we can use it later if we add new elements. entries[current].Next = this.pFirstFreeEntry; this.pFirstFreeEntry = current; // Decrements total number of items. --this.pCount; return true; }