Javascript Showing even numbers only - javascript

I've got this project where I have to generate random mathematics sums...
They are all 'divide by' sums, so I want to make all numbers even.
Can anyone help me with this? just ask if I'm not clear enough =)
<script>
$(function() {
var number = document.getElementById("breuken"),
i = 1;
for (; i <= 10; i++) {
var sRandom = Math.floor(Math.random()*10 + 1),
fRandom = Math.floor(sRandom + Math.random()*(20-sRandom )),
calc = Math.abs(fRandom / sRandom),
textInput = document.createElement('input'),
span = document.createElement('span'),
p = document.createElement('p');
textInput._calc = calc;
textInput.onchange = (function(p) {
return function(ev) {
var self = ev.target;
if (self.value == self._calc) {
p.style.color = 'green';
};
};
})(p);
span.innerHTML = fRandom + " : " + sRandom + " = ";
p.appendChild(span);
p.appendChild(textInput);
number.appendChild(p);
};
});
</script>

To get an even random number just:
halve you range and multiply by 2
var range = 100;
var number = Math.floor( Math.random() * range / 2 ) * 2;
or keep getting random numbers until you get an even one
var number;
do {
number = Math.floor(Math.random()*10 + 1)
} while( number % 2 == 1 );

Get a random integer over 1/2 the range and double it.

Related

Need to make a list of the outstanding GPA’s from the array Im making (GPA’s over 3.4). Prefer traditional loop solution over some ES6 function

I need help with getting a list of GPAs over 3.4. I was able to sort largest to smallest, average, and get min and max GPAs utilizing traditional approaches (not ES6).
<div id ="out"></div>
<script>
var gpas = [];
var thegpas = " ";
var total = 0
while (thegpas != "XXX")
{
thegpas = prompt("Enter gpas or XXX to Stop");
if(thegpas != "XXX"){
gpas.push(thegpas);
} else {
break;
}
}
for(var x = 0; x < gpas.length; x++)
{
a = gpas.sort((a,b)=>b-a);
total=total + parseFloat(gpas[x]);
b = total/gpas.length //parseFloat(total)/length;
var max = gpas[0];
var min = gpas[0];
for(var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
}
//need help with this part
//outstandingGPAs=0;
outstandingGPAs = [];
cutoff = 3.4;
if (gpas[x]>cutoff){
outstandingGPAs.push(parseFloat(gpas[x]));
}
out= "Largest to smallest " + a + "<br/>" + "GPAs average: " + b + "<br/>" + " Max and Min: " + max + ", " + min + "<br/>" + "Outstanding GPAs (greather than 3.4): " + outstandingGPAs ;
// alert(gpas[x]);
}
document.getElementById('out').innerHTML=out;
Current Output:
Best way to output a (not very long) array is the join function.
In your output, you should use:
out = "<whatever you put>" + outstandingGPAs.join();
Check this link for more explanation of the join function.
Since you are already looping over your gpas array you could save those that are over 3.4 while you do that.
You would do that within your existing loop, not afterwards.
const cutoff = 3.4;
let outstandingGPAs = [];
// ...
for (var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
// added to the existing loop
if (gpas[i] > cutoff) {
outstandingGPAs.push(gpas[i]);
}
}
The outer loop should not be there, as you just redo the same operation over and over again.
As you only push at most one value in outstandingGPAs after you have set it to the empty array, that result will be wrong.
There are several other similar issues going on...
Also, getting input with prompt is really not user-friendly. The way to do this, is using an input element, and let the user type all values freely, and go back and correct whenever they want, and when they are happy with it, they can press a button so the code can run on it.
Here is how that looks:
var calcButton = document.getElementById("calc");
var gpasInput = document.getElementById("gpas");
var outDiv = document.getElementById('out');
calcButton.addEventListener("click", function () {
var min = Infinity,
max = -Infinity,
total = 0,
gpas = [],
outstandingGPAs = [];
// Collect the input as an array of strings with number-related characters
var inputStrings = gpasInput.value.match(/-?\d+(\.\d+)?/g);
for (var i = 0; i < inputStrings.length; i++) {
var num = parseFloat(inputStrings[i]);
gpas.push(num);
if (num > 3.4) {
outstandingGPAs.push(num);
}
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
total += num;
}
var average = total / gpas.length;
gpas.sort((a, b) => b - a);
// lets also sort the outstanding GPAs
outstandingGPAs.sort((a, b) => b - a);
outDiv.innerHTML = "Largest to smallest " + gpas.join(", ") + "<br>"
+ "GPAs average: " + average + "<br>"
+ "Max and Min: " + max + ", " + min + "<br>"
+ "Outstanding GPAs (greather than 3.4): " + outstandingGPAs.join(", ");
});
Enter gpas values: <input id="gpas">
<button id="calc">Calculate</button><br>
<div id ="out"></div>
Here:
let theGpas = "";
let gpaArr = [];
while(theGpas != "XXX"){
theGpas = prompt("Enter GPAs. Enter XXX to stop.");
if(theGpas != "XXX"){
gpaArr.push(theGpas);
}
}
gpaArr = gpaArr.sort();
document.write("Largest to Smallest: "+gpaArr.join(",")+"<br/>");
function average(array){
var totalSum = 0;
for(var n in array){
totalSum += array[n];
}
return totalSum/array.length;
}
function moreThanArray(array, comparison){
var returnArr = [];
for(var z in array){
if(array[z]>comparison){
returnArr[returnArr.length] = array[z];
}
}
return returnArr;
}
const averageOf = average(gpaArr);
document.write("GPAs average: "+averageOf+"<br/>");
document.write("Max and Min: "+gpaArr[gpaArr.length-1]+", "+gpaArr[0]);
document.write("<br/>"+"Outstanding GPAs (greater than 3.4): "+moreThanArray(gpaArr, 3.4).join(","));

create a random integer unique in a given array

<div id='passarr'>1572 4528 3564 8921 4521</div>
I need to create a new random integer (4 digits), unique regarding the above content.
js
var content = $('#passarr').text();
var passarr = content.split(' ');
var pass = Math.floor(Math.random() * 9000) + 1000;
var i = 0;
while (i == 0) {
if (jQuery.inArray(pass, passarr) > -1) {
var pass = Math.floor(Math.random() * 9000) + 1000;
i = 1;
}
}
seems it works, but not sure this is the right and shortest way.
any suggestion?
Your code is the way to go. However, you can eliminate a few smaller mistakes ( an unneccessary i and non working code in < 0.00001%) :
var content = $('#passarr').text();
var passarr = content.split(' ');
do {
var pass = Math.floor(Math.random() * 9000) + 1000;
} while (jQuery.inArray(pass, passarr) > -1);
console.log(pass);

JS: How can I nest for loops WITHOUT making the first loop loop the second?

Issue with my for loop setup:
var gain = prompt("Please enter the GAIN value");
var rtp = prompt("Please enter the RTP value");
var equation = function (gaininput, mdecinput) {
rs = 2.56 * mdecinput / (0.0002 * gaininput * Math.pow(2, 24));
return rs;
};
var sum = 0;
var co = [439.932854, 472.41802, 37.684494, 7.472018, 2.920828, 0.005184, -0.963864, -0.188732, 0.191203, 0.049025];
var cohigh = [0.183324722, 0.240975303, 0.209108771, 0.190439972, 0.142648498, 0.077993465, 0.012475611, -0.032267127, -0.075291522, -0.05647067, 0.076201285, 0.123893204, -0.029201193, -0.091173542, 0.001317696, 0.026025526];
for (var i = 0; i <= 16777215; i += 5000) {
var rsoutput = equation(gain, i);
var w = (rsoutput / rtp);
document.writeln((i) + '. ' + rsoutput + '<br/>');
var blackbox = function blackbox(b) {
var coefficient = co[b];
if (w<1){
coefficient = co[b];
}
else{
coefficient = cohigh[b];
}
return (coefficient * Math.pow(((Math.pow(w, 1 / 6) - 0.65) / 0.35, b), b));
};
if (w<1){
for (var j = 0; j <= 15; j++) {
sum = sum + blackbox(j);
sum = sum * 273.16;
document.writeln("YOUR SUM: " + sum + '<br/>');
}
}
else {
for (var jtwo = 0; jtwo<=15; j++) {
sum = sum + blackbox(j);
sum = sum * 273.16;
document.writeln("YOUR SUM: " + sum + '<br/>');
}
}
}
var temp = prompt("Enter the temperature in KELVIN");
console.log("YOUR TEMPERATURE: " + temp * 1.86455556 + '<br/>');
When I run this code, what happens is that the first loop loops the if / else statement 16 million times. I don't want this to happen, but I have to put the if / else statement in this loop so that I can call variable w. Is there a workaround to this?
Thanks!
Well if you dont want the the if statements to be run inside the loop then I would move them out, if the only issue is accessing the W variable from outside the loop then move the delaration of "var w;" outside (above) the loop as well. Then the if statements can access it too.
var w;
for (var i = 0; i <= 16777215; i += 5000)
{
w = (rsoutput / rtp);
**do stuff**
}
if (w<1)
{
}
else
{}

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

unknown issue w/ JavaScript random number function

var randNum = function(){
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
addTXT(num);
}
};
This function is supposed to take the numbers typed into the text boxes with the IDs 'min', 'max', and 'reps', and use them to come up with some random numbers. It doesn't write anything to the HTML document. The addTXT() function should write the number to a div, and I know it works because I've used it just fine before this. Any help would be appreciated. Also, I've been working with javascript less than a week, so I'm suspicious the problem is really obvious and I just don't see it.
var addTXT = function(newText){
var outputDiv=document.getElementById("console");
var oldText = outputDiv.innerHTML;
outputDiv.innerHTML = newText + oldText;
};
Parse the string values into integers with parseInt():
var max = parseInt(document.getElementById('max').value);
var min = parseInt(document.getElementById('min').value);
var reps = parseInt(document.getElementById('reps').value);
DEMO.
Where do you get the issue? If you unsure, try to put an alert in on certain spots in your code.
For example:
var randNum = function(){
alert('Function is triggered');
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
alert(num);
addTXT(num);
}
};
If your addTxt function does not work, try the jQuery way
var randNum = function(){
alert('Function is triggered');
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
alert(num);
$('#console').append(num);
}
};

Categories

Resources