javascript possible to use polygon[i].x instead of polygon[i][j]? - javascript

I'm struggling with this concept. Is is possible in javascript to create a user defined so I can use
polygon[i].x
polygon[i].y
instead of
polygon[i][0]
polygon[i][1]
The code for polygon[i][j] is below.
var polygon = new Array();
for (i = 0; i < 4; i++)
{
polygon[i] = new Array(2);
for (j = 0; j < 2; j++)
{
polygon[i][j] = "[" + i + "," + j + "]";
}
}
for (var i = 0; i < polygon.length; i++)
{
alert(polygon[i][1]);
}

As far as I could understand your code, this would be it:
var polygon = [],
i;
//push an object with x and y into the polygon array
for (i = 0; i < 4; i++){
polygon.push({
x : 'x #'+i,
y : 'y #'+i
});
}
//accessible as
polygon[index].x
polygon[index].y

Related

Acessing elements in jagged arrays

I am starting to write a recursion backtrack maze system printed in console but I already stumble in a trivial problem, I can't set the lines from my grid structure as you can see below:
console.log("Teste de Labirinto - Recursive Backtracking")
let grid = []
let cells = []
const width = 8
const height = 10
for (let i = 0; i < width; i++){
cells.push(".")
}
for (let j = 0; j < height; j++){
grid.push(cells)
}
function printMaze(){
let line = " "
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
line += " " + grid[j][i] + " "
}
console.log(line)
line = " "
}
}
function createMazeBorder() {
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
if(i == 0) {
grid[j][i] = "X"
}
}
}
}
createMazeBorder()
printMaze()
How can I create a wall of "X" in my grid? I tried all the "ifs" as possible and swap the "i" and "j", widht, height, still can't do it... Thank you for the time.
Well, solved it, it was not possible to create the walls because all my cells got the same reference, there is the code:
console.log("Teste de Labirinto - Recursive Backtracking")
let grid = []
const width = 8
const height = 10
for (let j = 0; j < height; j++){
let cells = [];
for (let i = 0; i < width; i++){
cells.push(".")
}
grid.push(cells)
}
function printMaze(){
let line = " "
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
line += " " + grid[j][i] + " "
}
console.log(line)
line = " "
}
}
function createMazeBorder() {
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
if(j == 0 || i == 0 || j == height-1 || i == width-1) {
grid[j][i] = "X"
}
}
}
}
createMazeBorder()
printMaze()

How can I construct a path between two distant node in pathfinding3d.js?

To create a path in pathfinding3d.js, we have to add all nodes and their neighbors.
var nodes = [
new PF.Node(0,0,0),
new PF.Node(1,0,0),
new PF.Node(2,0,0),
];
nodes[0].neighbors.push(nodes[1]);
nodes[1].neighbors.push(nodes[0],nodes[2]);
nodes[2].neighbors.push(nodes[1]);
var finder = new PF.AStarFinder();
var path = finder.findPath(nodes[0], nodes[2], nodes);
The problem is, if I want to create a large 3d mesh of node, to create a path I need to push neighbour in each node to create a path.
Is there another way to do this? Can I create path from one point to another distant just by adding the origin node and destination node? Such as createPath(node(1,2,3), node(4,5,6) and the path between them create the path.
Or is there another solution more fitting than this?
I've managed to find a solution. First, I create three function to help me create layout, make all node connected, and, then, make only the necessary node connected using the pathfinding3d.js to calculate which node it need to connect based on proposed connected nodes. Here are the function:
function create3DLayout(x, y, z) {
let layout = new Array(x);
for (let i = 0; i < x; i++) {
layout[i] = new Array(y);
for (let j = 0; j < y; j++) {
layout[i][j] = new Array(z);
for (let k = 0; k < z; k++) {
layout[i][j][k] = new PF.Node(i, j, k);
}
}
}
return layout;
}
function createAllWalkable(layout) {
for (let i = 0; i < layout.length; i++) {
for (let j = 0; j < layout[i].length; j++) {
for (let k = 0; k < layout[i][j].length; k++) {
let mInit = (i + -1 >= 0) ? -1 : 0;
let mEnd = (i + 1 < layout.length) ? 1 : 0;
for (let m = mInit; m <= mEnd; m++) {
let nInit = (j + -1 >= 0) ? -1 : 0;
let nEnd = (j + 1 < layout[i].length) ? 1 : 0;
for (let n = nInit; n <= nEnd; n++) {
let oInit = (k + -1 >= 0) ? -1 : 0;
let oEnd = (k + 1 < layout[i][j].length) ? 1 : 0;
for (let o = oInit; o <= oEnd; o++) {
let xt = m + i;
let yt = n + j;
let zt = o + k;
if (layout[xt][yt][zt] != layout[i][j][k]) {
layout[i][j][k].neighbors.push(layout[xt][yt][zt]);
}
}
}
}
}
}
}
}
function createWalkablePath(layout, nodeStart, nodeEnd) {
// Create building
let walkablelayout = create3DLayout(layout.length, layout[0].length, layout[0][0].length);
// Create path to every corner of building
createAllWalkable(walkablelayout);
let startPath = walkablelayout[nodeStart.x][nodeStart.y][nodeStart.z];
let endPath = walkablelayout[nodeEnd.x][nodeEnd.y][nodeEnd.z];
let explorer = new PF.AStarFinder();
let exploredPath = explorer.findPath(startPath, endPath, walkablelayout);
for (let i = 0; i < exploredPath.length - 1; i++) {
layout[exploredPath[i][0]][exploredPath[i][1]][exploredPath[i][2]].neighbors.push(layout[exploredPath[i + 1][0]][exploredPath[i + 1][1]][exploredPath[i + 1][2]]);
layout[exploredPath[i + 1][0]][exploredPath[i + 1][1]][exploredPath[i + 1][2]].neighbors.push(layout[exploredPath[i][0]][exploredPath[i][1]][exploredPath[i][2]]);
}
}
Then, I'll do the calculation:
var nodes = create3DLayout(26, 26, 3);
createWalkablePath(nodes, nodes[7][14][0], nodes[9][17][0]);
createWalkablePath(nodes, nodes[0][0][0], nodes[25][25][2]);
createWalkablePath(nodes, nodes[0][25][0], nodes[9][17][0]);
createWalkablePath(nodes, nodes[1][15][1], nodes[9][17][0]);
createWalkablePath(nodes, nodes[20][25][1], nodes[9][17][0]);
// Create finder
var finder = new PF.AStarFinder();
// origin
var startNode = nodes[14][14][2];
console.log(startNode);
// Destination
var endNode = nodes[17][17][2];
console.log(endNode);
var path;
// Find path
path = finder.findPath(startNode, endNode, nodes);
console.log(path);
Hope this helps anyone who face same problem.

Looping javascript multi array

var size = ['s','m'];
var color = ['red','blue','black'];
var material = ['cotton','linen'];
i want result like :
array("s,red,cotton","s,red,linen","s,blue,cotton","s,blue,linen","s,black,cotton","s,black,linen");
array("m,red,cotton","m,red,linen","m,blue,cotton","m,blue,linen","m,black,cotton","m,black,linen");
would you like to help me please use javascript or jquery. Thank you :)
Three loops for each array. Just loop through every array, and append to new array.
var size = ['s','m'];
var color = ['red','blue','black'];
var material = ['cotton','linen'];
var arrayMaterials = []
for (var i = 0; i < size.length; i++) {
for (var j = 0; j < color.length; j++) {
for (var k = 0; k < material.length; k++) {
arrayMaterials.push(size[i] + "," + color[j] + "," + material[k]);
}
}
}
console.log(arrayMaterials);
As said in Comment you need 3 loops
var size = ['s','m'];
var color = ['red','blue','black'];
var material = ['cotton','linen'];
for (var a = 0; a < size.length; a++) {
for (var b = 0; b < color.length; b++) {
for (var c = 0; c < material.length; c++) {
console.log(size[a] + " , " + color[b] + " , " + material[c]);
}
}
}

how to make an Array of a for loop variable with Javascript?

I am new to this forum and I have searched and after a few hours of banging my head on the wall and even registering back at TeamTreeHouse for a detailed course on Arrays I couldn't find what I was looking for. I love teamTreehouse though.
I got a problem with trying to switch from C# to Javascript with lists and Arrays beeing different. It is for RPG Maker MV. I want to make a list of positions X and Y of a "CharacterID" and calculate the distance to each tiles that I have put inside an Array of X positions and Y positions. The ID of the Character is 0 or more specific it is eventArray[ID, x, y] for it's ID and its x and y positions. So I got the position of the CharacterID but I don't understand for the life of me how to loop the thing so that I get max 10 lines of code instead of 36 lines (length of my Array). In C# Vector3's are added automatically to a list or a dictionary and are separate "items" but if I try with the same principle with a Javascript Array I get 1 item containing the whole list of entry and I don't know how to retrieve them.
var eventArray = [];
var tilePosArrayXadd1 = [];
var tilePosArrayYadd1 = [];
Game_Event.prototype.initialize = function (mapId, eventId) {
Game_Character.prototype.initialize.call(this);
this._mapId = mapId;
this._eventId = eventId;
this.locate(this.event().x, this.event().y);
var eventX = this.event().x;
var eventY = this.event().y;
this.refresh();
eventArray.push([eventId, eventX, eventY]);
};
Game_Player.prototype.locate = function (x, y) {
Game_Character.prototype.locate.call(this, x, y);
actorX = $gamePlayer.x;
actorY = $gamePlayer.y;
main(actorX, actorY);
};
function main(x, y) {
var maxTileDist = 2;
///TOPRIGHTTILES
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y + 1);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y + 2);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y + 3);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y + 4);
};
///TOPLEFTTILES
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y + 1);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y + 2);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y + 3);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y + 4);
};
///BOTTOMRIGHTTILES
/*for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push([[i + x+1], y]);
};*/
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y - 1);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y - 2);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y - 3);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i + x);
tilePosArrayYadd1.push(y - 4);
};
///BOTTOMLEFTTILES
/*for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push([[i - x], y]);
};*/
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y - 1);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y - 2);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y - 3);
};
for (var i = 0; i < maxTileDist ; i++) {
tilePosArrayXadd1.push(i - x);
tilePosArrayYadd1.push(y - 4);
};
var tilex0 = [];
var tiley0 = [];
for (var j = 0; j < tilePosArrayXadd1.length; j++) {
tilex0.push(eventArray[0][1] - tilePosArrayXadd1[j]);
tiley0.push(eventArray[0][2] - tilePosArrayYadd1[j]);
console.log(tilex0[0])
console.log(tilex0.length)
}
the code above gives me a length of 1... when I thought it would give me a list of tilePosArrayXadd1.length as declared with the "j" variable. So lol can anyone explain what I am doing wrong or guide me to a very good tutorial containing explanations of this issue. Thank you guys for your time.
Ninekorn
You're new here. If you haven't looked over the Help Center, it would probably be a good idea, especially the section on creating a minimal, complete, and verifiable example
When I try to do that for your code, I come up with something that works as I presume is expected:
var events = [[10, 20]]
var foo = [];
var bar = [1, 2, 3]
for (var j = 0; j < bar.length; j++) {
foo.push(events[0][1] - bar[j]);
}
console.log(foo); //=> [19, 18, 17]
console.log(foo.length); //=> 3
It is very often the case that when trying to create such an example, you will find the error on your own. But if not, can you build this simple example back out to your code and see when it first breaks? That should help solve it.

How to make a triangle using for loop javascript

I have a simple question although i cannot manage to resolve this problem. Hope you can help. I need to make triangle using for loop and from this 4 exercises I don't know what to do with the third one. I haven't used Javascript before, so any help would be appreciated.
# # # # #
# # # #
# # # <----- here is triangle i need to make. Just in case
# #
#
var i;
var j;
for (i = 0; i <= 5; i++ )
{
document.write("</br>");
for ( j = 0; j < 6-i; j++ )
{
document.write( "&nbsp&nbsp" );
}
for ( j = 6-i; j <= 5; j++ )
{
document.write( "*" );
}
}
This is code I wrote for D in photo.
And I'm sorry i did not add it at first.
for (let line = "*"; line.length < 8; line += "*")
console.log(line);
this question came in this book: http://eloquentjavascript.net
I don't know why there are so bad answers on google for this one.
function leftTriangle(rows){
let result = '';
for(let i=rows;i>0;i--){
if(i===rows) {
result += '*'.repeat(i) + '\n';
}else{
let empty = rows-i
result+= ' '.repeat(empty) + '*'.repeat(i)+ '\n'
}
}
return result;
}
console.log(leftTriangle(5))
I'm sure there are better solutions (simply left-padding with spaces comes to mind), but here's the quick and dirty one I created from your own solution.
for (var i = 0; i < 5; i++) {
for (var j = 0; j < i; j++) {
document.write(" ");
}
for (var j = 5; j > i; j--) {
document.write("#");
if (j > i + 1) document.write(" ");
}
document.write('<br/>')
}
https://js.do/code/diamondsinthesky
Something like this?
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
Thank you for your help. I did it. It was too obvious but somehow I couldn't find it. Thank you one more time. Here is how i did it.
for (i = 5; i > 0; i--) {
document.write("</br>");
for (j = 0; j < 6 - i; j++) {
document.write("&nbsp&nbsp");
}
for (j = 6 - i; j <= 5; j++) {
document.write("*");
}
}
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
You can also do this if you are looking for something different.
This code is for a triangle of 7 lines.
let size = 8;
let y = "#";
for (let x = 0; x < size; x++)
{
console.log(y);
y += "#";
}
// Second method
for (let i = 1; i < size;i++)
{
let me ="#".repeat(`${i}`)
console.log(me);
}
var size = 5;
for (var i = 0; i < size; i++) {
for (var j = 0; j <= i; j++) {
document.write("*");
}
document.write("<br />\n");
}

Categories