I have a problem with the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Q3</title>
<script type="text/javascript">
function showvar(x) {
let sum = 0;
let ssq=0;
let N = x.length;
for (let i = 0; i < x.length; i++) {
sum = sum + x[i];
ssq+=x[i]*x[i];
}
let variance=(ssq-sum*sum/N)/(N-1)
return variance;
}
function showsd(x) {
let sum = 0;
let ssq=0;
let N = x.length;
for (let i = 0; i < x.length; i++) {
sum = sum + x[i];
ssq+=x[i]*x[i];
}
let variance=(ssq-sum*sum/N)/(N-1)
let sd=Math.sqrt(variance)
return sd;
}
function display() {
let numbers = document.getElementById("numbers").value.split(" ");
for (let i = 0; i < numbers.length; i++) {
numbers[i] = parseFloat(numbers[i]);
}
let v = showvar(numbers);
let sd = showsd(numbers);
document.getElementById("display").innerHTML = "variance = " + v;
document.getElementById("display").innerHTML = "Standard deviation = " + sd;
}
</script>
</head>
<body>
<p>
<br><br>
</p>
<input type="text" id="numbers">
<select>
<option>Standard deviation</option>
<option>variance</option>
</select>
<button type="button" onclick="display()">Calculate</button>
<p id="display">answer goes here</p>
</body>
</html>
I need to make it so that the paragraph will display the correct value based on the option that is selected. So, for example, if I put in some numbers and choose variance, then it will show me the value for variance. I currently just have code for each different option, but I need to somehow put it together. Any help is greatly appreciated.
Update your display function to add an if condition:
function display() {
let numbers = document.getElementById("numbers").value.split(" ");
for (let i = 0; i < numbers.length; i++) {
numbers[i] = parseFloat(numbers[i]);
}
if(document.getElementById("options").value === "variance") {
document.getElementById("display").innerHTML = "variance = " + showvar(numbers);
} else {
document.getElementById("display").innerHTML = "Standard deviation = " + showsd(numbers);
}
}
Also add an id to the select tag:
<select id="options">
<option>Standard deviation</option>
<option>variance</option>
</select>
Related
The order of the numbers in my box is as follows:
function boxNumbers(){
let boxes = document.querySelectorAll('.box')
boxes.forEach((box,i)=>{
if(String(i).length==1 || (String(i).length==2 && Number(String(i)[0]))%2==0){
//box.innerHTML = `${100-i}, i=${i}`
box.innerHTML = 100-i
}
else{
box.innerHTML = String(Number(`${9-Number(String(i)[0])}${String(i)[1]}`)+ 1)
}
})
}
how can I change it to look like this:
You can use this:
function boxNumbers() {
let boxes = document.querySelectorAll('.box');
let n = Math.sqrt(boxes.length);
[...boxes].reverse().forEach((box, i) => {
box.textContent = i % (n * 2) < n ? i + 1 : i + n - 2*(i % n);
})
}
With the assignment to n you make it a bit more generic -- still assuming your table is square. By reversing the iteration, you eliminate the need for the 100- subtraction. What remains is a formula that detects whether we're on a row with a reverse sequence or not, and adapts the number accordingly. The number "1" will always be in the bottom-right corner:
function boxNumbers() {
let boxes = document.querySelectorAll('.box');
let n = Math.sqrt(boxes.length);
[...boxes].reverse().forEach((box, i) => {
box.textContent = i % (n * 2) < n ? i + 1 : i + n - 2*(i % n);
})
}
// Utility to create the table
function fillTable(table, n) {
for (let i = 0; i < n; i++) {
let row = table.insertRow();
for (let j = 0; j < n; j++) {
let cell = row.insertCell();
cell.className = "box";
}
}
}
// Example run with n=5. Adapt as needed
let n = 5
fillTable(document.querySelector('table'), n);
boxNumbers();
table { border-collapse: collapse }
td { border: 1px solid ; width: 20px; height: 20px; text-align: center }
<table></table>
Here is a function which builds a bi-dimensional array and appends it as a table (row/col) to a dom element. You can adapt it to your template as you wish.
Works with any base number, yours is 5
function buildMatrix(baseNumber){
var flip = false;
var countDownNumber = baseNumber * baseNumber;
var currNumber = countDownNumber;
var matrix = "";
for(i = 0; i < baseNumber; i++) {
if(i !== 0){
currNumber = (flip)? countDownNumber + 1 - baseNumber : countDownNumber;
}
matrix += "<tr>";
for(j = 0; j < baseNumber; j++){
matrix += "<td>" + currNumber + "</td>";
// depending on the direction (flip) we increment or decrement
(flip)? currNumber++ : currNumber--;
countDownNumber--;
}
// change direction at the end of a row
flip = !flip;
matrix += "</tr>";
}
return matrix;
}
var baseSquareNumber = 11; // here you put 5
var matrixHtml = buildMatrix(baseSquareNumber);
document.getElementById("matrix").innerHTML = matrixHtml;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="matrix">
</table>
</body>
</html>
This function is freezing my page.
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
}
However, when I remove this it runs just fine.
modeArr.length = array.length;
modeCounter.length = array.length;
Here is all of my code:
<html>
<head>
</head>
<body>
<p> Please enter a series of numbers, each separated by a new line.<br><p>
<textarea id="myTextArea" rows = "7" cols = "50"></textarea><br>
<button onclick="processData()">Done</button>
<p id = "mean"></p>
<p id = "median"></p>
<p id = "count"></p>
<p id = "summation"></p>
<p id = "mode"></p>
<p id = "variance"></p>
<p id = "sd"></p>
<script type = "text/javascript">
var mean = 0;
var median = 0;
var count = length;
var mode = 0;
var variance = 0;
var standard_deviation = 0;
var meanOutput = document.getElementById('mean');
var medianOutput = document.getElementById('median');
var modeOutput = document.getElementById('mode');
var countOutput = document.getElementById('count');
var summationOutput = document.getElementById('summation');
var varianceOutput = document.getElementById('variance');
var sdOutput = document.getElementById('sd');
function processData()
{
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
var sum = findSum(arrayOfLines);
findMean(arrayOfLines, sum);
findMedian(arrayOfLines);
findMode(arrayOfLines);
findVariance(arrayOfLines);
findStandardDeviation(arrayOfLines);
findVariance(arrayOfLines);
}
function findSum (array)
{
var count = array.length;
var sum = 0;
for (var a = 0; a < array.length; a++)
{
sum += parseInt(array[a]);
}
countOutput.innerHTML = "Count: " + array.length;
summationOutput.innerHTML = "Sum: " + JSON.stringify(sum);
return sum;
}
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
for (var a = 0; a < array.length; a++)
{
for (var b = 0; b < modeArr.length; b++)
{
if (modeArr[a] == modeArr[b])
{
modeCounter[a]++;
}
if (a == 0)
{
b--;
}
}
modeArr[a] = array[a];
}
modeOutput.innerHTML = "Mode: ";
}
function findMean (array, sum)
{
mean = sum/array.length;
meanOutput.innerHTML = "Mean: " + mean.toPrecision(2);
}
function findMedian (array)
{
for(var i=0; i < array.length; i++)
{
array[i] = +array[i];
}
var sortedArrayOfLines = array.sort(function(a, b){return a - b});
if (array.length % 2 == 1)
{
median = sortedArrayOfLines[((array.length - 1)/2)]
}
else
{
median = (sortedArrayOfLines[array.length/2] + sortedArrayOfLines[(array.length/2)+1])/2
}
medianOutput.innerHTML = "Median: " + median;
}
function findVariance (array)
{
var mean = mean(array);
return mean(array.map(function(num)
{
varianceOutput.innerHTML = Math.pow(num - mean, 2);
}));
}
function findStandardDeviation (array)
{
medianOutput.innerHTML = Math.sqrt(variance(array));
}
</script>
</body>
</html>
So the issue isn't the length it's a infinite loop.
The problem is this bit of code
if (a == 0)
{
b--;
}
This is inside the following loop with b as the iterator. See below.
for (var b = 0; b < modeArr.length; b++)
a is set to zero by the outer loop. Thus a==0 is always true inside the inner loop. b will never increase only decrease. Thus this is a infinite loop because b will never be greater than modeArr.length.
So I would consider revising the function, below is a example of a possible candidate for a mode function:
Get the element with the highest occurrence in an array
I'm utilizing JSBin to write a block of JS code to accept an input string, then return each letter included in the string (removing duplicate letters and other characters), then counting how many times each letter was utilized in the string. I am trying to integrate regex for additional practice.
The code I've written is not removing duplicates, nor is it properly counting the frequency of each character. Can somebody please tell me what I have done wrong?
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="input"></input>
<button onclick="count()">Count letters</button>
<br>
<br>
<div id="output">Result</div>
</body>
</html>
Here is the JS:
function count() {
var x = document.getElementById("input").value.toString();
var y = "";
var z = [];
//Removal of white spaces and other characters.
x = x.replace(/[^a-z]/gi,"");
//Elimination of duplicate letters.
for (var i = 0; i < x.length; i++) {
if (/x.charAt(i)/i.test(y) === false) {
y += x.charAt(i);
}
}
//Count how many of each letter exists within the input string.
for(var i = 0; i < y.length; i++) {
for (var j = 0; j < y.length; j++) {
var freq = 0;
if (y.charAt(i) == y.charAt(j)) {
freq += 1;
}
z.push(freq);
}
}
//Write result to HTML document.
for (var i = 0; i < y.length; i++) {
document.write(y.charAt(i));
document.write(", ");
document.write(z[i]);
document.write("<br>");
}
}
Thank you so much for your help!
You are thinking too complicated. Just iterate through normalized string, and count letters:
window.count = function() {
var input = document.getElementById("input").value.toString();
var result = {};
input = input.replace(/[^a-z]/gi,"");
var letters = input.split('');
for(index in letters) {
result[letters[index]] = result[letters[index]] +1 || 1;
}
document.querySelector('#output').innerHTML = JSON.stringify(result);
}
demo fiddle
You can do it in a single replace function. This is an example.
function getFreq(str){
var freq={};//an object to fill
/*var tmp = result not required*/ str.toLowerCase()
.replace(/[a-z]/ig, function(match /*that is [a-z]*/){
freq[match] = (freq[match] || 0) + 1;//fill object
return match;//do not change str
});
console.log(JSON.stringify(freq));
return freq;
}
<input type="text" onchange="getFreq(this.value);" />
I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview
I have a bit of an issue at the moment that I am hoping one of you can help me with. I have tried several things, and I just can't get it. I am trying to print a triangle of asterisks using JavaScript. The program is to ask the user for the amount of rows, and then the direction. I haven't even started with the direction yet because I can't get the rows to work. Odd thing is that I can get it to print out the triangle hard-coding the function call.
This is the JS file:
function myTriangle(){
var result = "";
var totalRows = document.getElementById('rows').value;
var direction = document.getElementById('UpOrDown').value;
for (var i = 1; i <= totalRows; i++){
document.writeln("count");
for (var j = 1; j <= 1; j++)
{
result += "*";
}
result += "<br/>";
}
return result;
}
var answer = myTriangle();
document.getElementById('myDiv').innerHTML = answer;
This is the HTML file:
<!DOCTYPE html>
<head>
<title>Lab 2</title>
<script src="scripts.js", "div.js"></script>
</head>
<body>
<form name="myForm">
<fieldset>
<legend>Input Fields</legend>
rows: <input type="text" id="rows" /><br>
direction: <input type="text" id="UpOrDown" /><br>
press: <input type="button" value="GO!" id="myButton"
onclick="myTriangle();"/>
</fieldset>
</form>
<div id="myDiv">
</div>
</body>
The output will be something like this:
*
**
***
****
*****
Generally there are four types of triangle -
1.)* 2.) *** 3.) * 4.) ***
** ** ** **
*** * *** *
Code for 1 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 2 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 3 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 4 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
To print asterisk in document rather than console -
document.getElementById('anyElement').innerHTML+=ast[i] + '<br />';
document.writeln will completely wipe the page unless it's called while the page is loading.
Therefore it will destroy myDiv, causing the getElementById to fail.
Furthermore, I'm not sure what you're trying to achieve with that <script> tag, but it looks like you need two of them.
EDIT: Oh, and this: for (var j = 1; j <= 1; j++) will only ever iterate once.
EDIT 2: Here's my implementation of a solution.
This isn't a valid script tag.
<script src="scripts.js", "div.js"></script>
You need to break it up into two tags:
<script src="scripts.js"></script>
<script src="div.js"></script>
This is my solution, it uses es2015 .replace() but there is a nice
polyfill for es5 as well here:
var output = document.getElementById('output');
function triangle (size) {
for (var i = 1; i <= size; i++) {
output.innerHTML += '*'.repeat(i) + '<br>';
}
}
triangle(2);
This is a solution in ES3/5
var output = document.getElementById('output');
function triangle(size) {
var allLines = '';
for (var i = 1; i <= size; i++) {
var oneLine = createLine(i);
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 1; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
output.innerHTML += triangle(3);
<div id='output'></div>