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

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.

Related

Find the smallest common multiple

well i hope you can understand me. I want to get the the smallest common multiple between the range of number i give to the function, for example if i put looker(1,3) the function will look for the smallest common multiple in 1,2,3 that's the range, and the answer it's 6, i dunno if get it.
this is a challenge from freecodecamp, the problem it's that when i run function with the with the range (1,3) it works, (1,5) it works, but with other ranges the google console says "rende process gone".
const looker = (arra) => {
var nume = [];
var status = "no";
var statusN = 0;
var array = [];
var mul = [];
var contador = arra[1];
var aumentador = 2;
while(contador > arra[0] - 1) {
array.push(contador);
mul.push(contador);
nume.push(contador);
contador--;
}
// console.log(nume);
// console.log(array);
// console.log(mul);
// console.log(contador);
while(contador != arra[1]) {
for(let x of nume) {
array.push(x*aumentador);
mul.push(x*aumentador);
}
aumentador++;
for(let a of mul) {
for(let i of array) {
if(a == i) {
contador++;
}
}
if(contador == arra[1]) {
status = "si"
statusN = a;
break;
} else {
status = "no";
contador = 0;
}
}
}
if(status == "si") {
console.log(`el numero que se repite es ${statusN}`);
} else {
console.log(`ningun numero se repite ${arra[1]} veces`);
}
}
I think you want something like this ..
function findGCD() {
if($("#first").val() != null && $("#second").val() != null ){
let fn = parseInt($("#first").val());
let sn = parseInt($("#second").val());
let gcd = lcm_two_numbers(fn, sn);
$("#answer").html("Smallest common multiple : " + gcd)
}
}
function lcm_two_numbers(x, y) {
if ((typeof x !== 'number') || (typeof y !== 'number'))
return false;
return (!x || !y) ? 0 : Math.abs((x * y) / gcd_two_numbers(x, y));
}
function gcd_two_numbers(x, y) {
x = Math.abs(x);
y = Math.abs(y);
while(y) {
var t = y;
y = x % y;
x = t;
}
return x;
}
button {
background: #0095ff;
padding: 8px;
border-radius: 3px;
border: none;
color: white;
width: 80px;
margin-left: 20px;
cursor: pointer;
}
p {
font-weight: 700;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="first">First number:</label>
<input type="number" id="first" name="first" min="1" max="5">
<label for="second">Second number:</label>
<input type="number" id="second" name="second" min="1" max="5">
<button onclick="findGCD()">GCD</button>
<p id="answer"></p>

I need to figure out the problem in my code as it give false results (+1)

I need help to make the right table with the same result not plus one
let table = document.getElementById("pixelCanvas");
let sizePicker = document.getElementById("sizePicker");
let height = document.getElementById("inputHeight").value;
let width = document.getElementById("inputWidth").value;
makeGrid(height, width);
sizePicker.addEventListener("click", (e) => {
e.preventDefault();
let height = document.getElementById("inputHeight").value;
let width = document.getElementById("inputWidth").value;
table.firstElementChild.remove();
makeGrid(height, width);
});
function makeGrid(height, width) {
for (let i = 0; i <= height; i++) {
let row = table.insertRow(i);
for (let j = 0; j <= width; j++) {
let cell = row.insertCell(j);
cell.addEventListener("click", (e) => {
cell.style.backgroundColor = color.value;
})
}
}
}
I done it only because it was fun an short to do..
const in_H = document.querySelector('#input-Height')
, in_W = document.querySelector('#input-Width')
, btColor = document.querySelector('#Color-Button')
, btDraw = document.querySelector('#size-Picker')
, PixTab = document.querySelector('#pixel-Canvas')
;
function makeGrid()
{
let hMax = in_H.valueAsNumber
, wMax = in_W.valueAsNumber
;
PixTab.innerHTML = null
for (let h = 0; h < hMax; h++)
{
let row = PixTab.insertRow(h)
for (let w = 0; w < wMax; w++)
{ row.insertCell(w) }
}
}
makeGrid() // for init
btDraw.onclick = makeGrid
PixTab.onclick=e=>{
if (e.target.tagName.toLowerCase() != 'td') return
e.target.style.backgroundColor = btColor.value
}
table { border-collapse: collapse; margin: 1em }
td { border: 1px solid grey; width: 1em; height: 1em; }
<p>
height: <input type="number" min="5" max="20" value="5" id="input-Height">
width: <input type="number" min="5" max="20" value="5" id="input-Width" >
</p>
<p>
<input id="Color-Button" type="color" >
<button id="size-Picker" >draw new rect</button>
</p>
<table id="pixel-Canvas"></table>

minesweeper getAttribute of null error

Recently been creating minesweeper and came across a "Cannot read property 'getAttribute' of undefined" error on lines 19, 39, and 62 of my javascript code. I added the HTML to show where the javascript code is getting the variables from.
document.getElementById("begin").addEventListener("click", startGame);
let vertical;
let horizontal;
let DIFFICULTY;
let GG = false;
document.body.addEventListener('contextmenu', function(cm){e.preventDefault();});
function Winner(){
let ckCt = document.querySelectorAll('[clicked]').length;
let mCt = document.querySelectorAll('[mine]').length;
let cCt = horizontal * vertical;
if(cCt == ckCt + mCt){
GG = true;
return true;
}
return false;
}
function acrossTheBlock(cell){
let x = parseInt(cell.getAttribute('x'));
let y = parseInt(cell.getAttribute('y'));
//(x-1, y-1) (x, y-1) (x+1, y-1)
//(x-1, y) (x, y) (x+1, y)
//(x-1, y+1) (x, y+1) (x+1, y+1)
let nw = document.getElementById((x-1) + "_" + (y-1));
let n = document.getElementById((x) + "_" + (y-1));
let ne = document.getElementById((x+1) + "_" + (y-1));
let w = document.getElementById((x-1) + "_" + (y));
let e = document.getElementById((x+1) + "_" + (y));
let sw = document.getElementById((x-1) + "_" + (y+1));
let s = document.getElementById((x) + "_" + (y+1));
let se = document.getElementById((x+1) + "_" + (y+1));
return [nw, n, ne, w, e, sw, s, se];
}
function amt(count){
let z = 0;
let nextDoor = acrossTheBlock();
for(var n = 0; n < nextDoor.length; n++){
if(nextDoor[n] && nextDoor[n].hasAttribute("mine")){
count++
}
}
return count;
}
function findTheMine(e){
if(isNewGame){ this.removeAttribute("mine"); }
isNewGame = false;
if(this.classList.contains('flag')) { return; }
if(this.hasAttribute('clicked')) { return; }
if(this.hasAttribute("mine")){
//You lose!
isGameOver = true;
let bombs = document.querySelectorAll("[mine]");
for(var i = 0; i < bombs.length; i++){
bombs[i].className = "boom";
}
return;
}
this.setAttribute('clicked', true);
let BOOM = amt(this);
if(BOOM){
this.innerHTML = BOOM;
this.className = "c" + BOOM;
} else {
let nextDoor = acrossTheBlock(block);
for(var n = 0; n < nextDoor.length; n++){
if(nextDoor[n] && nextDoor[n].hasAttribute("mine")){
count++
}
}
}
isWin();
}
function IThinkIFoundTheMine(yay){
yay.preventDefault();
if(GG) { return; }
if(this.hasAttribute('clicked')) { return; }
if(this.classList.contains('flag')){
this.classList.remove('flag');
} else {
this.className = 'flag';
}
}
function getDifficulty(){
let radios = document.getElementsByName("difficulty");
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
return parseFloat(radios[i].value);
}
}
}
function startGame(){
vertical = parseInt(document.getElementById("vertical").value);
horizontal = parseInt(document.getElementById("horizontal").value);
DIFFICULTY = getDifficulty();
isNewGame = true;
isGameOver = false;
//clear out old gameboard (this allows for a new game.)
document.getElementById("minefield").innerHTML = "";
//dynamically build table.
var table = document.createElement("table");
document.getElementById("minefield").appendChild(table);
for(var r = 0; r < horizontal; r++){
var mineRows = document.createElement("tr");
table.appendChild(mineRows);
for(var c = 0; c < vertical; c++){
var textbox = document.createElement("td");
textbox.addEventListener("click", findTheMine);
textbox.addEventListener("contextmenu", IThinkIFoundTheMine);
textbox.setAttribute("id", c + "_" + r);
textbox.setAttribute("x", c);
textbox.setAttribute("y", r);
if(Math.random() < DIFFICULTY){
textbox.setAttribute("mine", true);
}
mineRows.appendChild(textbox);
}
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="minesweeper.css"/>
<title>Explosion</title>
</head>
<body>
<input id="horizontal" type="number" value="10">
<input id="vertical" type="number" value="10">
<input name="difficulty" value=".1" type="radio">Easy
<input name="difficulty" value=".2" type="radio" checked="true">Medium
<input name="difficulty" value=".3" type="radio">Hard
<input name="difficulty" value=".8" type="radio">Impossible
<button id="begin">Good Luck</button>
<div id="minefield"></div>
<script type="text/javascript" src="minesweeper.js"></script>
</body>
</html>
How can I fix this error?
On line 39 the script calls acrossTheBlock() without passing the argument (cell) needed to do cell.getAttribute() on the first two lines under that function.

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>

Standard Deviation Calculator in 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.

Categories

Resources