How can I mirror a Multidimmensional array in javascript? - javascript

I need to be able to mirror a multidimensional array that changes in size. I'm currently hard coding for each particular array size and it is horribly inefficient.
Example:
Arr1 { 1 2 3 Arr2 { 1 2
4 5 6 3 4
7 8 9 } 5 6 }
Mirrored:
{ 3 2 1 { 2 1
6 5 4 4 3
9 8 7 } 6 5 }
Arrays range in size from 2x5 to 4x10.

Ok, so all you need is a horizontal mirror.
I suppose that your array contains an array for every line,
so that means that you just need to reverse every row.
for(var i=0;i<multiarr.length;i++){
multiarr[i].reverse();
}
or even better
multiarr.map(function(arr){return arr.reverse();});

For each of the lines:
For i = 0 to width/2:
arr[line][i] <-> arr[line][width - i]
Shouldn't that work?

Related

How to solve a JS logic problem where some values have to increment based on a previous value keeping always a specific order

I'm trying to solve a problem I have in my JS which is related to the following snippet
const signatureOrder = role => {
let order;
switch (role) {
case 'GUARDIAN':
order = 2;
break;
case 'ASSENTEE':
order = 3;
break;
case 'COUNTERSIGNEE':
order = 4;
break;
default:
order = 1;
break;
}
return order;
};
This method basically takes a role which currently is 4: CONSENTEE, GUARDIAN, ASSENTEE, COUNTERSIGNEE.
The CONSENTEE is always 1 and the order is always as the numbers from 1 to 5.
However, there can be a situation where I can have like multi roles coming:
1 consented
2 guardians
2 assentee
1 countersignee
This will be translated by the method in the following order
1 consented
2 Guardian
2 Guardian
3 Assentee
3 Assentee
4 Countersignee
This is not very correct and the output should be an increment of the single values but keeping the order fixed as below:
1 Consented
2 Guardian
3 Guardian
4 Assentee
5 Assentee
6 Countersignee
so what happens is that if we have already a guardian the next guardian becomes the previous guardian + 1 but stays always after Consentee and before Assentee.
The scenarios areas:
consentee is the one always be there is always 1
Always we have 4 roles
but we can have different combinations like no guardians, no assentee, yes countersigned and so on
The always present role is consentee the other roles are present or not depending of the situation
We can have already a list of this roles and adding again guardian should change the values for example
we have C 1, G 2, A 3 and we add G so will change +1 everywhere so will have
c1, G 2, G 3, A 4 ...
I would like to understand how to solve this in the right manner.
It seems to me you need something like this:
const sortRoles = rolesArray => {
const orderOfRole = {
'CONSENTED': 1,
'GUARDIAN': 2,
'ASSENTEE': 3,
'COUNTERSIGNEE': 4
}
rolesArray.sort((role1, role2) => orderOfRole[role1] - orderOfRole[role2])
}
where, in the end, the order is just the index in the sorted array, incremented by 1:
roles = ['GUARDIAN', 'ASSENTEE', 'ASSENTEE', 'CONSENTED']
sortRoles(roles)
roles.map((role, index) => console.log(`${index + 1}: ${role}`))
// 1: CONSENTED
// 2: GUARDIAN
// 3: ASSENTEE
// 4: ASSENTEE
You can extend this to having an object for the role, instead of a string. In that case you just need to extract the string from the object in the comparison function of sort() and use it like above.
You can sort all your elements based on an orderArray. Then, assign the order based on the element index.
Based on this answer:
const orderArray = ['CONSENTEE', 'GUARDIAN', 'ASSENTEE', 'COUNTERSIGNEE']
const elements = ['CONSENTEE', 'ASSENTEE', 'GUARDIAN', 'COUNTERSIGNEE', 'ASSENTEE', 'GUARDIAN']
elements.sort(function(a, b){
return orderArray.indexOf(a) - orderArray.indexOf(b);
});
const withOrder = elements.map((el, i) => {
return {role: el, order: i+1}
})
console.log(withOrder)

Yahtzee Full House array logic javascipt

Hey guys this is my first post on here so take it easy on me! Apologies in advance for how basic this question is as I'm a beginner. I'm in the process of self learning and googling has been my best friend so far but I'm struggling to work out what's going wrong here. Maybe it is my approach altogether...
I am building a very simple game of Yahtzee with Javascript as my first project. Most of the program works smoothly however I can't seem to get the logic right for a full house. For anyone that doesn't know Yahtzee is played with 5 dice and a full house is a pair combined with 3 of a kind so for example [1, 1, 1, 6, 6] or [4, 4, 5, 5, 5]. I have a generated array with .sort() applied so my thinking is the logic should be if index 0 = index 2 and index 3 = index 4 OR index 0 = index 1 and index 2 = index 4. I have tried with multiple nested if statements and without nested parentheses but no luck there either. I understand it must be how I've used the logical operator as the first parentheses of code in each if statement works by itself.
function fullHouseFunc() {
if ((newRoll[0] === newRoll[2])&&(newRoll[3] === newRoll[4])) {
fullHouse.innerHTML = 25;
} else if ((newRoll[0] === newRoll[2])&&(newRoll[3] === newRoll[4])) {
fullHouse.innerHTML = 25;
}
};
You were almost there, just change the indices in the first if statement to 0 === 1 and 2 === 4. You had both statements checking 0 === 2 and 3 === 4:
let fullHouse = document.querySelector('.fh')
let newRoll = [4,4,5,5,5]
function fullHouseFunc() {
if ((newRoll[0] === newRoll[1])&&(newRoll[2] === newRoll[4])) {
fullHouse.innerHTML = 25;
} else if ((newRoll[0] === newRoll[2])&&(newRoll[3] === newRoll[4])) {
fullHouse.innerHTML = 25;
}
}
fullHouseFunc()
<div class='fh'></div>

tried binary tree examples got the output as an object , how can i get this object values into an array to proceed further problem

Problem Statement
You are given a tree with N nodes rooted at 1. Each of the N nodes have some special number Se related to it. Each Node also has certain Power. Power of each node of the tree is defined as the number of heavy nodes in the subtree of the node (including that node). A heavy node is a node whose sum of divisors of its special number is a multiple of 3. You are given Q queries
There are two types of queries :
Type 1: Update special number of node.
Type 2: Tell the power of a certain node.
Input Format
First line: Two space separated integers N and Q denoting number of nodes in the tree and number of queries respectively.Each of the next N-1 lines: Two space separated integers U and V denoting there is an edge between them.
Next line: N space separated integers, i of which denotes the special number related to node i.First integer in next Q lines is T (the type of query).
if T is 1, it is followed by 2 integers X and Y denoting special number S of node X is to be updated to Y if T is 2, it is followed by single integer X
Output Format
For each query of type 2, output the power of the given node X.
Answer for each query should come in a new line
Explanation of my problem statement
Basically, we have a tree with numbered nodes (Si). Some of these nodes presumably have children (since it's a tree).
What the question is asking for is to find the "Power" of a node, where power is defined as the number of "heavy nodes" in it's children.
A "heavy node" is defined as a node which has the sum of its divisors for Si as a multiple of 3.
There is a bunch of information we need to calculate here:
For a given node, we need to get all it's children nodes
For each of child node, we need to find the divisors for that node's number
We need to sum the divisors and determine if it's a multiple of 3
given sample input and outputs like
sample input
5 5
1 2
1 3
3 4
3 5
16 8 17 3 18
2 1
2 3
1 3 7
2 1
2 3
sample output
3
2
2
1
Code that i tried
function BinarySearchTree() {
this.root = null;
}
BinarySearchTree.prototype.insertNode = function (val) {
var node = {
data : val,
left : null,
right : null
};
var currentNode;
if (!this.root) {
this.root = node;
} else {
currentNode = this.root;
while (currentNode) {
if (val < currentNode.data) {
if (!currentNode.left) {
currentNode.left = node;
break;
} else {
currentNode = currentNode.left;
}
} else if (val > currentNode.data) {
if (!currentNode.right) {
currentNode.right = node;
break;
} else {
currentNode = currentNode.right;
}
} else {
break;
}
}
}
};
var BST = new BinarySearchTree();
BST.insertNode(16);
BST.insertNode(8);
BST.insertNode(17);
BST.insertNode(3);
BST.insertNode(18);
console.log(BST);
my output
BinarySearchTree {
root:
{ data: 16,
left: { data: 8, left: [Object], right: null },
right: { data: 17, left: null, right: [Object] } } }
now i want to pass this data in array like [16,8,17,3,18]
and want to find the divisors of each node and have to check whether the divisors are divisible by 3 or not. How to do that?
Is this the right way of doing?
I have tried the question with following Approach :
a) For Getting Factors sum for each Special Number , precomuted using Sieve approach and if sum % 3 == 0 then putting 1 for that node.
b) Applied Traversal approach (dfs) to get the Sum of all nodes below including that node . Takes O(n) complexity.
c) For each query of Type 2 : I can give answer in O(1) . But for Type 1 : query , my code is taking O(n) complexity in worst case. Because for each node , it is updating count of each successive parent nodes. Hence complexity goes to O(q*n) which is way more than because queries is of order 10^6 and n is of order 10^6.

How to push a boolean into an array? "undefined" error

Why does the console print "undefined" when I print index 3? I'm trying to set index 3 to false and after 7 secs set it to true.
I've tried to change "nr", index 2, with success trying to narrow down the problem.
if (Math.random() < 0.005) {
nx = Math.random()*1000; //index0
ny = 200; //index1
nr = 5;//index2
var nfall = false; //index3
Apples.push([nx,ny,nr,nfall]); //simply inserting 'false' into index 3 doesn't work either.
setTimeout(function(){ Apples[2][2] = 500; Apples[2][3] = true;}, 7000); //3rd apple
console.log("New circle, x:"+Apples[2][0]+" y:"+Apples[2][1]+" nr:"+Apples[2][2] +" nfall:"+Apples[2[3]]);
//What works - in 7 seconds "nr" is updated from 5 to 500, but nfall is still undefined and NOT = true
Initially I expect the output of false from index 3 "nfall" then I expect the output of true from index 3 "nfall" after 7 secs.
Thank you
In your console.log call, you're accessing the array like this:
Apples[2[3]]
But it should be
Apples[2][3]
In the first version, you're accessing index 3 of the number 2 which actually is not an error, just undefined.
Your issue is the last part - you're accessing Apples[2[3]] which doesn't exist, and it's invalid syntax. You want to get the third item in Apples (which is an array), then access the fourth item of that array - do it simply with `Apples[2][3]:
const Apples = [1, 2, [3, 4, 5, 6]];
console.log(Apples[2][3]);

javascript how to "fix" a variable inside a function, through eval? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following function
var label = function() {
return 'File: '+texts[t];
};
which is attached to highcharts, specified here
http://api.highcharts.com/highcharts#plotOptions.pie.dataLabels.formatter
where t has values let's say from 1 to 10 and text[t] corresponds to a different text. I attach this function to 10 highchart tooltips so that it executes the function with a mouseOver event.
The intended logic is that chart 1 has the text[1] label appearing, chart 6 has text[6], etc.
The problem is that all charts have the text[10] appearing, since t has that value when the function is executed.
How can I solve this? Is it a place for eval() like
var label = function() {
return 'File: '+eval(texts[t]);
};
UPDATE: based on comments, trying
var label = function(t) {
return 'File: '+t+' '+texts[t];
};
doesn't work as expected, it prints "File: [object Object] undefined"
This is a very common closure problem:
You probably have t in a for loop, just wrap the code which attaches the handler in another function:
// This will not work the way you might expect
// The value of i is left at 10 because that is the last
// time it is changed in the attacheHandlers1 scope held
// but the closure in the anonymous function used as a callback
// in setTimeout
//
function attachHandlers1(){
for(var i = 0; i < 10 ; i++){
setTimeout(function(){
console.log("Version 1", i);
}, 100)
}
}
// This works because the value is closured in
// attachHandlerImpl as 'x' with different values for
// each invocation
//
function attachHandlers2(){
for(var i = 0; i < 10 ; i++){
attachHandlerImpl(i);
}
}
function attachHandlerImpl(x){
setTimeout(function(){
console.log("Version 2", x);
}, 100);
}
attachHandlers1();
attachHandlers2();
Will output:
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 1 10
Version 2 0
Version 2 1
Version 2 2
Version 2 3
Version 2 4
Version 2 5
Version 2 6
Version 2 7
Version 2 8
Version 2 9
Without knowing the rest of your implementation details, something like this could work:
var texts = ['Text 1', 'Text 2', 'Text 3']
var label = function(idx) {
return "File: " + texts[idx];
};
label(2) returns "File: Text 3"

Categories

Resources