Basic JavaScript Sort Above Mean and Below - javascript

I am trying to write a JavaScript code that will take a users input and find the mean. Then it should put the numbers above the mean in a list and the numbers below the mean. Everything is working except for the sorting of the numbers below and above the mean. Than you for your help.
function getNums()
{
var nums = new Array();
var numAmt = prompt("How many data values do you have?");
numAmt = parseInt(numAmt);
var i = 0;
for (i = 0; i<= numAmt - 1; i++)
{
nums[i]= prompt("Enter the data value number " + (i + 1));
}
var sum = 0;
for(i = 0; i < nums.length; i++)
{
sum += parseInt(nums[i]);
var avg = sum/nums.length;
}
var big = 0;
var small = 0;
for (i = 0; i < nums.length; i++)
{
if (nums[i] > avg)
big += parseInt(numbers[i]);
else
small += parseInt(numbers[i]);
document.getElementById('numbers').innerHTML = "Your data: " + nums;
document.getElementById('average').innerHTML =("The mean(average) of these numbers is: " + avg.toFixed(2) +".<br>");
document.getElementById('bigger').innerHTML = "Your data: " + big;
document.getElementById('smaller').innerHTML = "Your data: " + small;
}
}

I would personally break this into two functions, one focused on "find the mean of this array", and another on "sort this array around a pivot."
function mean(arr) {
var sum = arr.reduce(function (prev, curr) {
return prev + curr;
});
return sum / arr.length;
}
function pivotSort(arr, pivot) {
var sorted = [];
arr.forEach(function (val) {
if (val >= pivot)
sorted.push(val);
else
sorted.unshift(val);
});
}
The pivot sort is not even close to optimized, but heck, v8 is pretty quick nowadays.

Related

Array not being populated in some ocasions

I'm having a hard time to crack this one out, would appreciate a hand with this script.
Trying to do a countdown script where I have to display the new number counting from previous.
let oldN = 0;
let newN = 0;
let arr = [];
function runner() {
arr = [];
newN = document.getElementById('newVar').value;
console.log("stored: " + oldN + " new: " + newN);
if (oldN > newN) {
for (let i = oldN; i >= newN; i--) {
arr.push(i);
}
} else if (oldN < newN) {
for (let e = oldN; e <= newN; e++) {
arr.push(e);
}
}
console.log("array: " + arr.length);
oldN = newN;
for (let u = 0; u < arr.length; u++) {
(function(index) {
setTimeout(() => {
document.getElementsByTagName('span')[0].innerText = arr[index];
}, 100 * u);
})(u);
}
}
<div class="board">
<span><!----></span>
</div>
<br/>
<input type="text" id="newVar" />
<button onclick="runner()">Start</button>
It seems to work but if I go from 13 to 7 it won't populate the array thus not running the countdown, the same issue happens when going from 7 to 13.
Any idea?
Kind Regards
You forgot to convert the input value (a string) to a number. They are compared alphabetically not numerically then, and "13" < "7" so your loop doesn't work. Use
newN = parseInt(document.getElementById('newVar').value, 10);

Find common Factor of two values

I have the following javascript code to calculate the factors of numbers.
var some = [];
var main = "";
var final = "";
function text(data) {
spliter = data.split(",");
var k = 0;
while (k < spliter.length) {
var meethi = 0;;
main = spliter[k];
var datas = "";
for (var i = 1; i <= 10; i += 1) {
meethi = Math.abs(main / i);
datas = meethi;
some.push('' + datas + '');
}
some.forEach(myFunction);
final += res + '<br>';
k++;
}
return final;
}
var max = 0;
var res = "";
function myFunction(item) {
var van = item.split(".");
if (van[1] == undefined) {
var high = Math.floor(main / van[0]);
if (high > max) {
max = high;
res += max + ':';
}
}
}
document.getElementById('demo').innerHTML = text('124,20');
<p id="demo"></p>
My program gets the factors with two values. How do I identify the common factor of both values,only the highest common value?
example like ('124,20') output --> 4
I tried the code with my own knowledge. If you have any other suggestion for code please tell me and correct my code with my desired result.
my fiddle
You could use for the greatest common divisor Euclid's algorithm.
function gcd(k, n) {
return k ? gcd(n % k, k) : n;
}
console.log(gcd(124, 20));
console.log([10, 500, 600].reduce(gcd));

JavaScript Function Arrays

How would I use a function that returns the sum of a given array while getting the sum of the even numbers and sum the odd numbers? I'm not understanding how that is done. Can someone please explain a little more in depth?
Here is my entire code:
function main()
{
var evenNum = 0;
//need a total Even count
var oddNum = 0;
//need a total Odd count
var counter = 1;
var num = 0;
function isOdd(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
function isEven(x) {
if ((num % 2) == 0)
{
return false;
}
else
{
return true;
}
}
for (counter = 1; counter <= 100; counter++)
{
num = Math.floor(1 + Math.random() * (100-1));
var total = 0;
for(var j = 0; j < length; j++)
total += a[j];//Array?
console.log(num);
console.log("The count of even number is " + evenNum);
console.log("The count of odd number is " + oddNum);
return 0;
}
main()
If I understand your question correctly, you need a function that returns two values, one for the sum of even numbers and one for the sum of odd numbers. It's not clear if you use even/odd referring to the index of the array or the values in array.
In both cases you can return an object that contains both values:
function sum(array) {
var evenSum = 0;
var oddSum = 0;
...calculate...
var res = {};
res.evenSum = evenSum;
res.oddSum = oddSum;
return res;
}
Hope this will help

Javascript Loto Game

How can I check for matching numbers in this script, stuck here, I need to compare the array of user numbers with the array of lotto numbers and display how many numbers they got correct if any along with their prize value.
function numbers() {
var numbercount = 6;
var maxnumbers = 40;
var ok = 1;
r = new Array(numbercount);
for (var i = 1; i <= numbercount; i++) {
r[i] = Math.round(Math.random() * (maxnumbers - 1)) + 1;
}
for (var i = numbercount; i >= 1; i--) {
for (var j = numbercount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])) ok = 0;
}
}
if (ok) {
var output = "";
for (var k = 1; k <= numbercount; k++) {
output += r[k] + ", ";
}
document.lotto.results.value = output;
} else numbers();
}
function userNumbers() {
var usersNumbers = new Array(5);
for (var count = 0; count <= 5; count++) {
usersNumbers[count] = window.prompt("Enter your number " + (count + 1) + ": ");
}
document.lotto.usersNumbers.value = usersNumbers;
}
Here is a lotto numbers generator and a scoring system. I'm going to leave it to you to validate the user input.
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
function scoreIt(){
var usersNumbers = document.getElementsByName('usersNumbers').item(0);
usersNumbers = String(usersNumbers)
usersNumbers = usersNumbers.split(' ');
var matches = 0;
for(var i = 0; i<6; i++){
if(lottoNumbers.indexOf(usersNumbers[i]) != -1){matches++;}
}
return matches;
}
Hi I'm new to this and trying to learn off my own back so obviously I'm no expert but the code above makes a lot of sense to me, apart from the fact I can't get it to work.. I tried to console.log where it says RETURN so I could see the numbers but it just shows an empty array still. I assumed this was to do with it being outside the loop..
I've tried various ways but the best I get is an array that loops the same number or an array with 6 numbers but some of which are repeated..
function lottoGen(){
var lottoNumbers = [];
for(var k = 0; k<6; k++){
var num = Math.floor(Math.random()*41);
if(lottoNumbers.indexOf(num) != -1){
lottoNumbers.push(num);
}
}
return lottoNumbers;
}
Lotto JS: CODEPEN DEMO >> HERE <<
(function(){
var btn = document.querySelector("button");
var output = document.querySelector("#result");
function getRandom(min, max){
return Math.round(Math.random() * (max - min) + min);
}
function showRandomNUmbers(){
var numbers = [],
random;
for(var i = 0; i < 6; i++){
random = getRandom(1, 49);
while(numbers.indexOf(random) !== -1){
console.log("upps (" + random + ") it is in already.");
random = getRandom(1, 49);
console.log("replaced with: (" + random + ").");
}
numbers.push(random);
}
output.value = numbers.join(", ");
}
btn.onclick = showRandomNUmbers;
})();

Javascript: getting rid of nested loop

It's been a while since I wrote any Javascript. Is there a more elegant way to do this. Specifically want to get rid of the second loop:
<script>
var number = 0;
for (var i=1; i<11; i++) {
for (var x=1; x<11; x++) {
if (i==1) {
number = x;
} else {
number = Math.pow(i, x);
}
document.write(number + " ");
if (x == 10) {
document.write("<br>");
}
}
}
</script>
I would stick with 2 loops but i would change one if statement and move it after the 2nd loop and avoid document.write and insert it all at once to reduce the number of time you change the DOM
let result = ''
for (let i = 1; i < 11; i++) {
for (let x = 1; x < 11; x++)
result += (i==1 ? x : Math.pow(i, x)) + ' '
result += '<br>'
}
document.body.insertAdjacentHTML('beforeend', result)
Edit If you really don't want the 2nd loop:
let result = ''
// you must swap the condition to check for x instead of i
for (let i = 1, x = 1; x < 11; i++) {
result += (x==1 ? i : Math.pow(x, i)) + ' '
// and reset i and increase x yourself
if (i == 10) {
i = 0
x++
result += '<br>'
}
}
document.body.insertAdjacentHTML('beforeend', result)
Edit2 just for the fun: No for loops.
Just a recursive function :P
function build(i = 1, x = 1, res = '') {
res += (x == 1 ? i : Math.pow(x, i)) + ' '
i == 10 ? (x++, i=1, res += '<br>') : i++
return x == 11 ? res : build(i, x, res)
}
document.body.insertAdjacentHTML('beforeend', build())
In terms of 'elegancy', I'd go for for... in loops or map function. That doesn't solve your nested loop though.
On a side note, nested loops are not necessarily bad. If that's the correct way to implement the specific algorithm, then that's how it is.
Using Math.pow() is un-necessary overhead. Nested loops are not necessarily bad.
var number = 0;
for (var i=1; i<11; i++) {
document.write(i + " ");
number = i;
for (var x=2; x<11; x++) {
number = (i == 1) ? x : number * i;
document.write(number + " ");
}
document.write("<br>");
}
Another way of doing it with 1 loop only, tho not as clean:
var number = 0;
var x = 1;
var calc = 0;
var calcx = 1;
var increment = false;
for (var i=1; i<101; i++) {
increment = false;
calc = i % 10;
if(calc == 0){
calc = 10;
increment = true;
}
if (calcx==1) {
number = calc;
} else {
number = Math.pow(calcx, calc);
console.log(calcx+" "+calc);
}
document.write(number + " ");
if (i % 10 == 0) {
document.write("<br>");
}
if(increment){
calcx++;
}
}
Here's another way with only one loop:
[...Array(100)].map((_,i) => {
document.write(((i>9)?Math.pow(Math.floor((i+10)/10),(i%10)+1):i+1) + ' ' + ((i%10==9)?'<br>':''));
});

Categories

Resources