Not Throwing an error, but not logging to console to test - javascript

Morning. I'm trying to calculate population density using for loop and if/else statements. When logging the results I get no errors but also get no log results for the variable density. Wonder if folks might be able to see what I'm missing in my functions. Thanks!
var cityCoords = [[30.5833302, -114.2666702], [48.864716, 2.349014],[40.730610, -73.935242 ]] // city coords
var cityPops = [8266000, 10958000, 19491339] // city populations
var cityAreas = [3280, 41, 303]// city areas in sq. miles
// NOTE. You can use the arrays you built in Lab 3, just make sure you keep track of your variable names
var button = document.getElementById("map-cities");
button.addEventListener("click", function () {
var units = prompt('Enter the units for calculating population density', 'Enter "miles" or "km"');
var mapCities = function(){ // assign function to variable mapCities
mapCities(units); // call mapCities function units variable as an argument
}
// call a function named mapCities, and send the units variable as an argument
}); // addEventListener callback function ends here
// Define function
function mapCities(units) {
for (var i = 0; i < cities.length; i++) {
var cityName = cities[i] ;
var cityNumPeeps = cityPops[i];
var cityZone = cityAreas[i];
var density = calcPopDensity(CityNumPeeps, CityZone, units); // call calcPopDensity passing population, cityZone and units as arguments
console.log(density);
}
};
function calcPopDensity(pop,area,unit){
if (units == "miles"){
cityZone/cityNumPeeps
return
} else if (units == "km"){
cityZone * 1.60934 / cityNumPeeps
return
}
};

There's... a few issues here. But, we all learn from our mistakes!
var cityCoords = [[30.5833302, -114.2666702], [48.864716, 2.349014],[40.730610, -73.935242 ]]
var cityPops = [8266000, 10958000, 19491339]
var cityAreas = [3280, 41, 303]
var button = document.getElementById("map-cities");
button.addEventListener("click", function () {
var units = prompt('Enter the units for calculating population density', 'Enter "miles" or "km"');
mapCities(units); // <= You just want to call the function here, no need to do the function-wrapping you had!
}
});
function mapCities(units) {
for (var i = 0; i < cities.length; i++) { // <= You don't actually have this array defined (cities)?
var cityName = cities[i] ;
var cityNumPeeps = cityPops[i];
var cityZone = cityAreas[i];
var density = calcPopDensity(CityNumPeeps, CityZone, units); // <= match case - 'cityNumPeeps' vs 'CityNumPeeps' etc
console.log(density);
}
};
function calcPopDensity(pop,area,unit){
if (units == "miles"){
return cityZone/cityNumPeeps // <= move the return to this line - we want the result of the calculation back!
} else if (units == "km"){
return cityZone * 1.60934 / cityNumPeeps // <= again, return statement
}
};

Related

Save sum in variable in jQuery each for range

I am working on a specific calculator and I need to sum up variables in my jQuery.each for a range from 0 to 4 (= 5 years).
I have found many pages where the solution is described, but only with references to an element, not to the range.
My code:
jQuery.each(new Array(duration),
function(n){
var investment = 1000; // 1000$
var duration = 5; // 5 years
var revenueRatio = 10; // 10% revenue / year
var reinvest = 50; // 50% reinvestment
if(n == 0){
var revenueReinvest = 0;
var newInvestment = investment;
}else{
console.log(revenueReinvest); // undefined
console.log(newInvestment); // undefined
var interest = ( ( newInvestment - investment ) * ( revenueRatio / 100 ) );
var removeInterest = interest * reinvest / 100;
var restIntereset = interest - removeInterest;
revenueReinvest += restIntereset;
newInvestment = newInvestment + revenueReinvest;
}
}
);
Any help or idea would be great! Thank you!
The issue with the code is that you have declared revenueReinvest and newInvestment inside the if block and using it inside the else block. This wont be possible. Declare revenueReinvest and newInvestment outside each loop and assign the values to them inside if statement. Now you can access the assigned values inside else statement.
You have to declare the variable outside the loop to prevent redeclaring of the variable inside the loop. Each time the variable gets redeclared inside the loop, old value will be lost.
The below code will work
$(document).ready(function () {
const duration = 4;
// Declare here
var revenueReinvest;
var newInvestment;
jQuery.each(new Array(duration),
function (n) {
var investment = 1000; // 1000$
var duration = 5; // 5 years
var revenueRatio = 10; // 10% revenue / year
var reinvest = 50; // 50% reinvestment
if (n == 0) {
// assign value here
revenueReinvest = 0;
newInvestment = investment;
} else {
var interest = ((newInvestment - investment) * (revenueRatio / 100));
var removeInterest = interest * reinvest / 100;
var restIntereset = interest - removeInterest;
revenueReinvest += restIntereset;
newInvestment = newInvestment + revenueReinvest;
}
}
);
console.log(revenueReinvest); // will be defined
console.log(newInvestment); // will be defined
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

How to reduce number of computations during d3.js transition?

So right now, I'm trying to implement a search bar function into my d3.js plot. Right now it doesn't do anything, but that's not the issue at the moment. The problem is that when I type/delete something from the bar, there's visible lag/choppiness in the characters appearing/disappearing. I believe the issue is stemming from my plot. I have 140+ dots moving around the screen, and their position is being interpolated. So from the beginning to the end of the transition, my code has to compute 140 positions thousands of times over.
I've looked into trying to reduce the cardinality of the d3.interpolateNumber function, but it appears that there isn't a third argument to change the number of terms like in a linspace command. Right now I have an array of 1000 numbers for my function to run through, but I don't know how to pass the array to my other functions.
Below are the pertinent functions for this issue. The commented line in tweenPatch is the original code I had that made my code run, but gave my plot computational issues. Variables arr, curr, and step were my attempt to fix the situation, but I haven't been able to figure out how to pass the array into displayPatch().
function tweenPatch() {
var patch = d3.interpolateNumber(1, 26);
var arr = [];
var curr = 1;
var step = (26 - 1) / (1000 - 1);
for (var i = 0; i < 1000; i++) {
arr.push(curr + (step * i));
}
return arr.forEach(function(d) {
console.log(arr[d]);
displayPatch(arr[d]);
});
//return function(t) { displayPatch(t); };
}
function displayPatch(patch) {
dots.data(interpolateData(patch), function(d) { return d.name; }).call(position).sort(order);
var inter = Math.floor(patch);
var seas = 8;
var patc = 1;
if (inter > 24) {
seas = 9;
patc = inter - 24;
} else {
patc = inter;
}
label.text("Patch " + seas + "." + patc);
}
function interpolateValues(values, number) {
old = Math.floor(number);
upd = Math.ceil(number);
var old_data = values.filter(function(d) {return d.internal == old;});
var new_data = values.filter(function(d) {return d.internal == upd;});
var oobj = old_data[0];
var nobj = new_data[0];
var onum = oobj[Object.keys(oobj)[4]];
var nnum = nobj[Object.keys(nobj)[4]];
var difint = number - old;
var difdis = 0;
var newnum = nnum;
if (nnum > onum) {
difdis = nnum - onum;
newnum = ((difint) * difdis) + onum;
} else if (onum > nnum) {
difdis = onum - nnum;
newnum = onum - ((difint) * difdis);
}
return newnum;
}
I believe switching my SVG to a canvas may help things, but since I have no knowledge of canvas I'd rather leave that as a last resort.

JavaScript: Trying to subtract two variables returns NaN for me

I'm trying to build a simple calorie calculator and for some odd reason, my math for totalCalories (which is calories, an integer, minus calorieDeduction, an integer) keeps returning NaN. Can anyone tell me what I'm missing? I've tested console.log outputs on both my calories entered and on calorieDeduction and they both return as integers. I don't understand why subtracting one from the other returns NaN, unless I need to maybe define totalCalories as an integer by hand. I'm a newbie so I'm not necessarily sure the best method to do that. Any help appreciated. Thanks!
var maxCaloriesCodes = ['FMW', 'FLW', 'MMW', 'MLW'];
var maxCaloriesAllowed = [2000, 1500, 2500, 2000];
var exerciseCodes = ['FL', 'FM', 'FV', 'ML', 'MM', 'MV'];
var exerciseCalories = [240, 370, 580, 300, 460, 730];
function performAssessment(){
var genderElem = document.getElementById('gender_id');
var genderValue = genderElem.options[genderElem.selectedIndex].value;
var genderText = genderElem.options[genderElem.selectedIndex].text;
var goalElem = document.getElementById('goal_id');
var goalValue = goalElem.options[goalElem.selectedIndex].value;
var goalText = goalElem.options[goalElem.selectedIndex].text;
var exerciseElem = document.getElementById('exercise_id');
var exerciseValue = exerciseElem.options[exerciseElem.selectedIndex].value;
var exerciseText = exerciseElem.options[exerciseElem.selectedIndex].text;
var caloriesCode = genderValue + goalValue;
var caloriesAllowed;
var completeExerciseCodes = genderValue + exerciseValue;
var calorieDeduction;
var totalCalories;
// Loop through the array and locate the code to get the maximum calories
for (var codeCount = 0; codeCount < maxCaloriesCodes.length; codeCount++) {
// Determine if the current code is the array
if (maxCaloriesCodes[codeCount] == caloriesCode) {
caloriesAllowed = maxCaloriesAllowed[codeCount];
}
}
totalCalories = (calories - calorieDeduction);
// Loop through my exercise arrays and locate codes for calorie deductions
for (var codeCount = 0; codeCount < exerciseCodes.length; codeCount++){
// Determine if the current code is in the array
if (exerciseCodes[codeCount] == completeExerciseCodes) {
calorieDeduction = exerciseCalories[codeCount];
}
}
console.log(totalCalories)
}
Except for loops, if-clauses or function calls, code is executed line by line from top to bottom. In the line where you execute totalCalories = (calories - calorieDeduction), neither calories nor calorieDeduction has a value. Or actually their value is undefined, which gives you NaN.

Solving Linear Equations & similar Algebra Problems with JavaScript

I'm new to JavaScript and I am trying to write a simple script that solves linear equations. So far my script solves linear equations that are plus and minus only such as "2x + 28 - 18x = 36 - 4x + 10". I want it to also be able to solve linear equations/algebra problems that contain multiplication and division such as "2x * 3x = 4 / 2x".
I kind of have an idea of what to do next but I think the script I have right now maybe overly complex and it's only going to make it more complicated to add the multiplication and division.
Below is my script. I'm hoping for a few pointers on how I could improve and simplify what I already have and what the best way to add multiplication and division?
My script on JS Bin: http://jsbin.com/ufekug/1/edit
My script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Problem Solver</title>
<script>
window.onload = function() {
// Total Xs on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideXTotal = 0; // 5
var rightSideXTotal = 0; // -2
// Total integers on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideIntTotal = 0; // 2
var rightSideIntTotal = 0; // 10
// Enter a math problem to solve
var problem = "5x + 2 = 10 - 2x";
// Remove all spaces in problem
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/\s/g,''); // 5x+2=10-2x
// Add + signs in front of all - signs
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/-/gi, "+-"); // 5x+2=10+-2x
// Split problem into left and right sides
// Example problem: 5x + 2 = 10 - 2x
var problemArray = problem.split("=");
var problemLeftSide = problemArray[0]; // 5x+2
var problemRightSide = problemArray[1]; // 10+-2x
// Split values on each side into an array
var problemLeftSideValues = problemLeftSide.split("+");
var problemRightSideValues = problemRightSide.split("+");
// Go through the left side values and add them up
for (var i = 0; i < problemLeftSideValues.length; i++) {
// Current value
var currentValue = problemLeftSideValues[i];
// Length of current value
var currentValueLength = currentValue.length;
if (currentValue.charAt(currentValueLength - 1) == "x") { //Check if current value is a X value
// Remove X from end of current value
currentValue = currentValue.split("x");
// Add to total Xs on left side
leftSideXTotal = Number(leftSideXTotal) + Number(currentValue[0]);
} else {
// Add to total integers on left side
leftSideIntTotal = Number(leftSideIntTotal) + Number(problemLeftSideValues[i]);
}
}
// Go through the right side values and add them up
for (var i = 0; i < problemRightSideValues.length; i++) {
// Current value
var currentValue = problemRightSideValues[i];
// Length of current value
var currentValueLength = currentValue.length;
if (currentValue.charAt(currentValueLength - 1) == "x") { //Check if current value is a X value
// Remove X from end of current value
currentValue = currentValue.split("x");
// Add to total Xs on right side
rightSideXTotal = Number(rightSideXTotal) + Number(currentValue[0]);
} else {
// Add to total integers on right side
rightSideIntTotal = Number(rightSideIntTotal) + Number(problemRightSideValues[i]);
}
}
// Compute
var totalXs = (leftSideXTotal - rightSideXTotal)
var totalIntegers = (rightSideIntTotal - leftSideIntTotal)
var solution = (totalIntegers / totalXs)
// Display solution
document.getElementById("divSolution").innerText = solution;
}
</script>
</head>
<body>
<div id="divSolution"></div>
</body>
</html>
You need to write (or use) an operator-precedence parser.
The idea is to turn the equation into a tree, e.g.
x + 3 = 3x - 2
Is really the structure
=
/ \
+ -
/ \ / \
x 3 * 2
/ \
3 x
Where each operator describes an operation between two "branches" of the tree. Using a javascript object it shouldn't be difficult to create the structure:
function tree(lterm,op,rterm) {
t.operator = op;
t.left = lterm;
t.right = rterm;
return t;
}
expression = tree("x", "/", tree("x","+",3) ); // x / (x+3)
Then by manipulating the tree you can resolve the equation, or carry out calculations. To evaluate an expression (with no unknowns), you run through the tree starting at the terminals, and upwards from intersection to intersection. You can replace a section of the tree with a result, or annotate it with a result - add a result variable to the tree object.
Here are some useful methods to include in a tree class:
getLeft
getRight
prettyPrint
evaluate
evaluate("x",5) // x=5, now evaluate
...
It's not just linear operations that can be "parsed" this way. Better parsers will have a list of operators that includes =*/+- but also unary operators: - ( ) sin cos...
I haven't used an operator-precedence parser in javascript, but some must exist prewritten. Surely a kind soul on this site will add a good link or two to my answer.
BTW, the tree approach has many applications. In a spreadsheet:
A2 = A1+B1
In a boolean solver:
A = not (B or C)
C = true
In XML parsing:
<main>
<part>A</part>
<part>B</part>
</main>
I have defined two functions:
getTotalX() : It will give you the count of x for any input string.
getTotalScalars() : It will give you the total of scalars (numbers).
And finally, your updated code (it still does only addition and subtraction):
<script>
window.onload = function() {
// Total Xs on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideXTotal = 0; // 5
var rightSideXTotal = 0; // -2
// Total integers on each side of equation
// Example problem: 5x + 2 = 10 - 2x
var leftSideIntTotal = 0; // 2
var rightSideIntTotal = 0; // 10
// Enter a math problem to solve
var problem = "5x + 2 = 10 - 2x";
// Remove all spaces in problem
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/\s/g,''); // 5x+2=10-2x
// Add + signs in front of all - signs
// Example problem: 5x + 2 = 10 - 2x
problem = problem.replace(/-/gi, "+-"); // 5x+2=10+-2x
// Split problem into left and right sides
// Example problem: 5x + 2 = 10 - 2x
var problemArray = problem.split("=");
var problemLeftSide = problemArray[0]; // 5x+2
var problemRightSide = problemArray[1]; // 10+-2x
leftSideXTotal = getTotalX(problemLeftSide);
leftSideIntTotal = getTotalScalars(problemLeftSide);
rightSideXTotal = getTotalX(problemRightSide);
rightSideIntTotal = getTotalScalars(problemRightSide);
// Compute
var totalXs = (leftSideXTotal - rightSideXTotal)
var totalIntegers = (rightSideIntTotal - leftSideIntTotal)
var solution = (totalIntegers / totalXs)
// Display solution
document.getElementById("divSolution").innerText = solution;
// Find the total number of X in the string
function getTotalX(data) {
data = data.replace(/\s/g,'');
xCount = 0;
if(data.indexOf('x') != -1) {
if (data.indexOf('+') != -1) {
data = data.split('+');
for(var i = 0; i < data.length; i++) {
xCount += getTotalX(data[i]);
}
} else if (data.indexOf('-') != -1) {
data = data.split('-');
// Single negative
if(data[0] == "") {
xCount -= getTotalX(data[1]);
} else {
xCount += getTotalX(data[0]);
for(var i = 1; i < data.length; i++) {
xCount -= getTotalX(data[i]);
}
}
} else {
xCount = parseInt(data.split('x')[0]);
}
}
return xCount;
}
// Find the total of scalars
function getTotalScalars(data) {
data = data.replace(/\s/g,'');
intCount = 0;
if (data.indexOf('+') != -1) {
data = data.split('+');
for(var i = 0; i < data.length; i++) {
intCount += getTotalScalars(data[i]);
}
} else if (data.indexOf('-') != -1) {
data = data.split('-');
// Single negative
if(data[0] == "") {
intCount -= getTotalScalars(data[1]);
} else {
intCount += getTotalScalars(data[0]);
for(var i = 1; i < data.length; i++) {
intCount -= getTotalScalars(data[i]);
}
}
} else {
if(data.indexOf('x') == -1) {
intCount = parseInt(data.split('x')[0]);
} else {
intCount = 0;
}
}
return intCount;
}
}
</script>

Random Number with javascript or jquery

I am trying to make a script to pick random number between two numbers . but it picks same number sometimes. i donot want to repeat same number until array is finished .
Here is my code
$(document).ready(function () {
abc();
test = array();
function abc() {
res = randomXToY(1, 10, 0);
$('#img' + res).fadeTo(1200, 1);
//$(this).addClass('activeImg');
//});
setTimeout(function () {
removeClassImg(res)
}, 3000);
}
function removeClassImg(res) {
$('#img' + res).fadeTo(1200, 0.1);
//$('#img' + res).removeClass('activeImg');
abc();
}
function randomXToY(minVal, maxVal, floatVal) {
var randVal = minVal + (Math.random() * (maxVal - minVal));
return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}
});
Does Anybody have idea about this ...
You'll have to maintain a list of numbers that have already been generated, and check against this list. Re-generate a new number if you find a dupe.
If you do not want the random numbers repeating themselves you have to keep track of the some way.
If you have the range you are dealing with is relatively small, you can create an array with all possible results and simply randomly pick out of it.
function Randomizer(minVal, maxVal, floatVal){
var possible_results = []; // for larger arrays you can build this using a loop of course
var randomization_array = [];
var count = minVal;
var incrementor = floatVal || 1; // set the distance between possible values (if floatVal equals 0 we round to 1)
while (count <= maxVal) {
possible_results.push(count);
count += incrementor;
}
this.run = function(){
// if randomization_array is empty set posssible results into it
randomization_array = randomization_array.length ? randomization_array : $.merge(randomization_array, possible_results);
// pick a random element within the array
var rand = Math.floor(Math.random()*randomization_array.length);
// return the relevant element
return randomization_array.splice(rand,1)[0];
}
}
and in order to use it (it creates a specialized object for each possible range):
rand = new Randomizer(1,10,0);
rand.run();
note that this approach does not work well for very large ranges

Categories

Resources