Linked List Parameterized constructor - class

I tried to do a Parameterized constructor for a linked list my program is about to implement a queue by using a liked list so i want to do a parameterized constructor like Queue(int value , int size) and it dose not run or doing a list
this is my code for this problem
Queue(int value,int _size)
{
for(int i = 0; i < _size; ++i)
{
Node* temp = new Node;
temp->data = value;
temp->next = nullptr;
if(head == nullptr)
{
head = tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
}
i expected that the result is to fill the lest by value times size like if i run this function Queue x(20,3) the linked list should be
20 20 20

Since that this is a constructor, The head and tail are not properly initialized to use them. I would suggest adding head = tail = nullptr just before the loop and see what happens.

Follow this code after your node creation. I hope this will work. And do use i++ instead of ++i, as the later will make the loop for size-1 times.
if(head == NULL)
head = temp;
else{
Node *x;
x= head;
while(x->next != NULL)
x = x->next;
x->next = temp;
}

Related

Restricting movement to a specific section

I am currently trying to working with restricting the agents to on 1/4 of the whole Manhattan map. The idea is simple and as follows;
Let us say we have 10 agents, their names being v1, v2 ... v10. I want them to move only in a specific section. Currently the method in whcih the MapBasedMovement has been made is such that it moves in all the place, but I need it to move in only specified coordinates.
Thanks,
I tried picking a specific set of coordinates i.e. (0, 0) and (700, 700). Tried to find all the MapNode that are between them and then ask the DTNNode to select only the MapNode in these coordinates. But this does not give me the correct results.
Adding code below
public Path getPath() {
Path p = new Path(generateSpeed());
MapNode curNode = lastMapNode;
MapNode prevNode = lastMapNode;
MapNode nextNode = null;
List<MapNode> neighbors;
Coord nextCoord;
assert lastMapNode != null: "Tried to get a path before placement";
// start paths from current node
p.addWaypoint(curNode.getLocation());
int pathLength = rng.nextInt(maxPathLength-minPathLength) +
minPathLength;
for (int i=0; i<pathLength; i++)
{
// neighbors = curNode.getNeighbors();
neighbors = host.possibleNodes;
Vector<MapNode> n2 = new Vector<MapNode>(neighbors);
if (!this.backAllowed)
{
n2.remove(prevNode); // to prevent going back
}
if (okMapNodeTypes != null) { //remove neighbor nodes that aren't ok
for (int j=0; j < n2.size(); ){
if (!n2.get(j).isType(okMapNodeTypes)) {
n2.remove(j);
}
else {
j++;
}
}
}
if (n2.size() == 0) { // only option is to go back
nextNode = prevNode;
}
else
{
// choose a random node from remaining neighbors
//nextNode = n2.get(rng.nextInt(n2.size()));
nextNode = host.possibleNodes.get(rng.nextInt(host.possibleNodes.size()));
System.out.println(lastMapNode);
List<MapNode> nodePath = pathFinder.getShortestPath(lastMapNode, nextNode);
for (MapNode node : nodePath)
{ // create a Path from the shortest path
p.addWaypoint(node.getLocation());
}
lastMapNode = nextNode;
prevNode = curNode;
nextCoord = nextNode.getLocation();
curNode = nextNode;
return p;
}
prevNode = curNode;
nextCoord = nextNode.getLocation();
curNode = nextNode;
p.addWaypoint(nextCoord);
}
lastMapNode = curNode;
return p;
}
Here, the parts where the host.possibleNodes have been mentioned are a method that I have made which basically tries to get the coordinates of each node and bins to a specific region. I can add that method as well if needed.

Bad address error when comparing Strings within BPF

I have an example program I am running here to see if the substring matches the string and then print them out. So far, I am having trouble running the program due to a bad address. I am wondering if there is a way to fix this problem? I have attached the entire code but my problem is mostly related to isSubstring.
#include <uapi/linux/bpf.h>
#define ARRAYSIZE 64
struct data_t {
char buf[ARRAYSIZE];
};
BPF_ARRAY(lookupTable, struct data_t, ARRAYSIZE);
//char name[20];
//find substring in a string
static bool isSubstring(struct data_t stringVal)
{
char substring[] = "New York";
int M = sizeof(substring);
int N = sizeof(stringVal.buf) - 1;
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++) {
int j;
/* For current index i, check for
pattern match */
for (j = 0; j < M; j++)
if (stringVal.buf[i + j] != substring[j])
break;
if (j == M)
return true;
}
return false;
}
int Test(void *ctx)
{
#pragma clang loop unroll(full)
for (int i = 0; i < ARRAYSIZE; i++) {
int k = i;
struct data_t *line = lookupTable.lookup(&k);
if (line) {
// bpf_trace_printk("%s\n", key->buf);
if (isSubstring(*line)) {
bpf_trace_printk("%s\n", line->buf);
}
}
}
return 0;
}
My python code here:
import ctypes
from bcc import BPF
b = BPF(src_file="hello.c")
lookupTable = b["lookupTable"]
#add hello.csv to the lookupTable array
f = open("hello.csv","r")
contents = f.readlines()
for i in range(0,len(contents)):
string = contents[i].encode('utf-8')
print(len(string))
lookupTable[ctypes.c_int(i)] = ctypes.create_string_buffer(string, len(string))
f.close()
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="Test")
b.trace_print()
Edit: Forgot to add the error: It's really long and can be found here: https://pastebin.com/a7E9L230
I think the most interesting part of the error is near the bottom where it mentions:
The sequence of 8193 jumps is too complex.
And a little bit farther down mentions: Bad Address.
The verifier checks all branches in your program. Each time it sees a jump instruction, it pushes the new branch to its “stack of branches to check”. This stack has a limit (BPF_COMPLEXITY_LIMIT_JMP_SEQ, currently 8192) that you are hitting, as the verifier tells you. “Bad Address” is just the translation of kernel's errno value which is set to -EFAULT in that case.
Not sure how to fix it though, you could try:
With smaller strings, or
On a 5.3+ kernel (which supports bounded loops): without unrolling the loop with clang (I don't know if it would help).

How to fix : The object of type 'GameObject' has been destroyed but you are still trying to access it ? -Unity

I made a 5 second time bar to replace the wave. when wave1 has been 5 seconds it will move to wave2. then the first wave will be destroyed. when I got to wave3, an error came out. here's my code:
IEnumerator ChangeWave()
{
for (int i = 0; i < wave.Length - 1; i++)
{
yield return new WaitForSeconds(5f);
Destroy(wave[i]);
wave[i+1].SetActive(true);
}
}
the error said The object of type 'GameObject' has been destroyed but you are still trying to access it. - unity
sorry for my bad english.
There's a few things going on here.
Remove the -1 in the for loop, so it iterates to end
wave[i+1] will cause an error, so check if (i < wave.Length -1)
Destroy( array[index] ) will try and access Game Object but it's destroyed, so you should create a temporary var to hold gameobject, and set null to the array element.
Some fixes below - there might be a better way, but this is what I use:
Version 1 - Using the above fixes
IEnumerator ChangeWaveV2()
{
for (int i = 0; i < wave.Length; i++)
{
yield return new WaitForSeconds(.2f);
var t = wave[i];
wave[i] = null;
Destroy(t);
if(i < wave.Length - 1)
wave[i + 1].SetActive(true);
}
}
Version 2 - A variation without needing to null out the element and create a temporary var. If you iterate from end to front of the array, you can freely Destroy() GameObjects in an array. May not be useful as it changes the wave array.
IEnumerator ChangeWaveV3()
{
System.Array.Reverse(wave);
for (int i = wave.Length - 1; i >= 0; i--)
{
yield return new WaitForSeconds(.2f);
Destroy(wave[i]);
if(i > 0)
wave[i - 1].SetActive(true);
}
}

Access non static function from static function

Here is some insight: I am working with UnityScript in Unity 4.6.3. I have one script called Pause.js and it contains this function:
function fadeMusicOut () {
while (audio.volume >= 0.005) {
yield WaitForSeconds(0.1);
Debug.Log("Loop Entered: " + audio.volume);
audio.volume = (audio.volume - 0.015);
}
Another script GameManager.js has this function:
static function Score (wallName : String) {
if (wallName == "rightWall") {
playerScore01 += 1;
}
else {
playerScore02 += 1;
}
if (playerScore01 == SettingsBack.scoreLimit || playerScore02 == SettingsBack.scoreLimit)
{
startParticles = 1;
SettingsBack.gameOver = 1;
BallControl.fadeSound = 1;
yield WaitForSeconds(4);
Camera.main.SendMessage("fadeOut");
Pause.fadeMusic = 1;
SettingsBack.soundVolume = 0;
yield WaitForSeconds(2);
playerScore01 = 0;
playerScore02 = 0;
SettingsBack.soundVolume = oldSoundVol;
Application.LoadLevel("_Menu");
}
}
So pretty much I want to call the fadeMusicOut() function from static function Score, but it will not let me because it says it needs an instance of that object.
The Pause.js script is not attached to any game objects, but it is attached to 2 buttons that call their specific functions. The GameManager.js script is attached to an object called GM. So how can I go about calling fadeMusicOut() from the Score function?
I have tried setting new vars that import the game object but still no luck. I tried making fadeMusicOut() a static function, but it creates many errors.
Any help at all is appreciated.

Comparing consecutive elements in a queue

I have a queue of elements, sorted by date. I need to extract the first n elements, which have the same date and add them to a temporary ArrayList, from which I choose one of them and scrap the others. After that I need to continue doing the same thing for the next n elements of the queue with the same date (extract them to the temp list and so on) until I have no more items in the queue.
// some notes to help you understand the code
PriorityQueue<Results> r, size(4), elementsEqualByTime(1=2,3=4);
List<Comments> c, size(2);
ArrayList temp;
if (c.size() != r.size() && resultIter.hasNext()) {
//first iteration will compare element 0 to itself -> 100% true
ResultObject r2 = resultIter.next();
ResultObject r1 = r2;
while (resultIter.hasNext() && r1.getTime().equals(r2.getTime())) {
temp.add(r1);
//we add the matching elements before we continue
r1 = r2;
temp.add(r1);
if (resultIter.hasNext()) {
//after we add the 2 matching elements we continue
r2 = resultIter.next();
}
}
//use the items in temp
temp.clear();
}
Right now it works for the 1st set of elements, but on the 2nd iteration it adds no elements to the temp ArrayList. I'd appreciate help with this solution, but am also open to different suggestions.
boolean Check (List<Element> elements,Element element)
{
for(Element element1:elements)
if(element1.equals(element))
return true;
return false;
}
void Stuff()
{
// some notes to help you understand the code
PriorityQueue<Element> r = new PriorityQueue<Element>();
List<Element> c;
List<Element> temp = new ArrayList<Element>();
for(Element element:r)
{
if(!Check(temp, element))
{
// do stuff with temp
temp = new ArrayList<Element>();
}
temp.add(element);
}
}
while (commentIter.hasNext()) {
Comment c1 = null;
temp.add(arrayQueue[0]);
for (int i = 1; i < arrayQueue.length; i++) {
if (!arrayQueue[i].getTime().equals(arrayQueue[i - 1].getTime())) {
c1 = commentIter.next();
//do stuff with the results
temp = new HashSet<ResultObject>();
}
temp.add(arrayQueue[i]);
}
if (!temp.isEmpty()) {
c1 = commentIter.next();
//do stuff with the results
}
temp = new HashSet<ResultObject>();
}
That's a tested solution which works.