Insert and delete in a multi level sorted linked list - algorithm

2->7->8->11
|
13->16->17->21
|
22->23->27->29
|
30->32
Sorted Linked List given like above where each node has 2 pointers next and down. For each row starting nodes down points to next row start. Each row has 4 elements, except last one which can have <= 4 elements. Next rows start element is greater than previous rows end element. We need to design and code for it insert of new value at correct place and delete operation. I could not solve this problem.

Structure representation and Pseudo code for the add operation is as follows
And we can implement the delete recursively using the add data as example
typedef struct sibling{
int data;
struct sibling *nxt;
} t_sibling
typedef struct children {
struct sibling *sibling;
struct children *nxt;
} t_children;
add_element(t_children **head, int newdata)
{
t_children *walk_down = *head;
t_children *parent = NULL;
while (walk_down != NULL) {
if(parent == NULL && Compare newdata < head of current walk_down->sibling) {
// Code comes here when we add 1 to above mentioned list example
newdata is added to begining to head of walk_down->sibling
sibling_list_count++;
if (sibling_list_count > 4) {
taildata = delete_end from tail of walk_down->sibling
add_element(&walk_down, taildata)
}
break;
}
else if(newdata < head of current walk_down->sibling) {
if (Compare newdata > tail of parent sibling) {
// Code comes here when we add 12 to above mentioned list
newdata is added to begining to head of walk_down->sibling
if (sibling_list_count > 4) {
taildata = delete_end from tail of walk_down->sibling
add_element(&walk_down, taildata)
}
}
else {
// Code comes here when we add 6 to above mentioned list
newdata is added to the appropriate location of parent of sibling
Since above step disturbs the <= 4 property we
taildata = delete_end from tail of parent->sibling
add_element(&walk_down, taildata)
}
break;
}
parent = walk_down;
walk_down = walk_down->nxt;
}
}

Related

Algorithm / data structure for resolving nested interpolated values in this example?

I am working on a compiler and one aspect currently is how to wait for interpolated variable names to be resolved. So I am wondering how to take a nested interpolated variable string and build some sort of simple data model/schema for unwrapping the evaluated string so to speak. Let me demonstrate.
Say we have a string like this:
foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}
That has 1, 2, and 3 levels of nested interpolations in it. So essentially it should resolve something like this:
wait for x, y, one, two, and c to resolve.
when both x and y resolve, then resolve a{x}-{y} immediately.
when both one and two resolve, resolve baz{one}-{two}.
when a{x}-{y}, baz{one}-{two}, and c all resolve, then finally resolve the whole expression.
I am shaky on my understanding of the logic flow for handling something like this, wondering if you could help solidify/clarify the general algorithm (high level pseudocode or something like that). Mainly just looking for how I would structure the data model and algorithm so as to progressively evaluate when the pieces are ready.
I'm starting out trying and it's not clear what to do next:
{
dependencies: [
{
path: [x]
},
{
path: [y]
}
],
parent: {
dependency: a{x}-{y} // interpolated term
parent: {
dependencies: [
{
}
]
}
}
}
Some sort of tree is probably necessary, but I am having trouble figuring out what it might look like, wondering if you could shed some light on that with some pseudocode (or JavaScript even).
watch the leaf nodes at first
then, when the children of a node are completed, propagate upward to resolving the next parent node. This would mean once x and y are done, it could resolve a{x}-{y}, but then wait until the other nodes are ready before doing the final top-level evaluation.
You can just simulate it by sending "events" to the system theoretically, like:
ready('y')
ready('c')
ready('x')
ready('a{x}-{y}')
function ready(variable) {
if ()
}
...actually that may not work, not sure how to handle the interpolated nodes in a hacky way like that. But even a high level description of how to solve this would be helpful.
export type SiteDependencyObserverParentType = {
observer: SiteDependencyObserverType
remaining: number
}
export type SiteDependencyObserverType = {
children: Array<SiteDependencyObserverType>
node: LinkNodeType
parent?: SiteDependencyObserverParentType
path: Array<string>
}
(What I'm currently thinking, some TypeScript)
Here is an approach in JavaScript:
Parse the input string to create a Node instance for each {} term, and create parent-child dependencies between the nodes.
Collect the leaf Nodes of this tree as the tree is being constructed: group these leaf nodes by their identifier. Note that the same identifier could occur multiple times in the input string, leading to multiple Nodes. If a variable x is resolved, then all Nodes with that name (the group) will be resolved.
Each node has a resolve method to set its final value
Each node has a notify method that any of its child nodes can call in order to notify it that the child has been resolved with a value. This may (or may not yet) lead to a cascading call of resolve.
In a demo, a timer is set up that at every tick will resolve a randomly picked variable to some number
I think that in your example, foo, and a might be functions that need to be called, but I didn't elaborate on that, and just considered them as literal text that does not need further treatment. It should not be difficult to extend the algorithm with such function-calling features.
class Node {
constructor(parent) {
this.source = ""; // The slice of the input string that maps to this node
this.texts = []; // Literal text that's not part of interpolation
this.children = []; // Node instances corresponding to interpolation
this.parent = parent; // Link to parent that should get notified when this node resolves
this.value = undefined; // Not yet resolved
}
isResolved() {
return this.value !== undefined;
}
resolve(value) {
if (this.isResolved()) return; // A node is not allowed to resolve twice: ignore
console.log(`Resolving "${this.source}" to "${value}"`);
this.value = value;
if (this.parent) this.parent.notify();
}
notify() {
// Check if all dependencies have been resolved
let value = "";
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (!child.isResolved()) { // Not ready yet
console.log(`"${this.source}" is getting notified, but not all dependecies are ready yet`);
return;
}
value += this.texts[i] + child.value;
}
console.log(`"${this.source}" is getting notified, and all dependecies are ready:`);
this.resolve(value + this.texts.at(-1));
}
}
function makeTree(s) {
const leaves = {}; // nodes keyed by atomic names (like "x" "y" in the example)
const tokens = s.split(/([{}])/);
let i = 0; // Index in s
function dfs(parent=null) {
const node = new Node(parent);
const start = i;
while (tokens.length) {
const token = tokens.shift();
i += token.length;
if (token == "}") break;
if (token == "{") {
node.children.push(dfs(node));
} else {
node.texts.push(token);
}
}
node.source = s.slice(start, i - (tokens.length ? 1 : 0));
if (node.children.length == 0) { // It's a leaf
const label = node.texts[0];
leaves[label] ??= []; // Define as empty array if not yet defined
leaves[label].push(node);
}
return node;
}
dfs();
return leaves;
}
// ------------------- DEMO --------------------
let s = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
const leaves = makeTree(s);
// Create a random order in which to resolve the atomic variables:
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[array[j], array[i]] = [array[i], array[j]];
}
return array;
}
const names = shuffle(Object.keys(leaves));
// Use a timer to resolve the variables one by one in the given random order
let index = 0;
function resolveRandomVariable() {
if (index >= names.length) return; // all done
console.log("\n---------------- timer tick --------------");
const name = names[index++];
console.log(`Variable ${name} gets a value: "${index}". Calling resolve() on the connected node instance(s):`);
for (const node of leaves[name]) node.resolve(index);
setTimeout(resolveRandomVariable, 1000);
}
setTimeout(resolveRandomVariable, 1000);
your idea of building a dependency tree it's really likeable.
Anyway I tryed to find a solution as simplest possible.
Even if it already works, there are many optimizations possible, take this just as proof of concept.
The background idea it's produce a List of Strings which you can read in order where each element it's what you need to solve progressively. Each element might be mandatory to solve something that come next in the List, hence for the overall expression. Once you solved all the chunks you have all pieces to solve your original expression.
It's written in Java, I hope it's understandable.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class StackOverflow {
public static void main(String[] args) {
String exp = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
List<String> chunks = expToChunks(exp);
//it just reverse the order of the list
Collections.reverse(chunks);
System.out.println(chunks);
//output -> [c, two, one, baz{one}-{two}, y, x, a{x}-{y}]
}
public static List<String> expToChunks(String exp) {
List<String> chunks = new ArrayList<>();
//this first piece just find the first inner open parenthesys and its relative close parenthesys
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
//this if put an end to recursive calls
if(begin > 0 && begin < exp.length() && end > 0) {
//add the chunk to the final list
String substring = exp.substring(begin, end);
chunks.add(substring);
//remove from the starting expression the already considered chunk
String newExp = exp.replace("{" + substring + "}", "");
//recursive call for inner element on the chunk found
chunks.addAll(Objects.requireNonNull(expToChunks(substring)));
//calculate other chunks on the remained expression
chunks.addAll(Objects.requireNonNull(expToChunks(newExp)));
}
return chunks;
}
}
Some details on the code:
The following piece find the begin and the end index of the first outer chunk of expression. The background idea is: in a valid expression the number of open parenthesys must be equal to the number of closing parenthesys. The count of open(+1) and close(-1) parenthesys can't ever be negative.
So using that simple loop once I find the count of parenthesys to be 0, I also found the first chunk of the expression.
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
The if condition provide validation on the begin and end indexes and stop the recursive call when no more chunks can be found on the remained expression.
if(begin > 0 && begin < exp.length() && end > 0) {
...
}

Swap Linked list objects

Following code works for sorting of the list (Peter,10) (John,32) (Mary,50) (Carol,31)
Ordered lists:
List 1: (Carol,31) (Carol,31) (John,32) (Mary,50)
however the peter is lost and carol is getting repeated, please help to suggest where Iam going wrong. WHat do I need to change in the loop to get this correct
LinkedList& LinkedList::order()
{
int swapped;
Node *temp;
Node *lptr = NULL;
temp=head;
// Checking for empty list
do
{
swapped = 0 ;
current = head;
while (current->get_next() != lptr)
{
if (current->get_data() > current->get_next()->get_data())
{
temp->set_Node(current->get_data());
current->set_Node(current->get_next()->get_data());
current->get_next()->set_Node(temp->get_data());
swapped = 1;
}
current = current->get_next();
}
lptr = current;
}
while (swapped);
return *this;
}

std::map find fails when key is pointer

I am unable to get the std::map find to locate the correct row in the std::map. The key is a class pointer and I have created a struct (tdEcApplDataMapEq) to compare the class's binary arrays for a match.'
The problem is it doesn't work. I call FoEcApplData::operator== when the find starts. It says the first entry does not a match and then the find returns out pointing to the first item on the std::map list. There is no attempt by find to search the other map entries. Also the one match test failed (false), so why is find saying its a match?
This probably has something to do with the std::map declaration. std::map says the third argument is for std::less, but I am doing a == vs. <.
If I change it to do < the same this happens. It enters FoEcApplData::operator< which return a true on the first check and find search stops with the search pointing to the 1st entry in the list.
How do I get find() to use the custom struct for the search?
My example adds 10 rows to FdTEcApplDataMap. It copies the CDH_DISABLE_XACT182 class into hold for the search later. I then do the find() test using hold as the search key.
Inside entry1
Inside entry2
Inside entry3<== this is the one I am searching for
Inside entry4
Inside entry5
Inside entry6
Inside entry7
Inside entry8
Inside entry9
Inside entry10
Inside entry1
This is the find:
auto hazard = ExcludedCmdDict.find(&hold);
if(hazard != ExcludedCmdDict.end())
{
std::cout << "found it " << hazard->second << std::endl;
}
This is the compare function being used:
bool FoEcApplData::operator==( const FoEcApplData& FoEcApplDataObject) const {
if(myNumOfBytes <= FoEcApplDataObject.NumOfBytes())
{
const EcTOctet* temp;
temp = FoEcApplDataObject.Data() ;
for(EcTInt i = 0; i < myNumOfBytes ; i++)
{
if(myData[i] != temp[i])
{
return false ;
}
}
return true;
}
else // myNumOfBytes > FoEcApplDataObject.NumOfBytes()
{
const EcTOctet* temp;
temp = FoEcApplDataObject.Data() ;
for(EcTInt i = 0; i < FoEcApplDataObject.NumOfBytes(); i++)
{
if(myData[i] != temp[i])
{
return false ;
}
}
return true;
}
}
This is the declaration for the std::map.
/*
Custom less for find on the FdTEcApplDataMap.
Needed since we are using pointers.
Returns - true - match, false - no match
node - pointer to the item you are looking for
node2 - pointer to an item on the list
*/
struct tdEcApplDataMapEq {
bool operator()(FoEcApplData *const& node, FoEcApplData *const& node2) const
{
return *node == *node2;
}
};
typedef std::map< FoEcApplData *, std::string, tdEcApplDataMapEq> FdTEcApplDataMap;
std::map expects the compare function to work like std::less. You need to use something along the lines of:
struct tdEcApplDataMapEq {
bool operator()(FoEcApplData *const& node, FoEcApplData *const& node2) const
{
return (*node < *node2); // Implement operator<() function for FoEcApplData
}
};
While at it, change the name of the struct to reflect the fact that it is trying to compute "less than".
struct tdEcApplDataMapLess {
bool operator()(FoEcApplData *const& node, FoEcApplData *const& node2) const
{
return (*node < *node2); // Implement operator<() function for FoEcApplData
}
};

data structure for sorted browsing history

Suppose i want to implement the browser history functionality. If i visit the the url for this first time it goes into the history , if i visit the same page again it comes up in the history list.
lets say that i only display the top 20 sites, but i can choose to see history say for the last month , last week and so on .
what is the best approach for this ? i would use hash map for inserting / checking if it is visited earlier , but how do i sort efficiently for recently visited, i don't want to use tree map or tree set . also, how can i store history of weeks and months. Is it written on disk when browser closes ? and when i click clear history , how is the data structure deleted ?
This is in Java-ish code.
You'll need two data structures: a hash map and a doubly linked list. The doubly linked list contains History objects (which contain a url string and a timestamp) in order sorted by timestamp; the hash map is a Map<String, History>, with urls as the key.
class History {
History prev
History next
String url
Long timestamp
void remove() {
prev.next = next
next.prev = prev
next = null
prev = null
}
}
When you add a url to the history, check to see if it's in the hash map; if it is then update its timestamp, remove it from the linked list, and add it to the end of the linked list. If it's not in the hash map then add it to the hash map and also add it to the end of the linked list. Adding a url (whether or not it's already in the hash map) is a constant time operation.
class Main {
History first // first element of the linked list
History last // last element of the linked list
HashMap<String, History> map
void add(String url) {
History hist = map.get(url)
if(hist != null) {
hist.remove()
hist.timestamp = System.currenttimemillis()
} else {
hist = new History(url, System.currenttimemillis())
map.add(url, hist)
}
last.next = hist
hist.prev = last
last = hist
}
}
To get the history from e.g. the last week, traverse the linked list backwards until you hit the correct timestamp.
If thread-safety is a concern, then use a thread-safe queue for urls to be added to the history, and use a single thread to process this queue; this way your map and linked list don't need to be thread-safe i.e. you don't need to worry about locks etc.
For persistence you can serialize / deserialize the linked list; when you deserialize the linked list, reconstruct the hash map by traversing it and adding its elements to the map. Then to clear the history you'd null the list and map in memory and delete the file you serialized the data to.
A more efficient solution in terms of memory consumption and IO (i.e. (de)serialization cost) is to use a serverless database like SQLite; this way you won't need to keep the history in memory, and if you want to get the history from e.g. the last week you'd just need to query the database rather than traversing the linked list. However, SQLite is essentially a treemap (specifically a B-Tree, which is optimized for data stored on disk).
Here is a Swift 4.0 implementation based on Zim-Zam O'Pootertoot's answer, including an iterator for traversing the history:
import Foundation
class SearchHistory: Sequence {
var first: SearchHistoryItem
var last: SearchHistoryItem
var map = [String: SearchHistoryItem]()
var count = 0
var limit: Int
init(limit: Int) {
first = SearchHistoryItem(name: "")
last = first
self.limit = Swift.max(limit, 2)
}
func add(name: String) {
var item: SearchHistoryItem! = map[name]
if item != nil {
if item.name == last.name {
last = last.prev!
}
item.remove()
item.timestamp = Date()
} else {
item = SearchHistoryItem(name: name)
count += 1
map[name] = item
if count > limit {
first.next!.remove()
count -= 1
}
}
last.next = item
item.prev = last
last = item
}
func makeIterator() -> SearchHistory.SearchHistoryIterator {
return SearchHistoryIterator(item: last)
}
struct SearchHistoryIterator: IteratorProtocol {
var currentItem: SearchHistoryItem
init(item: SearchHistoryItem) {
currentItem = item
}
mutating func next() -> SearchHistoryItem? {
var item: SearchHistoryItem? = nil
if let prev = currentItem.prev {
item = currentItem
currentItem = prev
}
return item
}
}
}
class SearchHistoryItem {
var prev: SearchHistoryItem?
var next: SearchHistoryItem?
var name: String
var timestamp: Date
init(name: String) {
self.name = name
timestamp = Date()
}
func remove() {
prev?.next = next
next?.prev = prev
next = nil
prev = nil
}
}

Binary Search Tree remove node function

I am working on a binary search tree and i have been given an insertnode function that looks like
void insertNode(Node **t, Node *n)
{
if(!(*t))
*t=n;
else if((*t)->key<n->key)insertNode(&(*t)->right,n);
else if((*t)->key>n->key) insertNode(&(*t)->left,n);
}
I am trying to write a function that removes nodes recursively so far i have come up with:
void remove(int huntKey,Node **t)
{
bool keyFound=false;
if(!(*t))
cout<<"There are no nodes"<<endl;
while(keyFound==false)
{
if((*t)->key==huntKey)
{
keyFound=true;
(*t)->key=0;
}
else if((*t)->key < huntKey)remove(huntKey,&(*t)->right);
else if((*t)->key> huntKey) remove(huntKey,&(*t)->left);
}
}
Both of these functions are getting called from a switch in my main function which looks like:
int main()
{
int key=0,countCatch=0;char q;
Node *t, *n;
t=0;
while((q=menu()) !=0)
{
switch(q)
{
case'?': menu(); break;
case'i': inOrderPrint(t); break;
case'a': preOrderPrint(t); break;
case'b': postOrderPrint(t); break;
case'c': {cout<<"enter key: ";cin>>key;
n=createNode(key);insertNode(&t,n);break;}
case'r':{cout<<"enter the key you want removed: ";
cin>>key;
remove(key,&t);
break;}
case'n': {countCatch=countNodes(t);cout<<countCatch<<"\n"; };break;
}
}
return 0;
}
my remove node function is not working properly....any advice would help....
When you remove the node, you are only setting its key to '0', not actually removing it.
Example:
'4' has child '2,' which has children '1' and '3.'
In your code, removing '2' gives you this tree: 4 has child 0, which has children 1 and 3.
To remove an internal node (a node with children), you must handle its parent pointer and its children. You must set the parent's child-pointer to one of the removed node's children. Check this article for more:
http://en.wikipedia.org/wiki/Binary_tree#Deletion
Look at the code, it is not recursive though
http://code.google.com/p/cstl/source/browse/src/c_rb.c

Resources