Actionscript 3 dynamic multidimensional array - arrays

Okay so this is my code
var no:int = 0;
var elem:int = 0;
loadedData = myLoader.data.split(/\r\n|\n|\r/);
for (var i:int = 0; i < loadedData.length; i++)
{
if (loadedData[i] != '')
{
if (loadedData[i] != ',')
{
if(patterns[no] == undefined) patterns[no] = [];
trace(no);
trace(elem);
obstacleData[i] = loadedData[i].split(",");
trace(patterns[no]);
patterns[no][elem] = obstacleData[i][0];
patterns[no][elem + 1] = obstacleData[i][1];
elem += 2;
trace('Pattern' , no, ': ', patterns[no]);
}
else if (loadedData[i] == ',')
{
no += 1;
elem = 0;
patterns[no] = 0;
}
}
}
The problem is at this line
patterns[no][elem] = obstacleData[i][0];
I'm getting the error: [Fault] exception, information=ReferenceError: Error #1056: Cannot create property 0 on Number.
I've read around on this and multidimensional arrays just seem to be so much more complicated on AS3 compared to other languages where you just create a multidimensional array and it works.
I feel like I've done something really obvious wrong and will feel like an idiot upon someone telling me but I really need help on this one since I'm new to this whole AS3 way of creating multidimensional arrays.
Just in case the output for the code when run is as so:
0
0
Pattern 0 : 300,60
0
2
300,60
Pattern 0 : 300,60,350,90
1
0
0 <--- This might be the problem?
[Fault] exception, information=ReferenceError: Error #1056: Cannot create property 0 on Number.

Maybe the error is caused by the line
patterns[no] = 0;
I think you want to assign an empty array or maybe null and check for null later.

Related

Getting timeout error in New Year Chaos problem using scala

I have got a working scala code for New Year Chaos problem in Hackerrank, but Im recieving timeout errors in some test cases
https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
Please help me with optimization of below code:
def minimumBribes(q: Array[Int]){
val c = q.sorted
var swap = 0
var count_swap=0
import scala.util.control._
val loop = new Breaks
var temp = 0
var flag = true
loop.breakable
{
for (i <- q.length-1 to 0 by -1)
{
swap = 0
if (q(i) != i+1)
{
swap=i-q.indexOf(i+1)
if (swap > 2) {println("Too Chaotic");flag=false;loop.break()}
else
{
temp= q(q.indexOf(i+1))
q(q.indexOf(i+1)) = q(i-1)
q(i-1) = q(i)
q(i) = temp
count_swap += swap
if(q.deep == c.deep){
loop.break()
}
}
}
}
}
if (flag)println(count_swap)
}
To be honest I don't understand your implementation but
1) q.sorted could possibly already run out of time given that n is ~10^5.
2) q.sorted call is actually redundant since it's just a 1..n sequence.
3) using q.indexOf makes your algorithm O(n^2) complex. It's possible to solve it in linear time.

Move Zeroes in Scala

I'm working on "Move Zeroes" of leetcode with scala. https://leetcode.com/problems/move-zeroes/description/
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array.
I have a solution which works well in IntelliJ but get the same Array with input while executing in Leetcode, also I'm not sure whether it is done in-place... Something wrong with my code ?
Thanks
def moveZeroes(nums: Array[Int]): Array[Int] = {
val lengthOrig = nums.length
val lengthFilfter = nums.filter(_ != 0).length
var numsWithoutZero = nums.filter(_ != 0)
var numZero = lengthOrig - lengthFilfter
while (numZero > 0){
numsWithoutZero = numsWithoutZero :+ 0
numZero = numZero - 1
}
numsWithoutZero
}
And one more thing: the template code given by leetcode returns Unit type but mine returns Array.
def moveZeroes(nums: Array[Int]): Unit = {
}
While I agree with #ayush, Leetcode is explicitly asking you to use mutable states. You need to update the input array so that it contains the changes. Also, they ask you to do that in a minimal number of operations.
So, while it is not idiomatic Scala code, I suggest you a solution allong these lines:
def moveZeroes(nums: Array[Int]): Unit = {
var i = 0
var lastNonZeroFoundAt = 0
while (i < nums.size) {
if(nums(i) != 0) {
nums(lastNonZeroFoundAt) = nums(i)
lastNonZeroFoundAt += 1
}
i += 1
i = lastNonZeroFoundAt
while(i < nums.size) {
nums(i) = 0
i += 1
}
}
As this is non-idomatic Scala, writing such code is not encouraged and thus, a little bit difficult to read. The C++ version that is shown in the solutions may actually be easier to read and help you to understand my code above:
void moveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = 0;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
// After we have finished processing new elements,
// all the non-zero elements are already at beginning of array.
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
nums[i] = 0;
}
}
Your answer gives TLE (Time Limit Exceeded) error in LeetCode..I do not know what the criteria is for that to occur..However i see a lot of things in your code that are not perfect .
Pure functional programming discourages use of any mutable state and rather focuses on using val for everything.
I would try it this way --
def moveZeroes(nums: Array[Int]): Array[Int] = {
val nonZero = nums.filter(_ != 0)
val numZero = nums.length - nonZero.length
val zeros = Array.fill(numZero){0}
nonZero ++ zeros
}
P.S - This also gives TLE in Leetcode but still i guess in terms of being functional its better..Open for reviews though.

How to access individual variable inside of a 2d array Actionscript 3

Im trying to access an individual tile inside of my 2d array of tiles
Ive created my array like so:
private var map:Array = [[25,25]];
ive tried several ways including:
map[1][1] = 1;
all that does is give me this:
ReferenceError: Error #1056: Cannot create property 1 on Number.
ive also tried:
map[[1,1]] = 1;
nothing happends that I can tell
The only way that ive tried so far that gets me a result thats not an error is:
map[1,1] = 1;
The issue here is this selects the whole row.
Any help would be apreciated..thanks!
This is not correct way to create 2D array:
private var map:Array = [[25,25]];
This array contains one array which contains two elements. You can't address to the second element like this:
map[1][1] = 1;
because the second element (array) of map doesn't exist.
You can create 2D array this way:
var map:Array = [];
for (var i:int = 0; i < rows; i++)
{
map[i] = [];// this line adds new row to the 2D array
// To fill the array by zeros add next loop
for (var j:int = 0; j < cols; j++)
{
map[i][j] = 0;
}
}
To start, I think that to get the error mentioned in your question, your array should looks like this :
var map:Array = [
[25, 25], // map[0] = [25, 25] ( array of two elements )
35 // map[1] = 35 ( just a simple number )
];
So, if you write :
trace(typeof map[1]); // gives : number
You will get : number, and that's why you can not right : map[1][1] = value; and it's normal that you got the #1056 error.
Here, I don't know if you meant assign the value 1 to your 2nd 25 of map[0] or you want really add or edit map[1][1], in the 1st case, you can simply write :
map[0][1] = 1; // gives : map[0] = [25, 1]
In the 2nd case, you can do :
map[1] = [any_other_value, 1]; // gives : map[1] = [any_other_value, 1]
Last remark, forget that you got an error and suppose that your map array was just:
var map:Array = [
[25, 25]
];
Here, you can not also write map[1][1] = value;, why ? Let's use the same method :
trace(map[1]); // gives : undefined
So sure you can not add a property to an undefined, that's why when you write :
map[1][1] = value;
You will get an #1010 error : "undefined has no properties. ".
Of course here, we should firstly create map[1] :
map[1] = []; // or directly map[1] = [any_other_value, value]
And then :
map[1][1] = value;
Hope that can help.

as3 array error #1010

im basically trying to make a mini game where you have to dodge the oncoming objects by using the on-screen buttons (button left and right of the screen) it worked fine when i did it with an individual object then i decided to have more objects and make an array to hold them. thats when the error accrued.
the error is :
TypeError: Error #1010: A term is undefined and has no properties.at Untitled_fla::MainTimeline/cyclespeed()
Your cycle Array has 5 elements starting by the index 0 and ending by 4 :
... Array indices are zero-based, which means that the first element in the array is [0], the second element is [1], and so on.
That's why your for loop should be like this :
for (var i:int = 0; i < 5; i++) { }
OR
for (var i:int = 0; i <= 4; i++) { }
OR simply
for (var i:int = 0; i < cycle.length; i++) { }
In your cyclespeed function, the value of your i var will be always 5, which is the last value assigned to it in your for loop, and of course cercle[5] didn't exist that's why you got the TypeError: Error #1010: A term is undefined and has no properties : cercle[5] is undefined and has not an x property.
In your case you can use only one Event.ENTER_FRAME listener to do all the job like this :
stage.addEventListener(Event.ENTER_FRAME, onEnterThisFrame);
function onEnterThisFrame(e:Event):void {
box_MC.x -= 1;
for (var i:int = 0; i < cycle.length; i++) {
cycle[i].x += 1;
if(box_MC.hitTestObject(cycle[i])) {
trace ("true");
box_MC.x += 4;
}
}
if (movingdown == 1) {
box_MC.y -= 4.5;
} else if (movingup == 1) {
box_MC.y += 4.5;
}
}
Hope that can help.
I don't have enough rep points to comment, so I'll critique what I saw in your code.
There are quite a few things wrong with the code.
This was declared twice, once in a for loop and one outside of the functions
addEventListener(Event.ENTER_FRAME, cyclespeed);
You attached the "handleCollision" event to the stage and not a movieclip.
handleCollision refers to "cycle[i]" but i is out of scope since it is not apart of the for loop where i has been declared
function handleCollision( e:Event) : void {
if(box_MC.hitTestObject(cycle[**i**])) {
trace ("true");
box_MC.x += 4;
}
}
I would suggest building each piece one at a time because it seems like you are trying to do a lot at once, without actually getting anything to work.

Search a substring in an array of Strings in unityscript

I'm trying to search a substring in an array of Strings. I'm using the following code (in Unity3):
var obstacles = ["Border", "Boundary", "BoundaryFlame"];
var frontAvailable = true;
var leftAvailable = true;
var rightAvailable = true;
var hitFront: RaycastHit;
if (Physics.Raycast(transform.position, transform.position + transform.forward, hitFront, 1.5)) {
Debug.Log("I hit this in front: ");
Debug.Log(hitFront.collider.gameObject.name);
for (var i = 0; i < obstacles.length; i++)
{
if (obstacles[i].IndexOf(hitFront.collider.gameObject.name) > -1)
{
Debug.Log("Hit in front!");
frontAvailable = false;
}
}
}
The problem is, the Debug.Log shows Boundary(Clone). I've included Boundary in the array obstacles. Shouldn't below code set frontAvailable to false? Or did I make a mistake here?
In addition to Kolink's answer, your if is looking for Boundary(clone) at the beginning of Boundary, rather than the other way around. I think you're looking for:
if (hitFront.collider.gameObject.name.IndexOf(obstacles[i]) >= 0)
I think you need indexOf, not IndexOf. Assuming you're talking about the native string function.
In addition, indexOf returns -1 if there is no match, 0 if the match is at the start, 1, 2, 3... for further positions. So you need > -1 instead of > 0

Resources