Problem with the rectangle method in javascript - javascript

I am a beginner in javascript and have a problem with my code. It says NaN whereas I've been checking for a long time and haven't found the problem. Thanks for having a look at it !Here is my code
const a = -10;
const b = 10;
let X = [];
let p = 20;
for (let i = 0; i <= p; i++) {
X.push(a + i * ((b - a) / p));
}
function maFonction(antecedent) {
return antecedent ** 2;
}
function methRectangles() {
let aireTotale = 0;
for (let i = 0; i <= p; i++) {
aireTotale = aireTotale + maFonction(X[i]) * (X[i + 1] - X[i]);
}
return aireTotale;
}
methRectangles();
console.log(methRectangles());

Related

Getting a type error: cannot read properties of undefined (reading 'value) when implementing quick sort in javascript

Please excuse the bad structure of the program. I'm a newbie programmer trying my first project in creating a sorting visualizer. I was able to implement bubble sort, but when I came around to trying to see if quick sort worked with the values in the child divs, I keep getting this error. My partition function correctly changes the value in each div, but my quick sort function shoots this error out. What's going on?
return Math.floor(Math.random() * (max - min) + min);
}
function rand_num_height(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
//Visuals
let speed = 500;
let c = 0;
let delay = 10000 / (Math.floor(10 / 10) * speed);
let p = "#75DF5B";
let p1 = "#63D7D8";
let p2 = "#008FF9";
let sorted = "#A946DA";
let p3 = "#E9EC13";
let p4 = "#F50101";
const anim = (bar, height, color) => {
setTimeout(() => {
bar.style.height = height + "px";
bar.style.backgroundColor = color;
}, (c += delay + 50));
};
const bar_container = document.getElementById("bar-container");
let children = bar_container.children;
const generate = document.getElementById("generate");
const btn = document.getElementById("sort-btn");
const reset = document.getElementById("reset");
generate.addEventListener("click", () => {
generateNewArray(rand_num_bars(10, 15));
});
function generateNewArray(rand_num_bars) {
bar_container.innerHTML = "";
//Inserting child bars into parent bar container, using rand_num function to generate # of bars
for (let i = 0; i < rand_num_bars; i++) {
document.getElementById(
"bar-container"
).innerHTML += `<div id = 'indiv_bar'></div>`;
}
//Randomizing the height for each child bar
for (i = 0; i < children.length; i++) {
var rand_height = rand_num_height(100, 500);
children[i].style.height = `${rand_height}px`;
//Setting values of each element in bar_con array to the current child height to use for sorting later
children[i].value = rand_height;
}
}
function disableBtn() {
//Prevent buttons from triggering an event
generate.style.pointerEvents = "none";
btn.style.pointerEvents = "none";
//Styling the elements to visually show user buttons are disabled
generate.style.color = "#FF0000";
btn.style.color = "#FF0000";
}
//Bubble Sort Algorithm
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - i - 1; j++) {
anim(arr[j], arr[j].value, p1);
anim(arr[j + 1], arr[j + 1].value, p2);
if (arr[j].value > arr[j + 1].value) {
[arr[j].value, arr[j + 1].value] = [arr[j + 1].value, arr[j].value];
anim(arr[j], arr[j].value, p2);
anim(arr[j + 1], arr[j + 1].value, p1);
}
anim(arr[j], arr[j].value, p);
anim(arr[j + 1], arr[j + 1].value, p);
}
anim(arr[n - i - 1], arr[n - i - 1].value, sorted);
}
sortState = true;
c = 0;
}
//Quick Sort Algorithm
function partition(arr, low, high) {
let i = low;
let j = high;
pivotEl = arr[low].value;
do {
do {
i++;
} while (arr[i].value <= pivotEl);
do {
j--;
} while (arr[j].value > pivotEl);
if (i <= j) {
[arr[i].value, arr[j].value] = [arr[j].value, arr[i].value];
}
} while (i < j);
[arr[low].value, arr[j].value] = [arr[j].value, arr[low].value];
return j;
}
function quickSort(arr, low, high) {
var j;
if (low < high) {
j = partition(arr, low, high);
quickSort(arr, low, j - 1);
quickSort(arr, j + 1, high);
}
}
btn.addEventListener("click", () => {
disableBtn();
quickSort(children, 0, children.length - 1);
});

Extract last ","

This is my code
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join();
}
basicIO.write(convertToCurr(input));
context.log.INFO("log data");
}
These are my outputs
{"output":"R 1,000,000,.00","log":["log data"]}
{"output":"R 1,000,.00","log":["log data"]}
I need to exctract the last "," so that the amounts make sense
The most straightforward solution is to perform a String.prototype.replace() on the final join().
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
if (z == 0) {
a = (x / 3) - 1;
}
else {
a = (x / 3);
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
return vals.join().replace(',.', '.');
}
console.log(convertToCurr(10000.75));
console.log(convertToCurr(10.01));
console.log(convertToCurr(1000));
console.log(convertToCurr(7002344));
It should be noted that replace() only replaces a single instance of the substring you provide it in the input string, but this doesn't matter here since ,. only appears in your output string one time.
function convertToCurr(value) {
var x = value.toString().length;
var z = x % 3;
var a = 0;
var combinedString; // holds string value after join
if (z == 0) {
a = x / 3 - 1;
} else {
a = x / 3;
}
var last = 0;
var vals = [];
var i;
for (i = 1; i <= a; i++) {
steps = 3;
start = x - steps * i;
end = start + steps;
last = end - steps;
vals.unshift(value.toString().slice(start, end));
}
vals.unshift("R " + value.toString().slice(0, last));
combinedString = vals.join(); // join array into string
return combinedString.replace(",.", "."); // replace ,. with .
}
console.log(convertToCurr(50000000.15));

Issues with understanding Javascript yarn pattern program

I came across the Javascript YarnPattern program from Stanford's CS106AX. However, as I was going through the code, I have difficulty understanding some lines.
In the main function YarnPattern(), I don't quite understand the bold chunk written between the stars " ** ". I'm not quite sure what it means when the variables are initialised with thisPeg = 0 and nextPeg = -1.
Also, I'm not quite sure about the line "nextPeg = (thisPeg + DELTA) % pegs.length". I was wondering how this line of code can help reaching a suitable peg's index position.
It would be great if someone can provide a clear explanation with regards to these lines of code. Your help is much appreciated.
// Constants
const GWINDOW_WIDTH = 1000;
const GWINDOW_HEIGHT = 625;
const N_ACROSS = 80;
const N_DOWN = 50;
const DELTA = 113;
// main function
function YarnPattern() {
let gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT);
let pegs = createPegArray(GWINDOW_WIDTH, GWINDOW_HEIGHT, N_ACROSS, N_DOWN);
**let thisPeg = 0;
let nextPeg = -1;
while (thisPeg !== 0 || nextPeg === -1) {
nextPeg = (thisPeg + DELTA) % pegs.length;
let p0 = pegs[thisPeg];
let p1 = pegs[nextPeg];
let line = GLine(p0.x, p0.y, p1.x, p1.y);**
line.setColor("Magenta");
gw.add(line);
thisPeg = nextPeg;
}
}
function createPegArray(width, height, nAcross, nDown) {
let dx = width / nAcross;
let dy = height / nDown;
let pegs = [ ];
for (let i = 0; i < nAcross; i++) {
pegs.push(Point(i * dx, 0));
}
for (let i = 0; i < nDown; i++) {
pegs.push(Point(nAcross * dx, i * dy));
}
for (let i = nAcross; i > 0; i--) {
pegs.push(Point(i * dx, nDown * dy));
}
for (let i = nDown; i > 0; i--) {
pegs.push(Point(0, i * dy));
}
return pegs;
}
function Point(x, y) {
if (x === undefined) {
x = 0;
y = 0;
}
return { x: x, y: y };
}

I'm trying to raise numbers to their consecutive powers and my code isn't working

https://codepen.io/aholston/pen/ZJbrjd
The codepen link has commented code as well as actual instructions in HTML
Otherwise.... what I ultimately have to do is write a function that takes two params(a and b) and takes all the numbers between those two params (a-b) and put every number that can be added to the consecutive fowers and be equal to that number into a new array. Ex: 89 = 8^1 + 9^2 = 89 or 135 = 1^1 + 3^2 + 5^3 = 135
function sumDigPow(a, b) {
// Your code here
var numbers = [];
var checkNum = [];
var finalNum = [];
var total = 0;
for (var i = 1; i <= b; i++) {
if (i >= a && i <= b) {
numbers.push(i);
}
}
for (var x = 0; x < numbers.length; x++) {
var checkNum = numbers[x].toString().split('');
if (checkNum.length == 1) {
var together = parseInt(checkNum);
finalNum.push(together);
} else if (checkNum.length > 1) {
var together = checkNum.join('');
var togNumber = parseInt(together);
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
try this:
function listnum(a, b) {
var finalNum = [];
for (var i = a; i <= b; i++) {
var x = i;
var y = i;
var tot = 0;
j = i.toString().length;
while (y) {
tot += Math.pow((y%10), j--);
y = Math.floor(y/10);
}
if (tot == x)
finalNum.push(i);
}
return finalNum;
}
console.log(listnum(1, 200));
Okay, after debugging this is what I learned.
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);
}
}
}
return finalNum;
}
Everytime this loop happened, I neglected to reset the 'total' variable back to 0. So I was never getting the right answer for my Math.pow() because my answer was always adding to the previous value of total. In order to fix this, I added var total = 0; after i decided whether or not to push 'togNumber' into 'finalNum.' So my code looks like this..
for (var y = checkNum.length; y > 0; y--) {
total += Math.pow(checkNum[y - 1], y);
}
if (total == togNumber) {
finalNum.push(togNumber);}
}
var total = 0;
}
return finalNum;
}

Got 90% of the JavaScript code - can't figure out the rest

So I am trying to model Gram-Schmidt for any size N×N matrix, and I have officially hit a roadblock I can't get past. I know it's a matter of looping this correctly, but I can't figure out what the problem is. Remember I do not want to just pass in a 3×3 matrix, but any size N×N.
The course notes QR Decomposition with Gram-Schmidt explains exactly what I want to do. Very simple calculation by the way. In the course notes ||u|| means that it is the sum of the square of the elements, so sqrt(x12 + x22 + x32 + .... + xn2).
The multiplication symbol is actually the dot product.
The code I wrote so far is listed below. What is wrong with it?
function qrProjection(arr) {
var qProjected = [];
var tempArray = [];
var aTemp = arr;
var uTemp = new Array(arr.length);
var uSquareSqrt = new Array(arr.length);
var eTemp = [];
var sum = 0;
var sumOfSquares = 0;
var breakCondition = 0;
var secondBreakCondition = 0;
var iterationCounter = 0;
//Build uTemp Array
for (i = 0; i < arr.length; i++) {
uTemp[i] = new Array(arr[i].length);
}
for (i = 0; i < arr.length; i++) {
eTemp[i] = new Array(arr[i].length);
}
uTemp[0] = aTemp[0];
for (j = 0; j <= arr.length; j++) {
for (l = 0; l < arr[j].length; l++) {
if (breakCondition == 1) break;
sumOfSquares = Math.pow(uTemp[j][l], 2) + sumOfSquares;
}
if (breakCondition == 0) {
uSquareSqrt[j] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
}
for (i = 0; i < arr[j].length; i++) {
if (breakCondition == 1) break;
eTemp[j][i] = (1 / (uSquareSqrt[j])) * (uTemp[j][i]);
}
breakCondition = 1;
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
matrixDotProduct = aTemp[j + 1][m] * eTemp[j][m] + matrixDotProduct;
}
}
else {
for (m = 0; m < arr[j].length; m++) {
for (s = 0; s <= iterationCounter; s++) {
matrixDotProduct = aTemp[j + 1][s] * eTemp[m][s] + matrixDotProduct;
}
for (t = 0; t < arr[j].length; t++) {
uTemp[j + 1][t] = aTemp[j + 1][t] - eTemp[j][t] * matrixDotProduct;
}
}
}
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
uTemp[j + 1][m] = aTemp[j + 1][m] - eTemp[j][m] * matrixDotProduct;
}
}
matrixDotProduct = 0;
for (l = 0; l < arr[j].length; l++) {
sumOfSquares = Math.pow(uTemp[j + 1][l], 2) + sumOfSquares;
}
uSquareSqrt[j + 1] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
for (i = 0; i < arr[j].length; i++) {
eTemp[j + 1][i] = (1 / (uSquareSqrt[j + 1])) * (uTemp[j + 1][i]);
}
iterationCounter++;
}
qProjected = eTemp;
return qProjected;
}
I must apologize that instead of tweaking your code, I wrote my own from scratch:
/* Main function of interest */
// Each entry of a matrix object represents a column
function gramSchmidt(matrixA, n) {
var totalVectors = matrixA.length;
for (var i = 0; i < totalVectors; i++) {
var tempVector = matrixA[i];
for (var j = 0; j < i; j++) {
var dotProd = dot(matrixA[i], matrixA[j], n);
var toSubtract = multiply(dotProd, matrixA[j], n);
tempVector = subtract(tempVector, toSubtract, n);
}
var nrm = norm(tempVector, n);
matrixA[i] = multiply(1 / nrm, tempVector, n);
}
}
/*
* Example usage:
* var myMatrix = [[1,0,0],[2,3,0],[5,4,7]];
* gramSchmidt(myMatrix, 3);
* ==> myMatrix now equals [[1,0,0],[0,1,0],[0,0,1]]
* 3 here equals the number of dimensions per vector
*/
/* Simple vector arithmetic */
function subtract(vectorX, vectorY, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = vectorX[i] - vectorY[i];
return result;
}
function multiply(scalarC, vectorX, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = scalarC * vectorX[i];
return result;
}
function dot(vectorX, vectorY, n) {
var sum = 0;
for (var i = 0; i < n; i++)
sum += vectorX[i] * vectorY[i];
return sum;
}
function norm(vectorX, n) {
return Math.sqrt(dot(vectorX, vectorX, n));
}
Note that the algorithm above computes the Gram-Schmidt orthogonalization, which is the matrix [e1 | e2 | ... | en], not the QR factorization!

Categories