Visualizing pointers - LinkedList in Swift - swift

I'm having some trouble and my brain hurts by reading those "pointers" - how do you efficiently read the pointers and visualizing the pointers?
Here is a simple example below yet daunting task in my brain to read/track of those pointers (previous and next). How do we approach this with less cognitive effort?
How do I see/visualize the removing of node in the linked list is thinking the linked list like a line of people and people pointing (hellish rebuke in dnd 5e) each other if they are previous and next to the person... That helps but not efficiently.
public func remove(node : Node<Element>) -> Element {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
}
else {
head = next
}
if let next = next {
next.previous = prev
}
else {
tail = prev
}
node.previous = nil
node.next = nil
return node.value
}

Draw each node as a box.
In each box, provide a section "pointer". Draw an arrow from the pointer section to another box.
Think of pointers as mailing addresses. Each box (node) has the (mailing) address of the previous and next nodes.
If you remove one node, you have to update the mailing addresses stored in the neighboring nodes so they no longer try top point to the now-missing node.
It is not a big jump from mailing address to memory address, which is what pointers actually store.

Related

In Swift a block to process an html string enters an infinite loop and causes app to break

In my iOS app, I have an auxiliary function that receives an html-formatted string and removes the explicit height tags from images.
This is the complete function:
/// This function removes any explicit height in image tag
/// - Parameter htmlString: target HTML
/// - Returns: string HTML after removing height from any aimge tag
private func removeExplicitHeightFromImgTag(for htmlString: String) -> String {
var result = NSString(string: htmlString)
/// Potential breakpoint / Infinite look: This while loop seems to be causing infinite loop behaviour.
while let imagTagrange = (result as String).firstRangeThatMatches(for: "<img.*height\\s*=\\s*(\\\")?[0-9]+(\\\")?") {
let imageTag = result.substring(with: imagTagrange)
if let heightRange = imageTag.firstRangeThatMatches(for: "height\\s*=\\s*(\\\")[0-9]+(\\\")?") {
let tagWithoutHeight = NSString(string: imageTag).replacingCharacters(in: heightRange, with: "")
result = result.replacingCharacters(in: imagTagrange, with: tagWithoutHeight) as NSString
}
}
return result as String
}
The specific block that seems to be causing havoc is the following:
/// Potential breakpoint / Infinite look: This while loop seems to be causing infinite loop behaviour.
while let imagTagrange = (result as String).firstRangeThatMatches(for: "<img.*height\\s*=\\s*(\\\")?[0-9]+(\\\")?") {
let imageTag = result.substring(with: imagTagrange)
if let heightRange = imageTag.firstRangeThatMatches(for: "height\\s*=\\s*(\\\")[0-9]+(\\\")?") {
let tagWithoutHeight = NSString(string: imageTag).replacingCharacters(in: heightRange, with: "")
result = result.replacingCharacters(in: imagTagrange, with: tagWithoutHeight) as NSString
}
}
The input for this function would be an html block encoded as string, which represents the body of an online article.
For example, the following url: https://www.architecturaldigest.com/story/inside-an-art-filled-hollywood-regency-pied-a-terre
Would be parsed and assigned to the htmlString parameter as:
<div><p>Busting a move to Los Angeles seemed only natural for Houston-based interior designer Garrett Hunter and architect Michael Landrum. Although the two friends maintain independent practices, they share an office space and frequently collaborate on projects. The two are also partners in an ever-evolving, experimental gallery/showroom project that first came to life in Houston in 2016 named Tienda X. Two years later, Hunter and Landrum moved the gallery—which hosts a compelling mix of fine and decorative art spanning the contemporary and the antique—to a Mediterranean-style stone house in Austin. They dubbed the operation Villa X.</p><span><img alt=\"pIn a sitting room a Maison Jansen sofa is accompanied by indigo pillows by Christopher Wrobleski a Spanish Majolica oil...\" src=\"https://media.architecturaldigest.com/photos/601c24457d77c6f2f298922d/master/w_1600%2Cc_limit/2020-11-12-Watsonia-AD0080_r2.jpg\"></span><span><p>In a sitting room...
Could you please help in understanding how to solve this and if there is a way to proceed?
I am really stuck and would be enormously grateful to you :)

Randomly select an array from group of "enabled" arrays

I have a set of four arrays. I also have an option to either enable or disable 3 of the 4 arrays (one is always enabled).
Is there a way to randomly decide which array to pull a value from (of the arrays indicated as enabled)?
I originally was aiming to make a master array and just append the content of the other enabled ones into it, but it proved a little harder than expected. I figured it would be easier to simply randomly select an array to pull the single value from as long as it was "enabled".
I'm currently pulling the value with a simple statement such as
If ????? {
return promptArrayA[desiredIndexA]
} else if { ?????
return promptArrayB[desiredIndexB]
} else if { ?????
return promptArrayC[desiredIndexC]
} else {
return promptArrayD[desiredIndexD]
I'm thinking if I had a "randomizer" that chose one of the enabled arrays, then I can use that as a constraint in an If Statement.
I'm fairly new to Swift so any help is much appreciated. Thank you
You can get the array randomly by doing:
let enabledArrays = [promptArrayA, promptArrayB, promptArrayC, promptArrayD]
let randomIndex = Int.random(in: 0..<enabledArrays.count)
let randomArray = enabledArrays[randomIndex]
return randomArray[desiredIndex]

Build Graph given a SuccessorsFunction and a set of nodes

I would like to build a Guava ImmutableGraph given a set of nodes (starting points) and a SuccessorsFunction. The graph would contain all the nodes reachable from any of the starting node and all the edges seen on the way thanks to the SuccessorsFunction. (E.g., given starting node {a} and successors a → b and b → c, the resulting graph should be {(a, b), (b, c)}.)
I see how I can obtain a Traverser to explore the reachable nodes in a certain order, given starting nodes and a SuccessorsFunction, but it does not meet my needs as I want to obtain a graph, not just the nodes.
It is not very hard to define an algorithm that does this, but it’s subtle enough to deserve trying to re-use an existing solution. I would be surprised if it didn’t exist already in the library. Does it? Or is this requirement not sensible?
I didn’t find this in the related wiki page.
Guava doesn't have this feature built in, so you'll need a custom solution that does some sort of graph traversal (like breadth-first traversal), like the following code snippet.
public static <N> ImmutableGraph<N> buildGraphWithBreadthFirstTraversal(
Iterable<N> startingNodes, SuccessorsFunction<N> successorsFunction) {
MutableGraph<N> result = GraphBuilder.directed().allowsSelfLoops(true).build();
startingNodes.forEach(result::addNode);
Queue<N> nodesRemaining = Queues.newArrayDeque(startingNodes);
while (!nodesRemaining.isEmpty()) {
N next = nodesRemaining.remove();
for (N successor : successorsFunction.successors(next)) {
if (!result.edges().contains(EndpointPair.ordered(next, successor))) {
nodesRemaining.add(successor);
result.putEdge(next, successor);
}
}
}
return ImmutableGraph.copyOf(result);
}
Here is a basic JUnit 5 unit test that confirms the code works when given a starting node and a successorsFunction that together form a cycle of 1 -> 2 -> 4 -> 1.
#Test
void succeedsOnTraversalWithCycle() {
var result =
MoreGraphs.buildGraphWithBreadthFirstTraversal(
ImmutableList.of(1),
node -> {
int nextNode = node * 2;
return nextNode <= 4 ? ImmutableList.of(nextNode) : ImmutableList.of(1);
});
assertThat(result)
.isEqualTo(
GraphBuilder.directed()
.allowsSelfLoops(true)
.immutable()
.putEdge(1, 2)
.putEdge(2, 4)
.putEdge(4, 1)
.build());
}

TActorIterator<T> to T

Im having problems with something,
Im not sure if its my understanding of pointers, or Unreal itself. Here is my code
TArray<Anode> nodes;
TActorIterator<Anode> ActorItr = TActorIterator< Anode >(GetWorld());
while (ActorItr) //Go through EVERY Node and check distance
{
if (this->GetUniqueID() != ActorItr->GetUniqueID())
{
//Check Distance
if (FVector::DistSquared(this->GetActorLocation(), ActorItr->GetActorLocation()) < 262144) //Check the distance between the two nodes.
{
Anode node = ActorItr;
//Anode* node = Cast<Anode>(*ActorItr);
nodes.Add(node); //Calls a error because
//cannot convert from 'TActorIterator<Anode>' to 'Anode'
}
}
}
}
So my issue is i cannot convert the Actor Iterator to my TArray, and i have played around with de-referencing etc, i got it to compile but crash at run-time. Thanks!
Edit: For clarity
i have tried
Anode node = *ActorItr;
but got a error C2440: 'initializing' : cannot convert from 'Anode *' to 'Anode'.
I then tried
Anode *node = *ActorItr;
nodes.Add(*node);
It compiled but created a run time error with unhanded memory or something, i think this is because its just handing the pointer to the TArray without handling the issue (is that right?). I understand the concept i feel, but not the syntax.
The actor iterator is not an actor, so direct assignment doesn't make any sense. Try dereferencing the iterator (Anode* node = *ActorItr;), that operator should be overloaded to return the current element of the iteration, i.e. the node you want to use.

NodeJS: What is the proper way to handling TCP socket streams ? Which delimiter should I use?

From what I understood here, "V8 has a generational garbage collector. Moves objects aound randomly. Node can’t get a pointer to raw string data to write to socket." so I shouldn't store data that comes from a TCP stream in a string, specially if that string becomes bigger than Math.pow(2,16) bytes. (hope I'm right till now..)
What is then the best way to handle all the data that's comming from a TCP socket ? So far I've been trying to use _:_:_ as a delimiter because I think it's somehow unique and won't mess around other things.
A sample of the data that would come would be something_:_:_maybe a large text_:_:_ maybe tons of lines_:_:_more and more data
This is what I tried to do:
net = require('net');
var server = net.createServer(function (socket) {
socket.on('connect',function() {
console.log('someone connected');
buf = new Buffer(Math.pow(2,16)); //new buffer with size 2^16
socket.on('data',function(data) {
if (data.toString().search('_:_:_') === -1) { // If there's no separator in the data that just arrived...
buf.write(data.toString()); // ... write it on the buffer. it's part of another message that will come.
} else { // if there is a separator in the data that arrived
parts = data.toString().split('_:_:_'); // the first part is the end of a previous message, the last part is the start of a message to be completed in the future. Parts between separators are independent messages
if (parts.length == 2) {
msg = buf.toString('utf-8',0,4) + parts[0];
console.log('MSG: '+ msg);
buf = (new Buffer(Math.pow(2,16))).write(parts[1]);
} else {
msg = buf.toString() + parts[0];
for (var i = 1; i <= parts.length -1; i++) {
if (i !== parts.length-1) {
msg = parts[i];
console.log('MSG: '+msg);
} else {
buf.write(parts[i]);
}
}
}
}
});
});
});
server.listen(9999);
Whenever I try to console.log('MSG' + msg), it will print out the whole buffer, so it's useless to see if something worked.
How can I handle this data the proper way ? Would the lazy module work, even if this data is not line oriented ? Is there some other module to handle streams that are not line oriented ?
It has indeed been said that there's extra work going on because Node has to take that buffer and then push it into v8/cast it to a string. However, doing a toString() on the buffer isn't any better. There's no good solution to this right now, as far as I know, especially if your end goal is to get a string and fool around with it. Its one of the things Ryan mentioned # nodeconf as an area where work needs to be done.
As for delimiter, you can choose whatever you want. A lot of binary protocols choose to include a fixed header, such that you can put things in a normal structure, which a lot of times includes a length. In this way, you slice apart a known header and get information about the rest of the data without having to iterate over the entire buffer. With a scheme like that, one can use a tool like:
node-buffer - https://github.com/substack/node-binary
node-ctype - https://github.com/rmustacc/node-ctype
As an aside, buffers can be accessed via array syntax, and they can also be sliced apart with .slice().
Lastly, check here: https://github.com/joyent/node/wiki/modules -- find a module that parses a simple tcp protocol and seems to do it well, and read some code.
You should use the new stream2 api. http://nodejs.org/api/stream.html
Here are some very useful examples: https://github.com/substack/stream-handbook
https://github.com/lvgithub/stick