How do I use Stack in singly linked list - singly-linked-list

I have a program that asks for 5 inputs and asks for a range. The ranges are in singly linked list. Now, if the 5 inputs are in that range, I have to stack push them to that node(range). So it will look like this for example:
range: 20 //max is 99. so it divides 99. for example: 0-19 20-39 40-59 and so on...
[15] [50]
| |
v v
[1] [21] [41] //5 inputs stack pushed to the ranges.
| | |
v V v
[0-19]----->[20-39]----->[40-59]
/range1 range2 range3
Now my problem is. How do i push the 5 input numbers to the list? Can i connect
two nodes to one node? Or do i break the ranges and push/connect the inputs to the ranges?

This seems more like a problem solved best by a sorted list instead of a stack or several stacks. Why is it that you need to use stacks?

Related

Traversing lists of 0, 1 with constraint

my apologies if this was answered somewhere, I tried searching but I do not know if this kind of problem has a specific name, so nothing came up in my search...
I have a list of objects, and each of these objects can either be accepted or rejected. Every combination is assigned a value, while some combinations are not valid. (So for example we have 4 objects, and objects 1 and 2 don't go together, then every combination that has objects 1 and 2 as accepted is invalid.) It is not known beforehand which objects don't go together and it is not possible to find the invalid ones just by looking at pairs. (For example it is possible that objects 1, 2 are valid together, objects 2,3 are valid, objects 1,3 are valid, but 1,2,3 are invalid.) I modeled this as lists of 0 and 1, so now I want to traverse these lists to find the one with the maximum value in an efficient way.
My idea was to traverse the lists like a tree by starting at all zeros and then in each step flipping a zero to a one, so for example for 3 objects this gives the tree
000
/ | \
100 010 001
/ \ / \ / \
110 101 110 011 101 011
\ \ \ / / /
111
which is actually worse than just listing all 2^n options since there are duplicates, but at each node I could stop if I discovered that it is invalid. Saving the invalid combinations of ones and keeping a list of all already visited nodes I could make sure that I don't revisit already checked nodes. (But I would still have to check those if they were already visited)
Is there any better way to do this?
You can try to build tree of variants (at most 2^n options, as you noticed), but cut unappropriate branches as early as possible.
In example below I've set two binary masks - no 1,2,3 together and no 2,4 together
def buildtree(x, maxsize, level, masks):
if level == maxsize:
print("{0:b}".format(x).zfill(maxsize))
else:
buildtree(x, maxsize, level + 1, masks)
t = x | (1 << level)
good = True
for m in masks:
if (t & m) == m:
good = False
break
if good:
buildtree(t, maxsize, level + 1, masks)
buildtree(0, 4, 0, [7, 10])
0000
1000
0100
1100
0010
0110
0001
1001
0101
1101
0011
Is is possible also to remove some masks but code will be more complicated

how python print me each element when i use random?

I need a list of 8 elements and i want that python randomly import that elements in a list. But i need each of them elements in a list. Like this:
I need numbers of 0 to 4 in a list, but if I write:
s = []
for i in range(8):
s.append(random.randint(0,4))
print("s:", s)
python doesn't print me each of number at least once. Python print me like that:
s = [1,0,2,2,1,0,1,3]- in this list is 4 missing but i want all 5 numbers at least once in a list.
Please help me.
If you want to have a list of eight items, consisting of at least one each of the elements 0,1,2,3,4, then what you really want is a list of [0,1,2,3,4] and three additional random elements, all in random order:
import random
# start a list with one each of the desired elements
s = [0,1,2,3,4]
# add three more elements
for i in range(3):
s.append(random.randint(0,4))
# randomize the order of the elements in the list
random.shuffle(s)
print("s:", s)

How to search in a Range Tree?

I read several slides, like this one's last page, where the describe the search algorithm. However, I have a basic question. The data lie in a 2D space.
I first build a Binary Search Tree based on the x value of the points. Every inner node holds a BST based on the y value of the points that lie in the subtree of that inner node.
Then I think I should search for the points that lie in the range query [x1, x2] and then check if for that points the requested [y1, y2] range query is satisfied. However, the algorithm suggests that you should search in the y-based BST of an inner node, if the range of the inner node is inside [x1, x2], but I don't get that.
If we do that, then in an example I have, we will search (without a reason) the y-based BST of the root. Check the example:
------ 0 ---------------------
| |
---- -3 ---- ---- 4 ------
| | | |
---- -4 - -2 --- 3 --- 5
| | / \ | | / \
-5 (-3,4) (-2,2)(0,7) 2 (4,-4) (5,3)(6,-1)
/ \ / \
(-5,6) (-4,0) (2,1) (3,6)
And the range query I wish to perform is (-oo, 1) x (0, 5)*.
If I look at the root, it has value 0, thus it's enclosed in (-oo, 1), so if I follow the algorithm I am going to search the whole y-based tree of the root?
That should be a tree that contains all the points, so there is no point in continuing searching in x-based tree. Moreover, that will result in more visited nodes than the necessary.
I am implementing that in c++, if that matters.
*Performing a range query for x's in the range [-inf, 1] and y's in the range [0, 5].
The algorithm you are proposing is not quite right - you should compare the range you are querying with the range of the node you are looking at, not the value of the node.
E.g., initially you should compare (-inf, 1) with (-5, 6), which is the data range of the tree (you can also use (-inf, inf) as the data range of the tree or any interval that encloses (-5, 6), for that matter), instead of the value 0. Recursively you should compare the query range with the range of the subtree rooted at the node you are querying at.
Also, the range update can be done while searching - when splitting at a node, the upper/lower bound of the left/right recursive call interval is the node value.

C++ Linked List - Print in sorted order

I've made a linked list in C++ containing car objects. A car object has a few different attributes, but, for this example we will focus upon the miles per gallon (MPG) attribute.
This attribute is an int and some cars have identical MPG.
Is there a way for me to print out these items in an increasing order of MPG without actually sorting the linked list, i.e. iterating through the entire list n-times where n = the size of the linked list, outputting a car object to the user with each iteration of the list.
I apologise in advance if my question is not in the correct format, I'm new here.
Yes there is a way to do that.
Make an array of false values equal to the size of the list.
Take a new object of type car and assign it the first value in the linked list.
Iterate over the list trying to find a car with a lower MPG. if found replace it with this one.
At the end of each iteration, print this element and mark the corresponding value in the false array as true so that you dont use it again.
Example:
CAR 1 -> 2 -> 3 -> 4 -> 5-> NULL
MPG 15 25 10 41 21
arr F F F F F
After each iteration one by one arr values will become true(ie you've printed them.)

Prolog List Neighbour of a Element

I am having problems with list of prolog. I want to make this:
[1,2,3,4,5]
[5,6,9,12,10]
You take a number for example 3, and you do a plus operation with the neighbours so the operation is 2+3+4 = 9. For the first and the last element you pretend there is an imaginary 1 there.
I have this now:
sum_list([A,X,B|T], [Xs|Ts]):-
add(A,X,B,Xs),
sum_list([X,B|T], Ts).
I haven't consider the first and the last element. My problem is I don't know how to get the element before and the next and then how to move on.
Note: I not allow to use meta-predicates.
Thanks.
I'm not sure how you calculated the first 5. The last 10 would be 4 + 5 + implicit 1. But following that calculation, the first element of your result should be 4 instead of 5?
Anyways, that doesn't really matter in terms of writing this code. You are actually close to your desired result. There are of course multiple ways of tackling this problem, but I think the simplest one would be to write a small 'initial' case in which you already calculate the first sum and afterwards recursively calculate all of the other sums. We can then write a case in which only 2 elements are left to calculate the last 'special' sum:
% Initial case for easily distinguishing the first sum
initial([X,Y|T],[Sum|R]) :-
Sum is X+Y+1,
others([X,Y|T],R).
% Match on 2 last elements left
others([X,Y],[Sum|[]]) :-
Sum is X+Y+1.
% Recursively keep adding neighbours
others([X,Y,Z|T],[Sum|R]) :-
Sum is X+Y+Z,
others([Y,Z|T],R).
Execution:
?- initial([1,2],Result)
Result = [4,4]
?- initial([1,2,3,4,5],Result)
Result = [4, 6, 9, 12, 10]
Note that we now don't have any cases (yet) for an empty list or a list with just one element in it. This still needs to be covered if necessary.