Why this solution can't use a for-loop? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was donig Intersection of Two Arrays II in leetcode.
I found solution in it and one thing that i don't understand is
Why this solution can't use for loop?
if i changed this line of code
while(p1 < nums1.length && p2 < nums2.length)
into
for(let p1=0,let p2=0;p1 < nums1.length && p2 < nums2.length;p1++;p2++)
the output will changed to only [2] not [2,2]
Why is that happened?
Request:
Given two arrays, write a function to compute their intersection.
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Here is the JS code:
var intersect = function(nums1, nums2) {
nums1.sort(cm);
nums2.sort(cm);
var p1 =0
var p2 =0
var res = [];
while(p1 < nums1.length && p2 < nums2.length) {
if(nums1[p1] === nums2[p2]) {
res.push(nums1[p1]);
p1++;
p2++;
} else if(nums1[p1] > nums2[p2]) {
p2++;
} else {
p1++;
}
}
return res;
};
var cm = function(a, b) {
return a - b;
}
console.log(intersect([1,2,2,1], [2,2]))

Consider the following for loop
for(let p1=0,let p2=0;p1 < nums1.length && p2 < nums2.length;p1++;p2++)
In this p1 and p2 always get increased in every loop. But in you you original code. There are increased conditionally
Why for loop returns `[2]`:
When you increase p1 and p2 initially setting them to 0. So it means
in every loop the p1=p2. And hence it will compare the values on same indexes.
In the following two arrays.
[1,2,2,1]
[2,2]
Only the second 2 ([1,2,2,1] [2,2]) will be matched because both have same index 1.
else if(nums1[p1] > nums2[p2]) {
p2++;
} else {
p1++;
}
You can also do that using filter() and includes()
const intersect = (num1,num2) => num1.filter(x => num2.includes(x))
console.log(intersect([1,2,2,1],[2,2]))

Related

Debugging small javascript with exponents [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 2 years ago.
Improve this question
n = 1;
while (n < 1024) {
alert(Math.pow(n, 2));
n = n + 2;
}
How can I make this display the powers of 2 from 2^0 to 2^10 inclusive i.e. (1-1024) and end once it reaches 1024 in Javascript
I would do something like this:
for(let n = 0; n <= 10; n++) {
console.log(2 ** n)
}
This logs the answer of each loop iteration. As Pointy suggested in the comment, we have to make the n value iterate from 1 to 10, since that is the variable that generates the output, whereas the 1024 is simply the output that comes from the power values. You could also use Math.pow as follows:
for(let n = 0; n <= 10; n++) {
console.log(Math.pow(2, n))
}
Implementing Secan's suggestion, here is a function which will take any number as a parameter:
function foo(x, exp) {
for(let i = 0; i <= exp; i++) {
console.log(x ** i)
}
}
So to apply this to the original answer, we would call it like this:
foo(2, 10)
Sorry for the ambuiguity with my original question. I've figured it out-
n=0;
while (n <= 10) {
alert(Math.pow(2, n));
n = n + 1;
}
Setting n=0, n<=10 in while and changing n + 1 instead of 2 resolved my issue. Thanks for your responses!

How i can get array from loop for? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Hello everybody can you help me get percent with steps?enter image description here
function getPlan(currentProduction, months, percent) {
// write code here
let sum = 0;
for(let i = 0; i < months; i++){
let workCalculate = currentProduction * percent / 100;
sum *= workCalculate;
}
return Math.floor(sum);
}
example:
getPlan(1000, 6, 30) === [1300, 1690, 2197, 2856, 3712, 4825]
getPlan(500, 3, 50) === [750, 1125, 1687]
Simply push each iteration to an array and return that array.
function getPlan(currentProduction, months, percent) {
// write code here
// starting at currentProduction
let sum = currentProduction;
// output
let output = [];
for(let i = 0; i < months; i++){
// progressive from sum and not from currentProduction
let workCalculate = sum * percent / 100;
sum += Math.floor(workCalculate);
output.push(sum)
};
return output
};
console.log(getPlan(1000, 6, 30))
console.log(getPlan(500, 3, 50))
Currently your method returns a number, not an array. What do you need exactly? Do you need it to return an array or you just want to see the intermediate values of the calculation done inside the loop?
In the first case, create an empty array and add the values you want to it in each step of the loop:
function getPlan(currentProduction, months, percent) {
// write code here
let sum = 0;
var result= [];
for(let i = 0; i < months; i++){
let workCalculate = currentProduction * percent / 100;
sum *= workCalculate;
result.push(sum);
}
return result;
}
In the second case, you have 2 options:
Add a console.log so the values are printed to the console.
Add a breaking point so the code stops at it and you can see the values of the variables and go step by step through the execution of the program.
This is a bit vague because your need is unclear, hope it helps though!
function getPlan(currentProduction, months, percent) {
var plan=[];
var workCalculate=currentProduction;
for(var i=0; i<months; i++) {
workCalculate*=(1+percent/100);
plan.push(Math.floor(workCalculate));
}
return plan;
}
console.log(getPlan(1000, 6, 30));
console.log(getPlan(500, 3, 50));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Implementing OneRule algorithmn in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
OneR, short for "One Rule", is a simple yet accurate classification algorithm that generates one rule for each predictor in the data, then selects the rule with the smallest total error as its "one rule".
I tried to find code samples on GitHub, but found only one, developed with R language. How could I implement this algorithm in Javascript?
What I have tried?
I am trying to implement following this sample article:
https://www.saedsayad.com/oner.htm
class OneR {
/**
* Pass dataset which will be an array of values.
* Last value is classifcator's value.
* All other values are predictors.
*
* Example
*
* The meaning of sequence values:
* |Outlook|Temp|Humidity|Windy|Play Golf|
*
* Representation of a sequence:
* ['rainy', 'hot', 'high', 0, 0]
*
* True and False are represented as zeros or ones
*/
constructor(data = []) {
this.data = data;
this.frequences = {};
}
predict() {
if (this.data && this.data.length > 0) {
const firstRow = this.data[0];
const predictorCount = firstRow.length - 1;
let classifcator;
// For each predictor,
for (let i = 0; i < predictorCount; i++) {
// For each value of that predictor, make a rule as follos;
for (let y = 0; y < this.data.length; y++) {
// Count how often each value of target (class) appears
classifcator = this.data[y][predictorCount];
console.log(classifcator);
// Find the most frequent class
// Make the rule assign that class to this value of the predictor
}
// Calculate the total error of the rules of each predictor
}
// Choose the predictor with the smallest total error
} else {
console.log("Cannot predict!");
}
}
}
module.exports = {
OneR
};
I have loaded data from csv
rainy,hot,high,0,0
rainy,hot,high,1,0
overcast,hot,high,0,1
sunny,mild,high,0,1
sunny,cool,normal,0,1
sunny,cool,normal,1,0
overcast,cool,normal,1,1
rainy,mild,high,0,0
rainy,cool,normal,0,1
sunny,mild,normal,0,1
rainy,mild,normal,1,1
overcast,mild,high,1,1
overcast,hot,normal,0,1
sunny,mild,high,1,0
If I understand correctly how the frequency tables must be compared (lowest error rate, highest accuracy), you could use Maps so to cope with non-string types if ever necessary.
Although your example has target values that are booleans (0 or 1), in general they could be from a larger domain, like for example "call", "fold", "raise", "check".
Your template code creates a class, but I honestly do not see the benefit of that, since you can practically only do one action on it. Of course, if you have other actions in mind, other than one-rule prediction, then a class could make sense. Here I will just provide a function that takes the data, and returns the number of the selected predictor and the rule table that goes with it:
function oneR(data) {
if (!data && !data.length) return console.log("Cannot predict!");
const predictorCount = data[0].length - 1;
// get unique list of classes (target values):
let classes = [...new Set(data.map(row => row[predictorCount]))];
let bestAccuracy = -1;
let bestFreq, bestPredictor;
// For each predictor,
for (let i = 0; i < predictorCount; i++) {
// create frequency table for this predictor: Map of Map of counts
let freq = new Map(data.map(row => [row[i], new Map(classes.map(targetValue => [targetValue, 0]))]));
// For each value of that predictor, collect the frequencies
for (let row of data) {
// Count how often each value of target (class) appears
let targetValue = row[predictorCount];
let predictorValueFreq = freq.get(row[i]);
let count = predictorValueFreq.get(targetValue);
predictorValueFreq.set(targetValue, count+1);
}
// Find the most frequent class for each predictor value
let accuracy = 0;
for (let [predictorValue, predictorValueFreq] of freq) {
let maxCount = 0;
let chosenTargetValue;
for (let [targetValue, count] of predictorValueFreq) {
if (count > maxCount) {
// Make the rule assign that class to this value of the predictor
maxCount = count;
chosenTargetValue = targetValue;
}
}
freq.set(predictorValue, chosenTargetValue);
accuracy += maxCount;
}
// If this accuracy is best, then retain this frequency table
if (accuracy > bestAccuracy) {
bestAccuracy = accuracy;
bestPredictor = i;
bestFreq = freq;
}
}
// Return the best frequency table and the predictor for which it applies
return {
predictor: bestPredictor, // zero-based column number
rule: [...bestFreq.entries()]
}
}
let data = [
["rainy","hot","high",0,0],
["rainy","hot","high",1,0],
["overcast","hot","high",0,1],
["sunny","mild","high",0,1],
["sunny","cool","normal",0,1],
["sunny","cool","normal",1,0],
["overcast","cool","normal",1,1],
["rainy","mild","high",0,0],
["rainy","cool","normal",0,1],
["sunny","mild","normal",0,1],
["rainy","mild","normal",1,1],
["overcast","mild","high",1,1],
["overcast","hot","normal",0,1],
["sunny","mild","high",1,0]
];
let result = oneR(data);
console.log(result);

JavaScript Function. Can someone help or explain why it logs 120? I see 20 based on my analysis [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 3 years ago.
Improve this question
I would like to sum up all the elements inside the array covertedValue. Why I am getting a Nan result? whats wrong with the recursive function I have written?
function findOutlier(integers){
var covertedValue = integers.map(x => x % 2);
var total = 0;
for (i=0 ; i<covertedValue.length ; i++){
total = total + covertedValue[0] + findOutlier(integers.splice(1));
}
console.log(total);
}
findOutlier([0, 1, 2]);
because this line create a function and a private alias to itself
var factorial =
// create a variable named factorial in global scope
// it contains the function fac
function fac(n) {
// fac is a function available only in the factorial var context
return n < 2 ? // if n < 2
1 : // return 1
n * fac(n - 1); // else return n * fac(n - 1)
};
console.log(factorial(5));
// calls factorial(5) which is 5*fac(4) which is 5*(4*fac(3)) ...
note that the fac function is not available outside of itself
var factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); };
console.log(fac(5));
This way of coding where a function call itself is called recursive programming it can be hard to grasp at first but can be VERY powerful in some situations
recurcive programming can easily be used when the result of func(n) depend directly on the result of func(n+x)
the cond ? then : else structure is called ternary operator, it's a way to make if in one line, can become messy very quick
as you noted in a comment : recursion can be replaced by a loop (it can be hard to do it sometime)
here's a more beginner way to write it
function factorial(n) {
if(n < 2) {
return 1
} else {
let fac = 1;
for(var i = n; i > 0; i--) {
fac = fac * i
// here fac takes the value of the precedent iteration
}
// this whole loop is the same as i*fac(i-1) in the recurcive way
return fac
}
};
console.log(factorial(5));

Find n-th element of Fibonacci sequence given first two integers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm doing some practicing and I've come across a question that I'm having trouble wrapping my head around.
You are given the first two integers of a Fibonacci sequence. You are to then find the n-th element of the sequence.
For example, given the sequence 2,4, output the 4th element. The answer is 10, because:
2,4,6,10
How would I program this solution in JavaScript (with and without recursion)?
Without recursion:
function Fibonacci(first, second, n){
let iter = 3; //set it to 3 since you are passing the first and second
//Use while loop instead of recursive calls to Fibonacci
while(iter < n){
let temp = first;
first = second;
second = temp + first;
iter++;
}
//If n is one, return first
if(n == 1)
return first;
//Display last item in sequence
console.log(second);
//Or return it
return second;
}
With Recursion:
function Fibonacci(first, second, n){
//If n - 2 (passing first 2 in sequence) is greater than or equal to 0, do operations and recall Fibonacci
if((n - 2) > 0){
let temp = first;
first = second;
second = temp + first;
n--;
return Fibonacci(first, second, n);
}
//If n is one, return first
if(n == 1)
return first;
//Display last item in sequence
console.log(second);
//Or return it
return second;
}
Here is a solution using recursion:
function nthFib( u0, u1, n ) {
return n > 1 ? nthFib( u1, u0 + u1, n - 1 ) : u0;
}
console.log( nthFib( 2, 4, 4 ) );
Here is one using a loop:
function nthFib( u0, u1, n ) {
for ( let i = 2; i <= n; i++ )
[ u0, u1 ] = [ u1, u0 + u1 ];
return u0;
}
console.log( nthFib( 2, 4, 4 ) );
You can also do it using a closed formula and then you don't need recursion or looping:
function nthFib( u0, u1, n ) {
const sqrt5 = 5**.5;
const golden = (1 + sqrt5)/2;
const a = (u1 - u0*(1 - golden))/sqrt5;
const b = (u0*golden - u1)/sqrt5;
return Math.round(a*golden**--n + b*(1 - golden)**n);
}
console.log( nthFib( 2, 4, 4 ) );

Categories

Resources