how to delete a sprite in an sprite array in pixi.js - pixi.js

I want to delete a sprite from my sprite array and I tried myPlane.bullets[index].destroy() and myPlane.bullets.shift():
for (let index = 0; index < myPlane.bullets.length; index++) {
if(myPlane.bullets[index].y < -bulletHeight) {
// step 1
myPlane.bullets[index].destroy()
// step 2
myPlane.bullets.shift()
continue
}
myPlane.bullets[index].y -= bulletSpeed
}
but I think that's not the best way to delete a sprite in an array, it is too fussy.
Is there a better way to delete a sprite in an array?

Unfortunately myPlane.bullets.shift() will only remove the first element of the array. To remove an element by index you need to use myPlane.bullets.splice(i, 1).
Keep in mind that this affects the original indexes of the objects. If you don't handle it, the for loop will continue increasing and will skip one element.
for (let index = 0; index < myPlane.bullets.length; index++) {
if (myPlane.bullets[index].y < -bulletHeight) {
// step 1
myPlane.bullets[index].destroy()
// step 2
myPlane.bullets.splice(index, 1)
index-- // compensate array length mutation
continue
}
myPlane.bullets[index].y -= bulletSpeed
}
Generally speaking, you should avoid mutating the array that you are looping through. If you don't keep references to the bullets array, here is an alternative where a new filtered array is created:
myPlane.bullets = myPlane.bullets.filter((bullet) => {
if (bullet.y < -bulletHeight) {
bullet.destroy()
return false
}
return true
});
for (let index = 0; index < myPlane.bullets.length; index++) {
myPlane.bullets[index].y -= bulletSpeed
}

Related

I cannot find out why this code keeps skipping a loop

Some background on what is going on:
We are processing addresses into standardized forms, this is the code to take addresses scored by how many components found and then rescore them using a levenshtein algorithm across similar post codes
The scores are how many components were found in that address divided by the number missed, to return a ratio
The input data, scoreDict, is a dictionary containing arrays of arrays. The first set of arrays is the scores, so there are 12 arrays because there are 12 scores in this file (it adjusts by file). There are then however many addresses fit that score in their own separate arrays stored in that. Don't ask me why I'm doing it that way, my brain is dead
The code correctly goes through each score array and each one is properly filled with the unique elements that make it up. It is not short by any amount, nothing is duplicated, I have checked
When we hit the score that is -1 (this goes to any address where it doesn't fit in some rule so we can't use its post code to find components so no components are found) the loop specifically ONLY DOES EVERY OTHER ADDRESS IN THIS SCORE ARRAY
It doesn't do this to any other score array, I have checked
I have tried changing the number to something else like 99, same issue except one LESS address got rescored, and the rest stayed at the original failing score of 99
I am going insane, can anyone find where in this loop something may be going wrong to cause it to only do every other line. The index counter of line and sc come through in the correct order and do not skip over. I have checked
I am sorry this is not professional, I have been at this one loop for 5 hours
Rescore: function Rescore(scoreDict) {
let tempInc = 0;
//Loop through all scores stored in scoreDict
for (var line in scoreDict) {
let addUpdate = "";
//Loop through each line stored by score
for (var sc in scoreDict[line.toString()]) {
console.log(scoreDict[line.toString()].length);
let possCodes = new Array();
const curLine = scoreDict[line.toString()][sc];
console.log(sc);
const curScore = curLine[1].split(',')[curLine[1].split(',').length-1];
switch (true) {
case curScore == -1:
let postCode = (new RegExp('([A-PR-UWYZ][A-HK-Y]?[0-9][A-Z0-9]?[ ]?[0-9][ABD-HJLNP-UW-Z]{2})', 'i')).exec(curLine[1].replace(/\\n/g, ','));
let areaCode;
//if (curLine.split(',')[curLine.split(',').length-2].includes("REFERENCE")) {
if ((postCode = (new RegExp('(([A-Z][A-Z]?[0-9][A-Z0-9]?(?=[ ]?[0-9][A-Z]{2}))|[0-9]{5})', 'i').exec(postCode))) !== null) {
for (const code in Object.keys(addProper)) {
leven.LoadWords(postCode[0], Object.keys(addProper)[code]);
if (leven.distance < 2) {
//Weight will have adjustment algorithms based on other factors
let weight = 1;
//Add all codes that are close to the same to a temp array
possCodes.push(postCode.input.replace(postCode[0], Object.keys(addProper)[code]).split(',')[0] + "(|W|)" + (leven.distance/weight));
}
}
let highScore = 0;
let candidates = new Array();
//Use the component script from cityprocess to rescore
for (var i=0;i<possCodes.length;i++) {
postValid.add([curLine[1].split(',').slice(0,curLine[1].split(',').length-2) + '(|S|)' + possCodes[i].split("(|W|)")[0]]);
if (postValid.addChunk[0].split('(|S|)')[postValid.addChunk[0].split('(|S|)').length-1] > highScore) {
candidates = new Array();
highScore = postValid.addChunk[0].split('(|S|)')[postValid.addChunk[0].split('(|S|)').length-1];
candidates.push(postValid.addChunk[0]);
} else if (postValid.addChunk[0].split('(|S|)')[postValid.addChunk[0].split('(|S|)').length-1] == highScore) {
candidates.push(postValid.addChunk[0]);
}
}
score.Rescore(curLine, sc, candidates[0]);
}
//} else if (curLine.split(',')[curLine.split(',').length-2].contains("AREA")) {
// leven.LoadWords();
//}
break;
case curScore > 0:
//console.log("That's a pretty good score mate");
break;
}
//console.log(line + ": " + scoreDict[line].length);
}
}
console.log(tempInc)
score.ScoreWrite(score.scoreDict);
}
The issue was that I was calling the loop on the array I was editing, so as each element got removed from the array (rescored and moved into a separate array) it got shorter by that element, resulting in an issue that when the first element was rescored and removed, and then we moved onto the second index which was now the third element, because everything shifted up by 1 index
I fixed it by having it simply enter an empty array for each removed element, so everything kept its index and the array kept its length, and then clear the empty values at a later time in the code

TypeScript: Assign an event to each element in an element array on a loop

I have come up with the code below. The problem is that on change every element alerts the last iteration index. For example if there are 24 items on the elements array every single element on change will alert "Changed row 23" . I kind of see why it is happening but cant find away to get around it so that every element onchange will alert its index instead of the last. Any help will be appreciated.
for (var i = 1; i < elements.length; i++) {
elements[i].onchange = (ev: Event) => alert("Changed row " + i);
usersTable.appendChild(elements[i]);
}
When your events are executed, the for loop would have completed. At that point i would equal whatever it was when the loop ended—elements.length - 1 (which is why it's always equal to 23 for you).
You can fix this by using Brocco's solution, but since you want to know a way of doing it without changing the loop, you will need to pass in the value of i when setting the change function. This can be achieved by using an IIFE:
for (var i = 1; i < elements.length; i++) {
(function (i) {
usersTable.appendChild(elements[i]);
elements[i].onchange = (ev: Event) => alert("Changed row " + i);
})(i);
}
Which is a longer way of expressing what the .forEach function does for you.
Alternatively, you could also use .bind:
elements[i].onchange = function(i: number, ev: Event) {
alert("Changed row " + i)
}.bind(this, i);
Use Array.prototype.forEach, where you can pass the index into the callback function...
elements.forEach((element, idx) => {
elem.onchange = (ev: Event) => alert("Changed row " + idx);
usersTable.appendChild(elem);
});
Documentation on Array.prototype.forEach can be found here

Longest Common Subsequence for a series of strings

For the Longest Common Subsequence of 2 Strings I have found plenty examples online and I believe that I understand the solution.
What I don't understand is, what is the proper way to apply this problem for N Strings? Is the same solution somehow applied? How? Is the solution different? What?
This problem becomes NP-hard when input has arbitrary number of strings. This problem becomes tractable only when input has fixed number of strings. If input has k strings, we could apply the same DP technique in by using a k dimensional array to stored optimal solutions of sub-problems.
Reference: Longest common subsequence problem
To find the Longest Common Subsequence (LCS) of 2 strings A and B, you can traverse a 2-dimensional array diagonally like shown in the Link you posted. Every element in the array corresponds to the problem of finding the LCS of the substrings A' and B' (A cut by its row number, B cut by its column number). This problem can be solved by calculating the value of all elements in the array.
You must be certain that when you calculate the value of an array element, all sub-problems required to calculate that given value has already been solved. That is why you traverse the 2-dimensional array diagonally.
This solution can be scaled to finding the longest common subsequence between N strings, but this requires a general way to iterate an array of N dimensions such that any element is reached only when all sub-problems the element requires a solution to has been solved.
Instead of iterating the N-dimensional array in a special order, you can also solve the problem recursively. With recursion it is important to save the intermediate solutions, since many branches will require the same intermediate solutions. I have written a small example in C# that does this:
string lcs(string[] strings)
{
if (strings.Length == 0)
return "";
if (strings.Length == 1)
return strings[0];
int max = -1;
int cacheSize = 1;
for (int i = 0; i < strings.Length; i++)
{
cacheSize *= strings[i].Length;
if (strings[i].Length > max)
max = strings[i].Length;
}
string[] cache = new string[cacheSize];
int[] indexes = new int[strings.Length];
for (int i = 0; i < indexes.Length; i++)
indexes[i] = strings[i].Length - 1;
return lcsBack(strings, indexes, cache);
}
string lcsBack(string[] strings, int[] indexes, string[] cache)
{
for (int i = 0; i < indexes.Length; i++ )
if (indexes[i] == -1)
return "";
bool match = true;
for (int i = 1; i < indexes.Length; i++)
{
if (strings[0][indexes[0]] != strings[i][indexes[i]])
{
match = false;
break;
}
}
if (match)
{
int[] newIndexes = new int[indexes.Length];
for (int i = 0; i < indexes.Length; i++)
newIndexes[i] = indexes[i] - 1;
string result = lcsBack(strings, newIndexes, cache) + strings[0][indexes[0]];
cache[calcCachePos(indexes, strings)] = result;
return result;
}
else
{
string[] subStrings = new string[strings.Length];
for (int i = 0; i < strings.Length; i++)
{
if (indexes[i] <= 0)
subStrings[i] = "";
else
{
int[] newIndexes = new int[indexes.Length];
for (int j = 0; j < indexes.Length; j++)
newIndexes[j] = indexes[j];
newIndexes[i]--;
int cachePos = calcCachePos(newIndexes, strings);
if (cache[cachePos] == null)
subStrings[i] = lcsBack(strings, newIndexes, cache);
else
subStrings[i] = cache[cachePos];
}
}
string longestString = "";
int longestLength = 0;
for (int i = 0; i < subStrings.Length; i++)
{
if (subStrings[i].Length > longestLength)
{
longestString = subStrings[i];
longestLength = longestString.Length;
}
}
cache[calcCachePos(indexes, strings)] = longestString;
return longestString;
}
}
int calcCachePos(int[] indexes, string[] strings)
{
int factor = 1;
int pos = 0;
for (int i = 0; i < indexes.Length; i++)
{
pos += indexes[i] * factor;
factor *= strings[i].Length;
}
return pos;
}
My code example can be optimized further. Many of the strings being cached are duplicates, and some are duplicates with just one additional character added. This uses more space than necessary when the input strings become large.
On input: "666222054263314443712", "5432127413542377777", "6664664565464057425"
The LCS returned is "54442"

Search an integer in a row-sorted two dim array, is there any better approach?

I have recently come across with this problem,
you have to find an integer from a sorted two dimensional array. But the two dim array is sorted in rows not in columns. I have solved the problem but still thinking that there may be some better approach. So I have come here to discuss with all of you. Your suggestions and improvement will help me to grow in coding. here is the code
int searchInteger = Int32.Parse(Console.ReadLine());
int cnt = 0;
for (int i = 0; i < x; i++)
{
if (intarry[i, 0] <= searchInteger && intarry[i,y-1] >= searchInteger)
{
if (intarry[i, 0] == searchInteger || intarry[i, y - 1] == searchInteger)
Console.WriteLine("string present {0} times" , ++cnt);
else
{
int[] array = new int[y];
int y1 = 0;
for (int k = 0; k < y; k++)
array[k] = intarry[i, y1++];
bool result;
if (result = binarySearch(array, searchInteger) == true)
{
Console.WriteLine("string present inside {0} times", ++ cnt);
Console.ReadLine();
}
}
}
}
Where searchInteger is the integer we have to find in the array. and binary search is the methiod which is returning boolean if the value is present in the single dimension array (in that single row).
please help, is it optimum or there are better solution than this.
Thanks
Provided you have declared the array intarry, x and y as follows:
int[,] intarry =
{
{0,7,2},
{3,4,5},
{6,7,8}
};
var y = intarry.GetUpperBound(0)+1;
var x = intarry.GetUpperBound(1)+1;
// intarry.Dump();
You can keep it as simple as:
int searchInteger = Int32.Parse(Console.ReadLine());
var cnt=0;
for(var r=0; r<y; r++)
{
for(var c=0; c<x; c++)
{
if (intarry[r, c].Equals(searchInteger))
{
cnt++;
Console.WriteLine(
"string present at position [{0},{1}]" , r, c);
} // if
} // for
} // for
Console.WriteLine("string present {0} times" , cnt);
This example assumes that you don't have any information whether the array is sorted or not (which means: if you don't know if it is sorted you have to go through every element and can't use binary search). Based on this example you can refine the performance, if you know more how the data in the array is structured:
if the rows are sorted ascending, you can replace the inner for loop by a binary search
if the entire array is sorted ascending and the data does not repeat, e.g.
int[,] intarry = {{0,1,2}, {3,4,5}, {6,7,8}};
then you can exit the loop as soon as the item is found. The easiest way to do this to create
a function and add a return statement to the inner for loop.

Binary Search in processing, ArrayIndexOutOfBounds

Basically, for revision purposes tried to code a Binary Search algorithm in Processing. Decided to use Processing for convenience. Can anybody spot the error because its baffling me. Thanks :)
//Set size and font information.
size(400, 200);
background(0,0,0);
PFont font;
font = loadFont("Arial-Black-14.vlw");
textFont(font);
//Initialise the variables.
int[] intArray = new int[10];
int lower = 1;
int upper = 10;
int flag = 0;
int criteria = 10;
int element = 0;
//Populate the Array.
for(int i=0; i<10; i++)
{
intArray[i] = i;
}
//Tell the user Array is filled.
text("Array Filled", 15, 20);
// Main loop.
while(flag == 0)
{
//Sets the element to search by finding mid point.
element = ((lower+upper)/2);
//Checks if the mid point is equal to search criteria.
if(intArray[element] == criteria)
{
flag = 1;
}
//Checks if the criteria is grater than the currently searched element.
else if(criteria > intArray[element])
{
lower = (element+1);
}
else
{
upper = (element-1);
}
//Checks if the lower value is higher than the upper value.
if(lower > upper)
{
flag = 2;
}
}
//If no match is found.
if(flag == 2)
{
text("Did not find criteria "+criteria, 15, 40);
}
//If a match is found.
else
{
text("Found "+criteria+" at index "+element+"", 15, 60);
}
When you initialize lower and upper, you set the values to 1 and 10, which is wrong. 1 and 10 would be the lowest and highest elements only if the array was 1-based (i.e. the first element is 1), but it's not, it's 0-based. Set the values to 0 and 9 and it should work.

Resources