Standard Deviation Calculator in JavaScript - javascript

I made a standard deviation calculator but am not sure where I am going wrong in the calculation. I am trying to learn how to manipulate arrays so everything probably takes the long route in what I am doing.
What am I doing wrong?
JavaScript:
myArray = [];
squaredArray = [];
var theTotal;
var average;
var theSquaredTotal;
var meanOfSquaredArray;
var squaredAverage;
var standardDeviation;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " +
theTotal);
average = parseFloat((theTotal /
myArray.length));
$('#average').html("");
$('#average').html(
"The mean value is: " + average
);
for (var i = 0; i < myArray.length; i++) {
squaredArray.push(myArray[i] -
average);
};
console.log(
"the subtracted squared away array is: " +
squaredArray);
for (var i = 0; i < myArray.length; i++) {
squaredArray[i] = Math.pow(
squaredArray[i], 2);
};
console.log(
"the squared away array is: " +
squaredArray);
for (var i = 0; i < squaredArray.length; i++) {
squaredTotal = 0;
squaredTotal = squaredTotal +
squaredArray[i]
};
console.log("The squared sum is: " +
squaredTotal);
//meanOfSquaredArray =
squaredAverage = parseFloat((
squaredTotal / squaredArray
.length));
console.log("The squared average is: " +
squaredAverage);
standardDeviation = Math.sqrt(
squaredAverage);
console.log(
"The standard deviation is: " +
standardDeviation);
});
});
});
CSS:
#wrapper {
width: 80%;
margin: 0 auto;
border: 1px solid #000;
border-radius: 5px 5px 5px 5px;
box-shadow: 5px 5px 10px 3px #000;
padding: 10px;
}
h1 {
text-align: center;
color: orange;
text-shadow: 1px 1px blue;
}
#intake {
text-align: center;
}
HTML:
<div id="wrapper">
<div id="content">
<h1>Standard Deviation</h1>
<div id="intake">
<input id="input" type="text"> <button id="inTakeButton">Push
to Array</button> <button id="showArray">Show Array</button>
<button id="doMath">Do Math</button>
</div>
<div id="middle">
<ul id="list"></ul>
<ul id="sortedList"></ul>
</div>
<div id="output">
<p id="sorted"></p>
<p id="sum"></p>
<p id="average"></p>
</div>
</div>
</div>
Fiddle here.

It´s quite simple mistake, you are doing
for (var i = 0; i < squaredArray.length; i++) {
squaredTotal = 0;
squaredTotal = squaredTotal + squaredArray[i]
};
So in each step, you are resetting squaredTotal to 0, which means when the loop ends, squaredTotal will be equal to the last value of the array. Fix is to put it outside the loop:
squaredTotal = 0;
for (var i = 0; i < squaredArray.length; i++) {
squaredTotal = squaredTotal + squaredArray[i]
};

You have nested two click events:
$('#showArray').on('click', function() {
//
$('#doMath').on('click', function() {
//
});
});
You should move the click event on #doMath out to stand alone so that it can run when you actually click that element.

Related

Why aren't numbers matching? They are absurdly higher than asked

I progressed in my code, but now for some reason the asked minimum and maximum numbers aren't matching!
I tried to fix some numbers adding for loops. But I think I only made it worse.
I made it on Dcoder(Phone)
var rndList = [];
var rndList2 = [];
function GD() {
var a = document.getElementById("MinS").value;
var b = document.getElementById("MaxS").value;
var c = document.getElementById("Min").value;
var d = document.getElementById("Max").value;
var e = document.getElementById("PrzNo").value;
r = [a, b, c, d, e];
return r;
}
var input = document.getElementsByClassName("o");
for (i = 0; i < input.length; i++) {
input[i].addEventListener("change", function() {
results = GD();
var a = results[0];
var b = (results[1] + 1);
var c = results[2];
var d = (results[3] + 1);
var e = results[4];
function raffle(MinS, MaxS, Min, Max, PrzNo) {
function getRndInt(min, max) {
return (Math.round(Math.random() * (max - min)) + min);
}
for (i = 0; i < PrzNo; i++) {
rndList.push(getRndInt(MinS, MaxS));
}
for (i = 0; i < PrzNo; i++) {
rndList2.push(getRndInt(Min, Max));
}
}
raffle(a, b, c, d, e);
for (i = 0; i < rndList.length; i++) {
while (rndList[i] >= b) {
rndList[i] = Math.round(rndList[i] / 10);
}
}
for (i = 0; i < rndList2.length; i++) {
while (rndList2[i] >= d) {
rndList2[i] = Math.round(rndList2[i] / 10);
}
}
for (i = 0; i < rndList.length; i++) {
if (rndList[i] == 0) {
rndList[i] = 1;
}
}
for (i = 0; i < rndList2.length; i++) {
if (rndList2[i] == 0) {
rndList2[i] = 1;
}
}
for (i = 0; i < rndList.length; i++) {
window.alert("Serial: " + rndList[i] + " y Number: " + rndList2[i]);
}
});
};
.center {
display: block;
text-align: center;
width: 50%;
border: 1px dotted #f00;
padding: 8px;
margin: auto;
}
<form action="Raffle.html" method="post" name="frm">
<p class="center"> Minimum Serial: <input class="center o" type="number" name="MinS" id="MinS"><br> Maximum Serial: <input class="center o" type="number" name="MaxS" id="MaxS"><br> Minimum Number: <input class="center o" type="number" name="Min" Id="Min"><br> Maximum
Number: <input class="center o" type="number" name="Max" id="Max"><br> Amount of Prizes: <input class="center o" type="number" name="PrzNo" id="PrzNo"></p>
</form>
I hope you can find what's wrong. I have another question, do you know some app or web page that reorganize your code? For making it more beautiful.

Generate different text in every tile javascript

I have arrays of strings with names and surnames. I created username which consist of random name and random surname and I want to display different username in every generated tile. I tried to splite names and surnames and than add it do array and get random array index but it didn't work. Better solution would be to use my "username". Biggest problem is that I can't modify my getData() function - it always assign the same username to each tile.
function createGrid(x, y) {
for (var cols = 0; cols < x; cols++) {
for (var rows = 0; rows < y; rows++) {
console.log(namesArr)
console.log(x*y)
numberOfTiles = x*y;
var randonIndex = Math.floor(Math.random() * numberOfTiles);
// $(".usernameSpace").html(namesArr[randomIndex]);
//Doesn't work here
$('#container').append("<div class='grid'><div class = 'usernameSpace'></div></div>");
};
};
$('.grid').width(800 / x);
$('.grid').height(800 / x);
};
function refreshGrid() {
var x = $("#colsNumber")[0].value;
var y = $("#rowsNumber")[0].value;
$('.grid').remove();
createGrid(x, y);
};
function getData(count) {
var names = ["Michal ", "Jan ", "Katarzyna ", "Andrzej ", "Jozef ", "Bartek ", "Mikolaj ", "Tomasz ", "Julian ", "Brajan ", "Dzesika "];
var surnames = ["Noga ", "Kowalski ", "Nowak ", "Pazura ", "Duda ", "Komorowski ", "Tomczyk ", "Jozefowicz ", "Lechicki ", "Goldberg "];
result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
var name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
function textDisplay() {
var numberOfTiles = 12;
//for (i = 0; i <= numberOfTiles; i++) {
var data = getData(12);
//var username = "";
////////////////////////////////////////////////////////////////////
username = "";
$.each(data, function (i, { name, surname }) {
username += ` ${name} ${surname}`;
});
////////////////////////////////////////////////////////////////////
// }
namesToDisplay = "";
surnamesToDisplay = "";
$.each(data, function (i, { name }) {
namesToDisplay += `${name}`;
});
$.each(data, function (i, { surname }) {
surnamesToDisplay += `${surname}`;
});
console.log(username)
console.log(namesToDisplay)
console.log(surnamesToDisplay)
//$(".usernameSpace").html(username);
namesArr = namesToDisplay.split(" ");
console.log(namesArr)
$(".usernameSpace").html(namesArr[2]);
}
function AssignUsername(Class, content) {
var container = document.getElementsByClassName(Class);
$(container).html(content);
}
$(document).ready(function () {
$(".startBtn").click(function () {
refreshGrid();
textDisplay();
});
});
#container {
position: relative;
margin:auto;
height:800px;
width:800px;
}
.grid{
outline:5px solid white;
margin:0;
padding:0;
border:none;
background-color: #212121;
display:inline-block;
color: white;
}
.input{
width: 15%;
background-color: #757575;
font-size: 18px;
border: 3px;
height: 4%;
border-radius: 5px;
color: white;
}
html {
font-family: 'Arial';
}
.startBtn{
background-color: #4b4b4b;
border-radius: 10px;
color: white;
}
#textDisplay{
height:800px;
width:800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<head>
<link rel=stylesheet type="text/css" href="MetroUI 03'2018 basic.css">
<script src="jquery.js"></script>
<script src="MetroUI 03'2018 basic.js"></script>
</head>
<body onload="textDisplay()">
<p>
Give me width of grid:
</p>
<div>
<input class='input' id='colsNumber' type='number'>
</div>
<p>
Give me height of grid:
</p>
<div>
<input class='input' id='rowsNumber' type='number'>
</div>
<button class="startBtn">START!</button>
<div class='nameDisplay'></div>
<div class="Container"></div>
<div id = "container"></div>
</body>
</html>
In your code when you do:
$(".usernameSpace").html(namesArr[2]);
You are assigning all titles with that class to the same HTML values. Instead iterate through your titles and assign it a value based on your data variable:
$(".usernameSpace").each(function(idx){
$(this).html(data[idx].surname);
});
Although I'd recommend storing the names directly in the data attribute of the .usernameSpace elements as you create them. Then you could just use $(this).data("surname") when you iterate through your elements. That way will be more safer as well in the event that data and the number of .usernameSpace elements differs, along with that it will make the code simpler.
Here is a fiddle example of what I described above
function createGrid(x, y) {
for (var cols = 0; cols < x; cols++) {
for (var rows = 0; rows < y; rows++) {
console.log(namesArr)
console.log(x*y)
numberOfTiles = x*y;
var randonIndex = Math.floor(Math.random() * numberOfTiles);
// $(".usernameSpace").html(namesArr[randomIndex]);
//Doesn't work here
$('#container').append("<div class='grid'><div class = 'usernameSpace'></div></div>");
};
};
$('.grid').width(800 / x);
$('.grid').height(800 / x);
};
function refreshGrid() {
var x = $("#colsNumber")[0].value;
var y = $("#rowsNumber")[0].value;
$('.grid').remove();
createGrid(x, y);
};
function getData(count) {
var names = ["Michal ", "Jan ", "Katarzyna ", "Andrzej ", "Jozef ", "Bartek ", "Mikolaj ", "Tomasz ", "Julian ", "Brajan ", "Dzesika "];
var surnames = ["Noga ", "Kowalski ", "Nowak ", "Pazura ", "Duda ", "Komorowski ", "Tomczyk ", "Jozefowicz ", "Lechicki ", "Goldberg "];
result = [];
for (var i = 0; i < count; i++) {
var randomNameIndex = Math.floor(Math.random() * names.length);
var randomSurnameIndex = Math.floor(Math.random() * surnames.length);
var name = names[randomNameIndex];
var surname = surnames[randomSurnameIndex];
result.push({
name: name,
surname: surname
});
}
return result
}
function textDisplay() {
var numberOfTiles = 12;
//for (i = 0; i <= numberOfTiles; i++) {
var data = getData(12);
//var username = "";
////////////////////////////////////////////////////////////////////
username = [];
$.each(data, function (i, { name, surname }) {
username.push(` ${name} ${surname}`);
});
////////////////////////////////////////////////////////////////////
// }
namesToDisplay = "";
surnamesToDisplay = "";
$.each(data, function (i, { name }) {
namesToDisplay += `${name}`;
});
$.each(data, function (i, { surname }) {
surnamesToDisplay += `${surname}`;
});
console.log(username)
console.log(namesToDisplay)
console.log(surnamesToDisplay)
//$(".usernameSpace").html(username);
namesArr = namesToDisplay.split(" ");
console.log(namesArr)
$(".usernameSpace").each(function(idx){
$(this).html(username[idx]);
})
}
function AssignUsername(Class, content) {
var container = document.getElementsByClassName(Class);
$(container).html(content);
}
$(document).ready(function () {
$(".startBtn").click(function () {
refreshGrid();
textDisplay();
});
});
#container {
position: relative;
margin:auto;
height:800px;
width:800px;
}
.grid{
outline:5px solid white;
margin:0;
padding:0;
border:none;
background-color: #212121;
display:inline-block;
color: white;
}
.input{
width: 15%;
background-color: #757575;
font-size: 18px;
border: 3px;
height: 4%;
border-radius: 5px;
color: white;
}
html {
font-family: 'Arial';
}
.startBtn{
background-color: #4b4b4b;
border-radius: 10px;
color: white;
}
#textDisplay{
height:800px;
width:800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<head>
<link rel=stylesheet type="text/css" href="MetroUI 03'2018 basic.css">
<script src="jquery.js"></script>
<script src="MetroUI 03'2018 basic.js"></script>
</head>
<body onload="textDisplay()">
<p>
Give me width of grid:
</p>
<div>
<input class='input' id='colsNumber' type='number'>
</div>
<p>
Give me height of grid:
</p>
<div>
<input class='input' id='rowsNumber' type='number'>
</div>
<button class="startBtn">START!</button>
<div class='nameDisplay'></div>
<div class="Container"></div>
<div id = "container"></div>
</body>
</html>

Having issue on loading elements to each container

I am trying to not load more than 9 alert on each .content but in result I am packing every number in group of 9 items and eliminating any items less than 10!
For example if the random value is 8 then nothing will shows in the content or if the random number is 19 only two set of content displays
How can I fix the following demo?
var itemsNumber = Math.floor(Math.random() * 50) + 1;
console.log(itemsNumber);
var contents = $('.contents');
var element = $('<div class="content"></div>');
for (var i = 0, j = 0; i < itemsNumber; i++, j++) {
element.append('<div class="alert alert-success" role="alert"> Alert ' + i + '</div>');
if (j == 9) {
contents.append(element);
element = $('<div class="content"></div>');
j = -1;
}
}
.content {
background: khaki;
margin: 10px;
border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents text-center">
</div>
The problem is that you condition to append the content is based on j == 9, so if you have less than 9 items it will never be true and never append. You can add || i === itemsNumber - 1 to tell if you are at the end of all the items.
var itemsNumber = 8; //Math.floor(Math.random() * 50) + 1;
console.log(itemsNumber);
var contents = $('.contents');
var element = $('<div class="content"></div>');
for (var i = 0, j = 0; i < itemsNumber; i++, j++) {
element.append('<div class="alert alert-success" role="alert"> Alert ' + i + '</div>');
if (j === 9 || i === itemsNumber - 1) {
contents.append(element);
element = $('<div class="content"></div>');
j = 0;
}
}
.content {
background: khaki;
margin: 10px;
border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents text-center">
</div>
Use condition i % 9 == 8 as break point
var itemsNumber = Math.floor(Math.random() * 50) + 1;
console.log(itemsNumber);
var contents = $('.contents');
var element = $('<div class="content"></div>');
for (var i = 0; i < itemsNumber; i++) {
element.append('<div class="alert alert-success" role="alert"> Alert ' + i + '</div>');
if (i % 9 == 8) {// break point
contents.append(element);
element = $('<div class="content"></div>');
}else if(i == itemsNumber - 1){// last loop
contents.append(element);
}
}
.content {
background: khaki;
margin: 10px;
border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents text-center">
</div>

How to add a variable's value to an array function?

I'm trying to add the random number to the array which is assigned to a function that keeps adding the numbers together.
function getMiNumber(number){
var value = Math.floor(Math.random() * 10) + 1 ;
value.push(value.value);
var myArray = someCalc([0]);
console.log(myArray);
function showMe(val) {
var presentMe = document.getElementById('someId');
presentMe.innerHTML = val;
}
showMe(myArray);
function someCalc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}
}
UPDATE
Reread the question and determined that a cumulative total is desired so this demo will:
Generate a random number 1 to 10.
Display that number.
Add that number to an array.
Display that array.
Add all of the array's elements.
Display that total.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>34562147</title>
<style>
html,
body {
font: small-caps 400 16px/1.4 'Source Code Pro';
}
fieldset {
border: 2px inset grey;
border-radius: 10px;
}
legend {
font-size: 1.3rem;
}
</style>
</head>
<body>
<fieldset>
<legend>Random Array Total</legend>
<input id="btn1" type="button" onclick="rand()" value="Random" />
<br/>
<label for="out0">Next:
<output id="out0"></output>
</label>
<br/>
<label for="out1">Array:
<output id="out1"></output>
</label>
<br/>
<label for="out2">Total:
<output id="out2"></output>
</label>
</fieldset>
<script>
var xArray = [];
function rand() {
var ran1 = Math.floor(Math.random() * 10) + 1;
var out0 = document.getElementById('out0');
var out1 = document.getElementById('out1');
var out2 = document.getElementById('out2');
out0.value = ran1;
xArray.push(ran1);
out1.value = xArray;
out2.value = calc(xArray);
}
function calc(xArray) {
var total = 0;
for (var i = 0; i < xArray.length; i++) {
total += xArray[i];
}
return total;
}
</script>
</body>
</html>
OLD
The array is pre-determined in this demo var xArray = [23, 8, 90, 7];
function randomNumber(xArray){
var value = Math.floor(Math.random() * 10) + 1 ;
xArray.push(value);
return xArray;
}
var xArray = [23, 8, 90, 7];
var total = calc(randomNumber(xArray));
console.log(total);
function output(total) {
var out1 = document.getElementById('out1');
out1.value = total;
}
function calc(list) {
var total = 0;
for(var i = 0; i < list.length; i++){
total += list[i];
}
return total;
}
output(total);
<output id="out1"></output>

In an array, how can I get values printed the way I would like them printed instead of the last value?

I am using a for-loop to get the values of a sorted list using .html() but it is only printing the last value in the array. I thought by using myArray.length and myArray[i] in the loop that it would cycle through as expected.
Ideally, I would like this to read:
The sorted values are:
1, 2, 3, 4, 5 etc. . .
What am I doing wrong?
Fiddle here.
HTML:
<div id="wrapper">
<div id="content">
<h1>Let's Do Some Math</h1>
<div id="intake">
<input type="text" id="input"> <button id="inTakeButton">Push to Array</button> <button id="showArray">Show Array</button> <button id="doMath">Do Math</button>
</div>
<div id="middle">
<ul id="list">
</ul>
</div>
<div id="output">
<p id="sorted"></p>
<p id="sum"></p>
<p id="average"></p>
</div>
</div>
</div>
CSS:
#wrapper{
width: 80%;
margin: 0 auto;
border: 1px solid black;
border-radius: 5px 5px 5px 5px;
box-shadow: 5px 5px 10px 3px black;
padding: 10px;
}
h1 {
text-align: center;
color: orange;
text-shadow: 1px 1px blue;
}
#intake {
text-align: center;
}
JavaScript:
myArray = [];
var theTotal;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " + theTotal);
var average = (theTotal/myArray.length);
$('#average').html("");
$('#average').html("The mean value is: " + average);
var sorted = myArray.sort();
$('#sorted').html("");
for (var i = 0; i < myArray.length; i++) {
$('#sorted').html("The sorted values are: <br>" + myArray[i] + ", ");
};
});
});
});
You don't even need to use loop trough the array to do this, just:
$('#sorted').html("The sorted values are: <br>" + myArray.join(", "));
In your loop for the sorted values, you are overriding the entire HTML content each time.
Try something like
for (var i = 0; i < myArray.length; i++) {
$('#sorted').append(myArray[i] + ", ");
};
You can try this. Instead of showing the values using a loop, you can just display the whole array at once. Edited JS code:
myArray = [];
var theTotal;
$(document).ready(function() {
$('#inTakeButton').on('click', function() {
var inputValue = parseFloat($('#input').val());
if (inputValue === "") {
return;
}
if (isNaN(inputValue)) {
$('#input').val("");
return;
}
myArray.push(inputValue);
$('#input').val("");
});
$('#showArray').on('click', function() {
console.log(myArray);
$('#list').html("");
for (var i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i] + "</ul>");
};
$('#doMath').on('click', function() {
theTotal = 0;
for (var i = 0; i < myArray.length; i++) {
theTotal = theTotal + myArray[i];
};
$('#sum').html("");
$('#sum').html("The sum is: " + theTotal);
var average = (theTotal/myArray.length);
$('#average').html("");
$('#average').html("The mean value is: " + average);
var sorted = myArray.sort();
$('#sorted').html("The sorted values are: <br>" + myArray )
});
});
});
Check out the fiddle
var sorted = myArray.sort(function (a, b) {
return a - b;
});
use this for sorting

Categories

Resources