3 numbers bingo. How could I write it better and shorter? - javascript

So I took simple task from a course where they wanted to let user input 3 numbers between 1 and 100 and repeat it until user numbers are higher then 70.
I made this:https://github.com/itayJoseph/Javascript-Bingo/blob/master/Bingo%20V2.js
//Bingo : User puts 3 numbers and they must be all equal to the computer 3 numbers
//Gets 3 Numbers from User
function getUserNum() {
var userNum = [];
for (var i = 0; userNum.length < 3; i++) {
userNum[i] = prompt("insert one number at a time ranging from 1 to 100");
if (userNum[i] > 100 || userNum[i] < 1 || userNum[i] == '') {
alert("Inavlid Number");
comparison();
} else {
userNum[i] = parseInt(userNum[i]);
}
}
console.log(userNum);
return userNum;
}
//Generate numbers from 1 to 100
function numG(x, y) {
var bingo;
bingo = Math.random() * (y - x) + x;
return parseInt(bingo);
}
//Get 3 Numbers from computer
function compNum() {
var bingoNum = [];
for (var j = 0; bingoNum.length < 3; j++) {
bingoNum[j] = numG(1, 100);
}
return bingoNum;
}
/*
This last function does the job of getting the 3
numbers from user then generating its own 3 numbers untill
all 3 numbers are equal.(follow the console to see the progress)
*/
function comparison() {
var userNumbers = getUserNum();
var bingoNumbers;
if (userNumbers.length == 3) {
do {
var numMatches = 0;
bingoNumbers = compNum();
console.log(bingoNumbers);
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (userNumbers[i] == bingoNumbers[j]) {
numMatches += 1;
}
}
}
} while (numMatches != 3)
}
if (numMatches == 3) {
alert("BINGOOOO");
}
}
comparison();

Related

How do I add the number to the variable in Javascript?

I need to guess the 4-digit code by this program, but I have no idea why it doesn't work.
I tried to use two for loops to guess all of the numbers from 0 to 9 for 4 digits.
However, the program doesn't print anything.
I wonder how can I add the current value x to the variable result.
function start() {
var secretPasscode = generateRandomPasscode();
// Write your code here
var result = "";
//Loop through for the secretPasscode's length
for(var i = 0; i < secretPasscode.length; i++){
//Put numbers from 0 to 9
for(var x = 0; x < 10; x++){
result = "";
var currNum = x;
//If the current number is right, store it to the result
if(currNum == secretPasscode.charAt(i)){
result += x;
}else{
result = result;
}
}
}
return result;
println(result);
}
function isCorrect(guessCode, correctCode) {
return guessCode == correctCode;
}
// Generates a random 4 digit passcode and returns it as a String
function generateRandomPasscode() {
var randomPasscode = "";
for(var i = 0; i < 4; i++) {
var randomDigit = Randomizer.nextInt(0, 9);
randomPasscode += randomDigit;
}
return randomPasscode;
}

Problem with Javascript function not returning total sum in a for loop with if conditions

I am writing pure javascript without any HTML and I am having trouble with one of my functions that would need to return the total "course points."
The program consists of prompting the user the # of course taken followed by the grade received which is pushed in the "grades" array. The function calculateCP will allow it to reiterate every element of the array and is suppose to give me the total course points given the following if conditions.
Please help why my function isn't working! The output is returning only the first element of the array, not the total sum of all elements.
calculateCP = () => {
let coursePoints;
let total = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i] >= 90) {
coursePoints = 4;
} else if (grades[i] >= 80 && grades[i] < 90) {
coursePoints = 3;
} else if (grades[i] >= 70 && grades[i] < 80) {
coursePoints = 2;
} else if (grades[i] >= 60 && grades[i] < 70) {
coursePoints = 1;
} else if (grades[i] < 60) {
coursePoints = 0;
}
return total = total + coursePoints;
}
}
const grades = [];
let noOfCourses = parseInt(prompt("Please enter # of courses taken: "));
console.log("\n")
for (let i = 0; i < noOfCourses; i++) {
grades.push(prompt('Enter grade recieved '));
}
console.log(calculateCP());
}
In the for loop you just want to sum the values.. only once you're done, return the total :) something like this..
calculateCP = () => {
let coursePoints;
let total = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i] >= 90) {
coursePoints = 4;
} else if (grades[i] >= 80 && grades[i] < 90) {
coursePoints = 3;
} else if (grades[i] >= 70 && grades[i] < 80) {
coursePoints = 2;
} else if (grades[i] >= 60 && grades[i] < 70) {
coursePoints = 1;
} else if (grades[i] < 60) {
coursePoints = 0;
}
total = total + coursePoints;
}
return total;
}
const grades = [];
let noOfCourses = parseInt(prompt("Please enter # of courses taken: "));
console.log("\n")
for (let i = 0; i < noOfCourses; i++) {
grades.push(prompt('Enter grade recieved '));
}
console.log(calculateCP());
}
try to remove the return statement from the for loop and put it right after it..
change this:
return total = total + coursePoints;
to this:
... for loop
total = total + coursePoints;
}
return total;

Hirsch Array Function Returning 0 instead of desired output

Trying my hardest to improve but it's been almost 3 hours and I still haven't figured out why this function returns a bunch of 0's
I'm suppose to check the hirsch number of a given array. It is the greatest number n in which n is n times greater than or equal to the values of the array.
This is what I have so far
// Hirsch Number given an array with each space in the array represents a paper and each number represents the amount of citations for a given paper.
function hirschNumber(numberArray)
{
let hirschIndex = 0;
let continueCheck = true;
for (i=0; i < numberArray.length; i++)
{
let count = 0;
let citationsTreshold = hirschIndex + 1
for (i=0; i < numberArray.length; i++)
{
if (citationsTreshold <= numberArray[i])
{
count++
}
if (numberArray.length == (i - 1))
{
if (count >= citationsTreshold)
{
hirschIndex++
}
else if (count < citationsTreshold)
{
continueCheck = false
return
}
}
if (continueCheck = false)
{
return hirschIndex
}
else
{
console.log(hirschIndex)
}
}
if (continueCheck = false)
{
return hirschIndex
}
else {
console.log(hirschIndex)
};
};
return hirschIndex;
};
console.log(hirschNumber([3,0,6,1,5]));

Rounding off to 6 decimals

I would like to round off this code to 6 digits
function plus-minus(arr) {
let pos = 0;
let neg = 0;
let zero = 0;
let len = 6;
for (let i = 0; i < len; i++){
if (arr[i] > 0) {
neg++;
} else if (arr[i] < 0) {
pos++;
} else {
zero++;
}
}
console.log(pos/len);
console.log(neg/len);
console.log(zero/len);
}
For rounding you can use a little trick like this:
var number = 0.00012367
var round = 6;
number = Math.round(number * 10**round) / (10**round)
console.log(number)
Or you can use the toFixed method:
var number = 0.00012367
number = number.toFixed(6)
console.log(number)

Create range of letters and numbers

I'm creating a form where users can input a range. They are allowed to input letters and numbers. Some sample input:
From: AA01
To: AZ02
Which should result in:
AA01
AA02
AB01
AB02
And so on, till AZ02
And:
From: BC01
To: DE01
Should result in:
BC01
BD01
BE01
CC01
CD01
CE01
Etc
I managed to get it working for the input A01 to D10 (for example)
jsFiddle
However, i can't get it to work with multiple letters.
JS code:
var $from = $('input[name="from"]');
var $to = $('input[name="to"]');
var $quantity = $('input[name="quantity"]');
var $rangeList = $('.rangeList');
var $leadingzeros = $('input[name="leadingzeros"]');
$from.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$to.on('keyup blur', function () {
$(this).val($(this).val().replace(/[^a-zA-Z0-9]/g, ''));
updateQuantity();
});
$leadingzeros.on('click', function () {
updateQuantity();
});
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
if (xl != null && yl != null && xl[0].length > 0 && yl[0].length > 0) {
xl = xl[0].toUpperCase();
yl = yl[0].toUpperCase();
$rangeList.html('');
var a = yl.charCodeAt(0) - xl.charCodeAt(0);
for (var i = 0; i <= a; i++) {
if (!isNaN(x) && !isNaN(y)) {
if (x <= y) {
var z = (y - x) + 1;
$quantity.val(z * (a + 1));
$rangeList.html('');
for (var b = z; b > 0; b--) {
var c = ((y - b) + 1);
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(String.fromCharCode(65 + i) + c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
}
} else if (!isNaN(x) && !isNaN(y)) {
if (x < y) {
var z = (y - x) + 1;
$quantity.val(z);
$rangeList.html('');
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
result.push(c);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
} else {
$rangeList.html('');
$quantity.val(0);
}
$rangeList.html('');
for (var i = 0; i < result.length; i++) {
$rangeList.append(result[i] + '<br />');
}
}
function leadingZeroes(number, size) {
number = number.toString();
while (number.length < size) number = "0" + number;
return number;
}
This is perfect for a recursive algorithm:
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
return result;
}
Called as follows:
createRange('BC01', 'DE02'); // Generates an array containing all values expected
EDIT: Amended function below to match new test case (much more messy, however, involving lots of type coercion between strings and integers).
function prefixZeroes(value, digits) {
var result = '';
value = value.toString();
for (var i = 0; i < digits - value.length; i++) {
result += '0';
}
return result + value;
}
function createRange(from, to) {
if (from.length === 0) {
return [ "" ];
}
var result = [];
if (from.charCodeAt(0) < 65) {
fromInt = parseInt(from);
toInt = parseInt(to);
length = toInt.toString().length;
var innerRange = createRange(from.substring(length), to.substring(length));
for (var i = fromInt; i <= toInt; i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(prefixZeroes(i, length) + innerRange[j]);
}
}
} else {
var innerRange = createRange(from.substring(1), to.substring(1));
for (var i = from.charCodeAt(0); i <= to.charCodeAt(0); i++) {
for (var j = 0; j < innerRange.length; j++) {
result.push(String.fromCharCode(i) + innerRange[j]);
}
}
}
return result;
}
Please note that because of your strict logic in how the value increments this method requires exactly 4 characters (2 letters followed by 2 numbers) to work. Also, this might not be as efficient/tidy as it can be but it took some tinkering to meet your logic requirements.
function generate(start, end) {
var results = [];
//break out the start/end letters/numbers so that we can increment them seperately
var startLetters = start[0] + start[1];
var endLetters = end[0] + end[1];
var startNumber = Number(start[2] + start[3]);
var endNumber = Number(end[2] + end[3]);
//store the start letter/number so we no which value to reset the counter to when a maximum boundry in reached
var resetLetter = startLetters[1];
var resetNumber = startNumber;
//add first result as we will always have at least one
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
//maximum while loops for saefty, increase if needed
var whileSafety = 10000;
while (true) {
//safety check to ensure while loop doesn't go infinite
whileSafety--;
if (whileSafety == 0) break;
//check if we have reached the maximum value, if so stop the loop (break)
if (startNumber == endNumber && startLetters == endLetters) break;
//check if we have reached the maximum number. If so, and the letters limit is not reached
//then reset the number and increment the letters by 1
if (startNumber == endNumber && startLetters != endLetters) {
//reset the number counter
startNumber = resetNumber;
//if the second letter is at the limit then reset it and increment the first letter,
//otherwise increment the second letter and continue
if (startLetters[1] == endLetters[1]) {
startLetters = '' + String.fromCharCode(startLetters.charCodeAt(0) + 1) + resetLetter;
} else {
startLetters = startLetters[0] + String.fromCharCode(startLetters.charCodeAt(1) + 1);
}
} else {
//number limit not reached so just increment the number counter
startNumber++;
}
//add the next sequential value to the array
results.push(startLetters + (startNumber < 10 ? "0" + startNumber : "" + startNumber));
}
return results;
}
var results = generate("BC01", "DE01");
console.log(results);
Here is a working example, which uses your second test case
Using #Phylogenesis' code, i managed to achieve my goal.
jsFiddle demo
function updateQuantity() {
var x = parseInt($from.val().match(/\d+/));
var y = parseInt($to.val().match(/\d+/));
var xl = $from.val().match(/[a-zA-Z]+/);
var yl = $to.val().match(/[a-zA-Z]+/);
var result = new Array();
var r = createRange(xl[0], yl[0]);
var z = (y - x) + 1;
if (x <= y) {
for (var j = 0; j < r.length; j++) {
var letters = r[j];
for (var i = z; i > 0; i--) {
var c = (y - i) + 1;
if ($leadingzeros.prop('checked')) {
c = leadingZeroes(c, y.toString().length);
}
if (i == z) {
r[j] = letters + c + '<br />';
} else {
j++;
r.splice(j, 0, letters + c + '<br />');
}
}
}
} else {
for (var i = 0; i < r.length; i++) {
r[i] += '<br />';
}
}
$quantity.val(r.length);
$rangeList.html('');
for (var i = 0; i < r.length; i++) {
$rangeList.append(r[i]);
}
}
This works for unlimited letters and numbers, as long as the letters are first.
Thanks for your help!

Categories

Resources