i have code like this in actionscript3,
var map: Array = [
[[0,1,0],[0,1,0]],
[[0,1,0], [0,1,0]]];
var nom1: int = 0;
var nom2: int = 0;
var nom3: int = 1;
var nom4: int = 18;
stage.addEventListener (Event.ENTER_FRAME, beff);
function beff (e: Event): void
{
map[nom1][nom2][nom3] = nom4
}
stage.addEventListener (MouseEvent.CLICK, brut);
function brut(e: MouseEvent):void
{
trace (map)
}
when run, it gets an error in its output
what I want is to fill in each "1" value and not remove the "[" or "]" sign
so when var nom1, var nom2 are changed
Then the output is
[[[0,18,0],[0,18,0]],
[[0,18,0],[0,18,0]]]
please helps for those who can solve this problem
If what you want to achieve is to replace every 1 by 18 in this nested array, you could try :
for (var i = 0; i < map.length; i++) {
var secondLevel = map[i];
for (var j = 0; j < secondLevel.length; j++) {
var thirdLevel = secondLevel[j];
for (var k = 0; k < thirdLevel.length; k++) {
if (thirdLevel[k] === 1) {
thirdLevel[k] = 18;
}
}
}
}
Note that, this would only work for nested arrays with 3 levels of depth
Related
I am working on a minesweeper game in javascript. The mechanism that is causing me trouble is the for loop inside the Mine object that sets the isBomb variable to true or false.
var board = [];
var bombs = [];
var mines;
function findNeighbors(x,y) {
return 'work in progress'
}
function setup() {
// create bombs
for (var i = 0; i < 45; i++) {
var position = [floor(random(0,15)),floor(random(0,15))];
if (!bombs.includes(position)) {
bombs[i] = position;
}
}
// create board
for (var y = 0; y < 15; y++) {
board[y] = new Array();
for (var x = 0; x < 15; x++) {
board[y][x] = new Mine(y,x);
}
}
}
console.log(board);
console.log(bombs);
function Mine(x,y) {
this.x = x;
this.y = y;
this.neighbors = findNeighbors(this.x,this.y);
for (var iter = 0; iter < 45; iter++) {
if (bombs[iter] == [this.x,this.y]) {
this.isBomb = true;
}
else {
this.isBomb = false;
}
}
this.show = function() {
return 'show'
}
this.setValue = function(value) {
this.value = value;
return value;
}
}
When I type bombs[44] in the console for example, it returns something like [5,11] yet when I check if bombs[44] = [5,11] it will always return false. Is there a specific way I have to denote the [5,11] array for it to be recognized?
This is because you cannot compare two arrays in javascript. What you can do is using join() and then compare as strings in single step,
bombs[44].join(",") == [5,11].join(",")
Or you can compare the contents of the array individually
Try changing the conditional expression in your for-loop at the top for (var i = 0; i < 45; i++) to for (var i = 0; i < arr.length; i++)
this will make the loop , go over the full array length with less room for error. for loops can be , error prone and tedious.
Kindly help me investigate my function below since I'm stuck and still having a hard time figuring it out.
All is well until it reaches the last column on the nested FOR loop. The last column of each row's values are only "0". However, I used the Number() function to make the cell values(i.e. "0") a number but I keep on getting NaN for the last element of the SUM & COUNT arrays.
colCount = 326 while rowCount = 374.
sum.length and count.length should really be ONLY 325 since the headers are unnecessary and the first column is just composed of time stamps. I was able to .push(0) successfully until the nested FOR loop changed the result of the last element to NaN.
function processDataToDictionary(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var csvArray = [];
for (let i = 0; i < allTextLines.length - 1; i++) {
var row = allTextLines[i].split(',');
csvArray.push(row);
}
var colCount = csvArray[0].length;
var rowCount = csvArray.length;
//Arrays of values
var count = [];
var sum = [];
var average = [];
var headers = [];
for (let i = 1; i < colCount; i++) {
var current = csvArray[0][i].replace(/"/g, '');
sum.push(0);
count.push(0);
headers[i] = current;
}
for (let i = 1; i < rowCount; i++) {
for (let j = 1; j < colCount; j++) {
// Remove the quotes from your array
current = csvArray[i][j].replace(/"/g, '');
// Added the Method IsNullOrWhiteSpace
if (!isNullOrWhitespace(current)) {
// Parse as double not int to account for dec. values
sum[j] += Number(current);
count[j]++;
}
}
}
for (let i = 0; i < colCount; i++) {
average.push((sum[i] + 0.0) / count[i]);
}
for (let i = 1; i < colCount; i++) {
// create an empty array
dictionary[headers[i]] = average[i];
}
return dictionary;
}
function isNullOrWhitespace(input) {
if (input == " ") {
return true;
} else {
return false;
}
}
This gives you a dictionary (Object) with the columns names as keys and numbers that appear to be the correct averages as values. But one must still check whether there is a fault in the logic somewhere and the averages are not correct in fact.
function processDataToDictionary(csv) {
function isNullOrWhitespace(input) {
if (input === " ") {
return true;
} else if (input === null) {
return true;
//} else if (input === undefined) {
//return true;
} else {
return false;
}
}
var allTextLines = csv.split(/\r\n|\n/);
var csvArray = [];
for (let i = 0; i < allTextLines.length - 1; i++) {
var row = allTextLines[i].split(',');
csvArray.push(row);
}
var colCount = csvArray[0].length;
var rowCount = csvArray.length;
//Arrays of values
var count = [];
var sum = [];
var average = [];
var headers = [];
for (let i = 1; i < colCount; i++) {
var current = csvArray[0][i].replace(/"/g, '');
sum.push(0);
count.push(0);
headers[i] = current;
}
/**** I added these two lines ****/
sum.push(0);
count.push(0);
for (let i = 1; i < rowCount; i++) {
for (let j = 1; j < colCount ; j++) {
// Remove the quotes from your array
current = csvArray[i][j].replace(/"/g, '');
// Added the Method IsNullOrWhiteSpace
if (!isNullOrWhitespace(current)) {
// Parse as double not int to account for dec. values
sum[j] += Number(current);
count[j]++;
}
}
}
for (let i = 0; i < colCount; i++) {
average.push((sum[i] + 0.0) / count[i]);
}
// I added this line:
dictionary = {};
for (let i = 1; i < colCount; i++) {
dictionary[headers[i]] = average[i];
}
return dictionary;
}
Let me know if this works out for you. You can loop through the values with: for (let key in dictionary) {console.log("key: " + key + " , value: " + dictionary[key]);} . Regards!
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});
I try to create a 4-dimensional array. I fill it dynamically and use content of it in another function. But the content is empty. Is there error below code?
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
I test below example :
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementByID('result').innerHTML = datas[0][0][0];
}
I see only ,,,,,,,.
I think the principal problem is that you're getting the element where you want to show your result badly using getElementByID instead of getElementById. Also make sure that your element has innerHTML property to write the result, or alternatively use value.
I write the follow example using <textArea id="result"></textArea> and generating a button which calls foo1();foo2(); onClick an it works for me.
In the sample I use an random value for timeInterval and allCoords.length.
Note also that you want a 4-dimensional array however you're creating a 3-dimensional.
var timeInterval = 60;
var allCoords = { length : 1};
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementById('result').value = datas[0][0][0];
}
<textArea id="result"></textArea>
<input type="button" value="foo" onclick="foo1();foo2();"/>
Hope this helps,
I need help fixing my existing code to accomplish what I am trying to do.
with the following sample data:
var SAMPLE_DATA = [{start: 30, end: 150}, {start: 540, end: 600}, {start: 560, end: 620}, {start: 610, end: 670}];
I need to do the following:
iterate through each sample object
determine if the current objects range (obj.start:obj.end) overlaps with any other object ranges.
record the total number of overlaps for that object into totalSlots property
determine the "index" of the object (used for it's left-to-right positioning)
mockup of what I am trying to accomplish:
As you can see in the mockup, slotIndex is used to determine the left-to-right ordering of the display. totalSlots is how many objects it shares space with (1 meaning it is the only object). 100 / totalSlots tells me how wide the square can be (i.e. totalSlots=2, means it is 100 / 2, or 50% container width).
Current Output from my code
Obj[0] slotIndex=0, totalSlots=0
Obj[1] slotIndex=1, totalSlots=1
Obj[2] slotIndex=1, totalSlots=2
Obj[3] slotIndex=0, totalSlots=1
expected/desired output from my code:
Obj[0] slotIndex=0, totalSlots=0
Obj[1] slotIndex=0, totalSlots=1
Obj[2] slotIndex=1, totalSlots=2
Obj[3] slotIndex=0, totalSlots=1
the code:
detectSlots: function(oldEventArr) {
oldEventArr.sort(this.eventSorter);
var newEventArr = [],
n = oldEventArr.length;
for (var i = 0; i < n; i++) {
var currObj = oldEventArr[i];
if ('undefined' == typeof currObj.totalSlots) {
currObj.slotIndex = 0;
currObj.totalSlots = 0;
}
for (var x = 0; x < n; x++) {
if (i == x) {
continue;
}
var nextObj = oldEventArr[x];
if (currObj.start <= nextObj.end && nextObj.start <= currObj.end) {
currObj.totalSlots++;
nextObj.slotIndex++;
}
}
newEventArr.push(currObj);
}
return newEventArr;
}
Please help me figure out what is going wrong in my code. I'm about 90% sure the problem lies in the if(currObj.start <= nextObj.end && nextObj.start <= currObj.end) statement where I am assigning/incrementing the values but I could use an extra set of eyes on this.
The slotIndex value can be calculated by using graph colouring algorithm. Note that brute force algorithm is exponential in time and will only be a viable solution for a small set of overlapping slots. Other algorithms are heuristics and you won't be guaranteed the least slot possible.
Here is an example of heuristic for your problem:
...
// init
var newEventArr = [], n = oldEventArr.length;
for (var i = 0; i < n; i+=1) {
var currObj = oldEventArr[i];
newEventArr.push({"start":currObj.start,"end":currObj.end,"slotIndex":undefined,"totalSlots":0});
}
var link = {};
// create link lists and totals
for (var i = 0; i < n; i+=1) {
var currObj = newEventArr[i];
if (!link.hasOwnProperty(""+i))
link[""+i] = {};
for (var j = i+1; j < n; j+=1) {
var nextObj = newEventArr[j];
var not_overlap = (currObj.end <= nextObj.start || nextObj.end <= currObj.start);
if (!not_overlap) {
currObj.totalSlots+=1;
nextObj.totalSlots+=1;
link[""+i][""+j] = 1;
if (!link.hasOwnProperty(""+j))
link[""+j] = {};
link[""+j][""+i] = 1;
}
}
}
var arrities = [];
for (var i = 0; i < n; i+=1) {
arrities.push( {"arrity":newEventArr[i].totalSlots, "indx":i} );
}
// sort by arrities [a better solution is using a priority queue]
for (var i = 0; i < n-1; i+=1) {
var current_arrity = -1, indx = -1;
for (var j = i; j < n; j+=1) {
if (arrities[j].arrity > current_arrity) {
indx = j;
current_arrity = arrities[j].arrity;
}
}
var temp = arrities[i];
arrities[i] = arrities[indx];
arrities[indx] = temp;
}
for (var i = 0; i < n; i+=1) {
var nodeIndex = arrities[i].indx;
// init used colors
var colors = [];
for (var j = 0; j < n; j+=1) {
colors.push(0);
}
//find used colors on links
for (var k in link[""+nodeIndex]) {
var color = newEventArr[k].slotIndex;
if (color || color === 0)
colors[color] += 1;
}
//find the first unused color
for (var j = 0; j < n; j+=1) {
if (colors[j] <= 0) {
// color the node
newEventArr[nodeIndex].slotIndex = j;
break;
}
}
}
return newEventArr;
...
like this
var not_overlap = (currObj.end <= nextObj.start || nextObj.end <= currObj.start);
if (!not_overlap) { ...
or
var overlap = (currObj.end > nextObj.start && nextObj.end < currObj.start);
if (overlap) { ...