I tried making mean deviation calculator using javascript but when I try to output the summation of |x-x̅|, It always returns 0;
var frequencies = []
var output = document.getElementById("text")
function add() {
var score = document.getElementById("lol").value
frequencies.push(score)
}
function show() {
//Calculate the mean
var total = 0
var mean = 0
var scoreMinusMean = []
var summation = 0
for (i = 0; i < frequencies.length; i++) {
total += parseInt(frequencies[i])
}
mean = total / frequencies.length
//Gets the score - mean
for (j = 0; j < frequencies.length; j++) {
scoreMinusMean.push(Math.abs(frequencies[j] - mean))
}
for (k = 0; k < scoreMinusMean; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML = scoreMinusMean
}
<input id="lol">
<button onclick="add()">Add</button>
<button onclick="show()">Show</button>
Output: <span id="text"></span>
In your last loop, the condition you have is k < scoreMinusMean, you forgot to add .length there. It should be
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
Also, you should use let before declaring the variables or else they will be made global.
var frequencies = [];
var output = document.getElementById("text")
function add() {
var score = document.getElementById("lol").value
frequencies.push(score)
}
function show() {
//Calculate the mean
var total = 0
var mean = 0
var scoreMinusMean = []
var summation = 0
for (i = 0; i < frequencies.length; i++) {
total += parseInt(frequencies[i])
}
mean = total / frequencies.length
//Gets the score - mean
for (j = 0; j < frequencies.length; j++) {
scoreMinusMean.push(Math.abs(frequencies[j] - mean))
}
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML = summation
}
<input id="lol">
<button onclick="add()">Add</button>
<button onclick="show()">Show</button>
Output: <span id="text"></span>
THe last four lines of your code should be:
for (k = 0; k < scoreMinusMean.length; k++) {
summation += scoreMinusMean[k]
}
output.innerHTML =summation/frequencies.length
}
As you forgot the .length on the array, and for a standard deviation, you need to average the deviation again (ie. divide the total of deviations from the mean, by the number of elements).
Related
I have tried this but only from 1 to 50 or 1 to 100 prime numbers are obtained.
How should I properly find out the prime number. Which are asked by users?
<h1>enter the no.</h1><input type="text" id="limit">
<h1>enter the no.</h1><input type="text" id="limit2">
<button onclick="fun()">Submit</button>
<div id="result"></div>
<script type="text/javascript">
function fun() {
var i = limit;
var j = limit2;
limit = document.getElementById('limit').value;
limit2 = document.getElementById('limit2').value;
for (i = limit; i <= limit2; i++) {
c = 0;
for (j = 1; j <= i; j++) {
if (i % j == 0) {
c++;
}
}
if (c == 2) {
document.getElementById("result").insertAdjacentHTML('beforeend', i + '<br>');
}
}
}
</script>
Find the corrections below
function fun() {
/*var i = limit;*/
/*var j = limit2;*/
var limit = document.getElementById('limit').value;
var limit2 = document.getElementById('limit2').value;
var result = document.getElementById("result");
result.innerHTML = "Result: ";
for (var i = limit; i <= limit2; i++) {
var prime = true;
/* set j = 2 and NOT j = 1 */
for (var j = 2; j < i; j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) {
result.insertAdjacentHTML('beforeend', i + ','); /* replaced <br/> with , to avoid page scroll */
}
}
}
fun(); /* test pupose only */
h1 {
margin: 0px;
}
<h1>enter the no.</h1><input type="text" id="limit" value="12">
<h1>enter the no.</h1><input type="text" id="limit2" value="55">
<button onclick="fun()">Submit</button>
<div id="result">Result:</div>
The text inserted inside an input is of type string , so you need to convert them to a number. Note the use of + document.getElementById("limit").value. The + convert a string to number.
The fill range function inside fun creates a new array starting from the the value inserted in the first text box upto the value inserted in second text box.
The array fill function will be used to create an array of length end-start+1 and initially filled with undefined. The map function will then create another array but undefined will be replaced by consecutive values.
filter is used to return only prime numbers
function fun() {
const fillRange = (start, end) => {
return Array(end - start + 1)
.fill().map((item, index) => start + index)
.filter((number) => {
for (var i = 2; i <= Math.sqrt(number); i++) {
if (number % i === 0) return false;
}
return true;
});
};
let lowerRange = +document.getElementById("limit").value;
let upperRange = +document.getElementById("limit2").value
const primeNums = fillRange(lowerRange, upperRange);
document.getElementById("result").innerHTML = primeNums.join('<br/>')
}
<h1>enter the no.</h1><input type="text" id="limit">
<h1>enter the no.</h1><input type="text" id="limit2">
<button onclick="fun()">Submit</button>
<div id="result"></div>
If you want the fast implementation of the wiki link you provided in the question, here is the javascript for the same:
function getPrimesSuperFast(m, n) {
// Eratosthenes algorithm to find all primes under n
var array = [], upperLimit = Math.sqrt(n), output = [];
// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}
// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}
// All array[i] set to true are primes
for (var i = m; i < n; i++) {
if(array[i]) {
output.push(i);
}
}
return output;
}
function getPrimes() {
var a = Number(document.getElementById("num1").value);
var b = Number(document.getElementById("num2").value);
var result = getPrimesSuperFast(a, b);
document.getElementById("res").value = result;
}
<input type="number" id="num1">
<input type="number" id="num2">
<button id="primes" onClick="getPrimes()">Get Primes</button>
<hr>
<textarea id="res" rows="20" cols="50">result will be displayed here...</textarea>
Using Sieve of Eratosthenes link: Rosetta Code
If I run the following code it will output 0.
var total = 0;
for(var i = i; i <= 100; i++) {
total = total + i;
}
console.log(total);
This is because the line console.log(total) doesn't wait for the loop to finish; it just immediately executes.
How can I print the final value of total?
There is a mistake in your code:
change:
for(var i = i; i <= 100; i++)
To:
for(var i = 0; i <= 100; i++)
And it works:
var total = 0;
for(var i = 0; i <= 100; i++) {
total = total + i;
}
console.log(total);
Change for loop to
for(var i = 0; i <= 100; i++) { //i=0 instead of i = i
i = i will cause i = undefined and that will cause i < 100 to fail
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});
I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. It is working with larger numbers. There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly.
function sumPrimes(num) {
var sum = 0;
var count = 0;
var array = [];
var upperLimit = Math.sqrt(num);
var output = [];
for (var i = 0; i < num; i++) {
array.push(true);
}
for (var j = 2; j <= upperLimit; j++) {
if (array[j]) {
for (var h = j * j; h < num; h += j) {
array[h] = false;
}
}
}
for (var k = 2; k < num; k++) {
if (array[k]) {
output.push(k);
}
}
for (var a = 0; a < output.length; a++) {
sum += output[a];
count++;
}
return sum;
}
sumPrimes(977);
The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n.
Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977.
The issue seems to be fixed when I change all instances of < num to < num+1.
I am trying to find the phone number whose digits sum to the largest number. I was able to get get the correct phone number but it returned with a => 0. I'm curious to know why that follow.
var allNum = ['123-456-7777', '963-481-7945', '111-222-3333'];
console.log(allNum[highest_number_index]);
var sum;
var highest_Num;
var highest_number_index;
for (var i = 0; i < allNum.length; i++){
allNum[i] = allNum[i].replace(/-/g, "");
for(var j= 0; j < (allNum[i].length); j++){
sum += parseInt(newNum[j], 10);
}
if (sum > highest_Num) {
highest_Num = sum;
highest_number_index = i;
}
sum = 0;
}