Check the last digit of a number - javascript

I was doing some basic linear search exercises (I've been coding for 2 months or so) with javascript and stumbled upon the following problem:
I get input from the user that goes to an array and the program tells in which position of the array the number they decided to retrieve is. I wanted to do something clean like "I've retrieved the number 69 for you. It was on the 22nd position of the array of inputs you created."
So I wanted to check the last digit of the number and respond accordingly with X1st, X2nd and X3rd or Xth.
But I don't know how to check the last digit of the desired number. Should I convert it into a string and then check with the .pop() function?
I only accounted for 30 inputs. But I would like for it to work not depending on a set number of inputs.
let inputsArray = [];
let totalInputs;
do
{
totalInputs = Number(prompt("How many number do you want to input? (max. 30)"));
}
while(totalInputs >= 31 || totalInputs <= 0)
for(i = 0; i < totalInputs; i++) //Get the inputs from the user and add them into the inputsArray
{
let input = Number(prompt("Type a number"));
inputsArray.push(input);
}
let desiredNum = Number(prompt(`What number do you want to retrieve? (Select from ${inputsArray})`));
let validator = 0;
for(i = 0; i < inputsArray.length; i++) //Check on each index of the inputsArray for the number prompted
{
if(inputsArray[i] == desiredNum)
{
if (i + 1 == 1 || i + 1 == 21) //Tell the user which position in the array the prompted number was
{
alert(`I've retrieved the number ${desiredNum} for you. It was on the ${i+1}st position on the array of numbers you created.`);
validator++;
}
else if (i + 1 == 2 || i + 1 == 22)
{
alert(`I've retrieved the number ${desiredNum} for you. It was on the ${i+1}nd position on the array of numbers you created.`);
validator++;
}
else if (i + 1 == 3 || i + 1 == 23)
{
alert(`I've retrieved the number ${desiredNum} for you. It was on the ${i+1}rd position on the array of numbers you created.`);
validator++;
}
else
{
alert(`I've retrieved the number ${desiredNum} for you. It was on the ${i+1}th position on the array of numbers you created.`);
validator++;
}
}
}
if(validator != 1) //If the desiredNum is invalid
{
alert("The number you specified does not exist in the array.");
}

What if you tried a modulo operator like
last_digit = number % 10;

Yes, the easiest way would be just convert to string:
var str_number = number.toString(); //converts number to string
var last_char = str_number.slice(-1); //gets last character
var last_digit = +(last_char); //convert last character to number

No need to convert to string. Let's just address what we are looking for with the number. The case is either 0, 1, 2, or other; the +1 you use is not necessary for computing this.
You can use % (modulo) here in order to check what the last digit is. Ensure that it avoids the edge case of 12nd with an extra condition.
This will allow for a single response to be issued instead of looking at multiple cases.
var desiredNum = 20;
var suffixes = ["st","nd","rd"];
var suffix = num => (num < 4 || num > 13) && suffixes[num%10] ? suffixes[num%10] : "th";
for(let i = 0; i < 56; i+=11)
console.log(`I've retrieved the number ${desiredNum} for you. It was on the ${(i+1)+suffix(i)} position on the array of numbers you created.`);

Related

Why are these numbers not summing in a for loop using javascript?

I'm iterating over a range, extracting 2 texts (to be converted into numbers) and summing them to put the total back into the stirng later.
However, although I see the numbers logged ok, the sums give me NaN as the results.
Here's the code piece:
var totalPriceToPay = 0;
var totalCODAmount = 0;
if (ss.getActiveSheet().getName() == sheet.getName() && row > 1) {
for (var a = 0; a < dataRng.length; a++) {
if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {
//Isolate the Price to Pay Amounts to be summed and put the total back into the string.
const str = dataRng[a][35].toString();
const priceToPay = str.split(",").slice(8, 9)[0] //Extracts 8th element
totalPriceToPay += Number(priceToPay) //Converts it into a nº and sums to the total
const codAmount = str.split(',').slice(9, 10)[0] //Extracts the 9th element
totalCODAmount += Number(codAmount) //Converts it into a nº and sums to the total
Logger.log('Type Price To Pay: ' + str.split(",").slice(8, 9)[0]);
Logger.log('Type codAmount: ' + str.split(",").slice(9, 10)[0]);
Logger.log('Total Price to Pay: ' + totalPriceToPay);
Logger.log('Total COD: ' + totalCODAmount);
Here are the logs:
Thanks.
The numbers have a $ before it. You need to remove it. Use String.slice:
const priceToPay = Number(str.split(",")[8].slice(1));
The Number() constructor will give NaN when the value cannot be converted to a number. When you add NaN to a number, you get NaN. To avoid the issue, use this pattern:
totalPriceToPay += Number(priceToPay) || 0;
totalCODAmount += Number(codAmount) || 0;

JavaScript to check which one of the given numbers differs from other

I am stuck on a problem. I want to print the index of an array which differs from other elements of that array in evenness. To be more specific the input would be like 5 even numbers and 1 odd number. So print the position(index+1) of odd number.
My code
function Test(numbers){
var e = 0; //number of even numbers
var o = 0; //number of odd numbers
console.log(numbers.length);
for(var i = 0; i < numbers.length; i++){
if(numbers[i] % 2 == 0){
e++;
var pose = i; //index of even no
}
else{
o++
var poso = i; //index of odd number
}
}
if(e==1){ //only one even number
console.log(pose+1);
}
else if(o==1){ //only one odd number
console.log(poso+1);
}
else{
console.log("no number differs");
}
}
Test("2 4 7 8 6");
Expected output = '3';
The console prints :
"no number differs".
I have debugged and I found the problem. The console.log(numbers.length); is printing 9. That is it is including blank spaces as well. Same if we put comma ',' in between the numbers. Also if there is a two digit number it treats them as 2 separate elements.
Now I know that i can add code at the beginning to check if i=1,3,5... to break the loop but I would like to know if there is a better solution. Also if the solution is passing array in different format I would like to know how can we correct the code if we want to pass as above.
Pass an array as an argument like below.
function Test(numbers){
var e = 0; //number of even numbers
var o = 0; //number of odd numbers
console.log(numbers.length);
for(var i = 0; i < numbers.length; i++){
if(numbers[i] % 2 == 0){
e++;
var pose = i; //index of even no
}
else{
o++
var poso = i; //index of odd number
}
}
if(e==1){ //only one even number
console.log(pose+1);
}
else if(o==1){ //only one odd number
console.log(poso+1);
}
else{
console.log("no number differs");
}
}
var x = [2,4,7,8,6];
Test(x);
Your Program is absolutely fine.
I guess the problem is with how you are passing data to your function Test.
You are passing a string instead of array.
it should be like:
Test([2,4,7,8,6]);
Also If you want to pass it as string just make sure you split the String with ',' comma and make an array of the numbers and then feed it to your for loop.
In your code you are passing the argument as a string, but I guess you may need to pass an array.
If it is so then you can look into array#forEach method
Hope this snippet will be useful
function Test(numbers) {
// looping through the array
numbers.forEach(function(item, index) {
//checking if it is odd or even
if (item % 2 == 0) {
console.log("current number is Even & its index is " + index);
} else {
//updating index
var modIndex = index+1;
console.log("current number is Odd & its modified index is " + modIndex);
}
})
}
var num = ['2','4','7','8','6']
Test(num);
DEMO

using a for loop in javascript write a code that prompts the user to enter any amount of numbers the print the largest and smallest of those numbers

new to JS, here's the problem, code to ask user to enter any amount of numbers -1 to end, find and display the largest and smallest; it's working except that it displays the smallest as the largest but the largest displays
fine??
var numInputs = parseInt(prompt("Please enter numbers seperated by
a space end with -1"))
var largestNum =0;
var smallestNum = 9999;
if (numInputs >0)
{
for (i=1; i<=numInputs; i++)
{
if (numInputs > largestNum)
{
largestNum = numInputs;
}
}
}
alert("The largest number entered was " + largestNum);
if (numInputs >0)
{
for (i=1; i<=numInputs; i++)
{
if (numInputs < smallestNum)
{
smallestNum = numInputs;
}
}
}
alert("The smallest number entered was " + smallestNum);
How about refactoring your code a bit here. We remove the parseInt since it dosent work and the take the entered numbers split them by a space making an array out of it sorting the array then just poping and shifting numbers from it which just removes the last and first number respectively.
Here is an example.
Code:
var numbers = prompt("please enter a range of numbers separated by a space:");
var arrayOfNumbers = numbers.split(" ").sort();
alert("Lowest entered number:" + arrayOfNumbers.pop() + "\n highest entered number: " + arrayOfNumbers.shift());
The problem with your code is that numInputs only parses the first number you put. so if you put the string "1 2 3 4 5 -1", numInputs gets the value 1.
Here is a code snippet that will fix your problem:
var largestNum, smallestNum;
var numInput = parseInt(prompt("Please enter the next number (-1 to exit)"));
if (numInput != -1) {
largestNum = numInput;
smallestNum = numInput;
}
while (numInput != -1) {
if (numInput > largestNum) {
largestNum = numInput;
} else if (numInput < smallestNum) {
smallestNum = numInput;
}
numInput = parseInt(prompt("Please enter the next number (-1 to exit)"));
}
alert("Smallest number is " + smallestNum + ", largest number is " + largestNum);
as you can see, I update the smallest and largest numbers as I get them, in real-time, and not after I get all the input.
Also, I set the first number as both the smallest and largest one, for simplicity (not working with fixed values as 0 and 9999, which may be wrong).
Lastly, I did a prompt separately for each number, so you can't input them all together. To do that, you're gonna have to split the string and store in an array, and iterate over the array elements.
You code doesn't make too much sense.
numInputs will be a string(numbers separated by space), you need to parse it intro an Array, like:
numInputs = prompt("Please enter numbers...")).split(" ");
Then you should loop through Array and check for max and minimum numbers, like :
var smallestNum = numInputs[0];
var largestNum = numInputs[0];
for(var i=0; i<numInputs.length; i++) {
if (smallestNum > numInputs[i]) {
smallestNum = numInputs[i];
} else if (largestNum < numInputs[i]) {
largestNum = numInputs[i];
}
}
var a = [],
value;
value = parseInt(prompt("Please enter numbers seperated by a space end with - 1 "));
while (value !== -1) {
a.push(value);
value = parseInt(prompt("Please enter numbers seperated by a space end with - 1 "));
}
a.sort();
console.log(a);
alert("The largest number entered was " + a[a.length-1]);
alert("The smallest number entered was " + a[0]);
Edit:
If you want to sort numbers that are larger than 9, use :
a.sort(function(a,b){ return a - b });

Comparing 2 arrays to output total integer

I have 2 arrays of numbers. I want to go through each array and find the number of times 1 number from each array adds up to the particular amount x.
If the particular amount x is reached as many times as another set number n then the function should print 'YES'. If x does not reach the set number of n then the function should print 'NO'.
The values of x , n and both arrays are in a string input. These values have been split into arrays as seen below in the code.
I have set up 2 for loops to run through each array and an if statement that checks for the condition of x meeting n.
The arrays I'm using in this code should print out the result of 'YES' however every time I run the code I'm getting 'NO' ? I've tried tinkering with the code but nothing has worked.
Any idea on where this code is broke and how to fix the problem?
Thanks :)
code:
var input = '2\n3 10\n2 1 3\n7 8 9';
function processData(input) {
var inputArray = input.split('\n');
var n = inputArray[1][0];
var x = inputArray[1].split(' ')[1];
var arrayA = inputArray[2].split(' ');
var arrayB = inputArray[3].split(' ');
var total = 0;
for(var i = 0; i < arrayA.length; i++) {
for(var j = 0; j < arrayB.length; j++) {
if(arrayA[i] + arrayB[j] == x) {
total = total + 1;
} if (total == n) {
return 'YES';
}
}
}
return 'NO';
}
console.log(processData(input));
arrayA[i] and arrayB[j] are strings, so arrayA[i] + arrayB[j] will be the concatenation of them (ex: '2' + '3' === '23').
If your logic is correct (i didn't quite understand what you are trying to do), it should be enough to convert them to numbers before adding them, using parseInt or some other method:
if(+arrayA[i] + (+arrayB[j]) == +x) { // used unary + to convert to number
total = total + 1;
} if (total == n) {
return 'YES';
}
PS: A cleaner version would be to convert each string in the array to number, but that involves more than adding 3 characters to your code.
PS2: You have a weird way of getting the input data. If you get it from another place in your JS code, you could simply pass it as an object with the relevant structure, otherwise you could pass it around in a more ... common format, like JSON.

Javascript regular expressions problem

I am creating a small Yahtzee game and i have run into some regex problems. I need to verify certain criteria to see if they are met. The fields one to six is very straight forward the problem comes after that. Like trying to create a regex that matches the ladder. The Straight should contain one of the following characters 1-5. It must contain one of each to pass but i can't figure out how to check for it. I was thinking /1{1}2{1}3{1}4{1}5{1}/g; but that only matches if they come in order. How can i check if they don't come in the correct order?
If I understood you right, you want to check if a string contains the numbers from 1 to 5 in random order. If that is correct, then you can use:
var s = '25143';
var valid = s.match(/^[1-5]{5}$/);
for (var i=1; i<=5; i++) {
if (!s.match(i.toString())) valid = false;
}
Or:
var s = '25143';
var valid = s.split('').sort().join('').match(/^12345$/);
Although this definitely can be solved with regular expressions, I find it quite interesting and educative to provide a "pure" solution, based on simple arithmetic. It goes like this:
function yahtzee(comb) {
if(comb.length != 5) return null;
var map = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < comb.length; i++) {
var digit = comb.charCodeAt(i) - 48;
if(digit < 1 || digit > 6) return null;
map[digit - 1]++;
}
var sum = 0, p = 0, seq = 0;
for(var i = 0; i < map.length; i++) {
if(map[i] == 2) sum += 20;
if(map[i] >= 3) sum += map[i];
p = map[i] ? p + 1 : 0;
if(p > seq) seq = p;
}
if(sum == 5) return "Yahtzee";
if(sum == 23) return "Full House";
if(sum == 3) return "Three-Of-A-Kind";
if(sum == 4) return "Four-Of-A-Kind";
if(seq == 5) return "Large Straight";
if(seq == 4) return "Small Straight";
return "Chance";
}
for reference, Yahtzee rules
For simplicity and easiness, I'd go with indexOf.
string.indexOf(searchstring, start)
Loop 1 to 5 like Max but just check indexOf i, break out for any false.
This also will help for the small straight, which is only 4 out of 5 in order(12345 or 23456).
Edit: Woops. 1234, 2345, 3456. Sorry.
You could even have a generic function to check for straights of an arbitrary length, passing in the maximum loop index as well as the string to check.
"12543".split('').sort().join('') == '12345'
With regex:
return /^([1-5])(?!\1)([1-5])(?!\1|\2)([1-5])(?!\1|\2|\3)([1-5])(?!\1|\2|\3|\4)[1-5]$/.test("15243");
(Not that it's recommended...)
A regexp is likely not the best solution for this problem, but for fun:
/^(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5).{5}$/.test("12354")
That matches every string that contains exactly five characters, being the numbers 1-5, with one of each.
(?=.*1) is a positive lookahead, essentially saying "to the very right of here, there should be whatever or nothing followed by 1".
Lookaheads don't "consume" any part of the regexp, so each number check starts off the beginning of the string.
Then there's .{5} to actually consume the five characters, to make sure there's the right number of them.

Categories

Resources