while loop javascript logic [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can anybody explain this while loop for me? It part of the roman numeral challenge on free code camp - it's not mine, I did my own but it was much more code. I'm trying understand this one to improve my own. Anyway, the while loop is totally throwing me. Any help would be awesome.
function romans(num){
var roman = "";
var romanNumerals = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
var numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
for (var i=0; i<numbers.length; i++) {
//If the num was 5 then then it would read 5 greater than 1000?
while (num >= numbers[i]) {
roman = roman + romanNumerals[i]
//5 minus 1000?
num = num - numbers[i]
}
}
return roman;
}
console.log(romans(5))

num starts as the desired input, then you find the numbers that add up to num, starting at the biggest roman numeral (numbers[0]).
You repeat with the while loop because you might need multiple copies of the letter (i.e. "III" == 3)
romans(5) will not trigger the while loop until numbers[10] (because as you say 5 >= 1000 == false,) at this point you append the character V to roman, and subtract 5 from num. The while loop will never again trigger since num is now 0.
Try thinking through it with romans(3001) and you will see the while loop trigger 3 times for M/1000, then get skipped 10 times, then trigger once for I/1

function romans(num){
var roman = "";
var romanNumerals=["M","CM","D","CD","C","XC","L","XL","X",
"IX","V","IV","I"];
var numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
for (var i=0; i<numbers.length; i++){
//If the num was 5 then then it would read 5 greater than 1000?
console.log("comparing: " + numbers[i]);
console.log(" with: " + num);
while(num >= numbers[i]){
console.log("entered");
roman = roman + romanNumerals[i]
//5 minus 1000?
num = num - numbers[i]
console.log('subtracting: ' + numbers[i]);
}
}
return roman
}
console.log(romans(44))
It will go down the line of numbers until it finds one that is smaller: for example 44:
In the for it'll go through the numbers array until it finds a number then 44 (during the iterations before the while loop is never entered).
When it finds a number smaller then 44 it enters the while loop and takes the romanNumerals at the position of i in that iteration, in this case 40. Then it lowers the original number by 40 (44-40=4) and then exits the loop going back into the for to search for a number lower then 4.

Related

how to add 1 in last item of array in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am solving one problem .but getting correct output for small array but my solution fail when array size is large
solution
/**
* #param {number[]} digits
* #return {number[]}
*/
var plusOne = function(digits) {
let str = parseInt(digits.join(''))+1+''
return str.split('')
};
Question
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
above cases are passed
failed cases
Input
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
let str = parseInt(digits.join(''))+1+''
With too many array elements, you are simply creating a number that is outside of the integer range here.
An implicit conversion to a float has to happen, and with that you get the inherent loss of precision - which then leads to several zeros in those places at the end, when you reverse the process.
Access the last array element specifically, and add 1 to the value. But if that last element had the value 9 already, you will of course have to repeat that same process for the previous one … basic application of “carry the one”.
var input = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9];
var output = [];
// loop over input array in reverse order
for(var i=input.length-1, toadd = 1; i>-1; --i) {
// add value `toadd` to current digit
var incremented = input[i] + toadd;
if(incremented < 10) {
output.unshift(incremented); // add to front of output array
toadd = 0; // reset toadd for all following digits, if we had no overflow
}
else {
output.unshift(0); // overflow occurred, so we add 0 to front of array instead
}
}
console.log(output)
This does take an “overflow” for 9 digits at the end into account; it does not handle the case when all digits are 9 though, if you need to handle that edge case as well, please implement that yourself.
This one recursively checks the last digits:
const test1 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
const test2 = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,9]
const plusOne = function(digits) {
if(digits[digits.length - 1] === 9){
digits = [...plusOne(digits.slice(0, -1)), 0]
}else{
digits[digits.length - 1]++
}
return digits;
};
console.log(plusOne(test1));
console.log(plusOne(test2));
You could do something like this :
var arr = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3,9,9]
function plusOne(index){
if( index < 0 ) return ; // Base case
if(arr[index] === 9){
arr[index] = 0;
plusOne(index-1); // For carry ahead
}else{
arr[index] += 1
}
}
plusOne(arr.length-1) // start with last digit

Algorithm to convert any string to a 1-3 digit number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to make an algorithm, for a NodeJS app, that converta any given string to a 1 to 3 digit number (better if the number is between 1-500).
e.g
ExampleString -> 214
Can anyone help me find a good solution?
EDIT:
I want to get a crime coefficient number from a username (string).
Ok, you can use JS function to get charCode of letter
let str = "some string example";
let sum = 0;
for (let i=0; i<str.length; i++) {
sum += parseInt(str[i].charCodeAt(0), 10); // Sum all codes
}
// Now we have some value as Number in sum, lets convert it to 0..1 value to scale to needed value
let rangedSum = parseFloat('0.' + String(sum)); // Looks dirty but works
let resultValue = Math.round(rangedSum * 500) + 1; // Same alogorythm as using Math.random(Math.round() * (max-min)) + min;
I hope it helps.
So as you are using nodejs, you can use crypto library to get md5 hash of string and then get it as HEX.
const crypto = require('crypto');
let valueHex = crypto.createHash('md5').update('YOUR STRING HERE').digest('hex');
// then get it as decimal based value
let valueDec = parseInt(valueHex, 16);
// and apply the same algorythm as above to scale it between 1-500
function coeficient() {
return Math.floor(Math.random() * 500) + 1;
}
console.log(coeficient());
console.log(coeficient());
console.log(coeficient());

How can I find the sum of each individual element in an array of long numbers? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
This question will need to be answered in Javascript.
For example, I have an array of phone numbers:
var phoneNumbers = ['123-434-4455', '123-495-8475', '484-728-3456'];
The phone number at index 0 (123-434-4455) would be added as 1+2+3+4+3+4+4+4+5+5, totaling to 35.
I'm guessing this will involve some kind of loop (for loops, or the method .forEach), because I will need to do this for multiple phone numbers in an array that will probably be randomly generated by a computer, so length and amount will vary.
Also, I'm wondering if the hyphen will matter, in which case I have found .replaceAll("-","");.
I've researched some other methods on here that involve .split, .parsInt, .map, .toString, .reduce, .digitSum, and more. They seem pretty complicated, especially since I'm in a beginning course (however I'm totally new to programming - this is my first post btw). Also, I'd rather not post the full question because I really want to figure it out alone, but this is the part I'm most stuck on. Forgive me if this has been answered previously! Like I said...new to programming.
I also need to determine which phone number has the last largest sum of digits, and use a return statement to return the required phone number in its’ original form.
You can use map and reduce array methods:
['123-434-4455', '123-495-8475', '484-728-3456'].map(function(str) {
return str.split('').reduce(function(a,b) {
return a + (+b || 0);
}, 0);
}); // [ 35, 48, 51 ]
Some notes:
split('') splits a string into an array of characters
+b coerces b into a number, e.g. "5" to 5 and "-" to NaN.
+b || 0 will return 0 if +b is falsy (0 or NaN), and +b otherwise
This code will do it:
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
for (var i=0; i<phoneNumbers.length; i++) {//For every phone number
var total=0; //create a total variable
var indNumbers = phoneNumbers[i].replace(/-/g, ""); //remove all dashes
for (var j=0; j<indNumbers.length; j++) {//loop for all digits
total+=parseFloat(indNumbers[j]);//add each digit to total
}
console.log(total);//do stuff with it here
}
All pretty standard javascript stuff. Only confusing bit I might have used is the .replace method - my parameter is /-/g which might look scary, but it's the equivalent of passing in "-" except it tells the function to replace ALL instances of the dash. If you do pass "-", it only replaces the first instance.
If you're a beginner, the things in this code you'll want to learn about are .replace, parseFloat for loops, and accessing strings using square bracket notation.
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
function crossSum(arr, pos) {
var sum = 0;
var a = arr[pos].split("-").join("").split("");
a.forEach(function(e, i) {
sum += parseInt(a[i]);
})
return sum;
}
document.write(crossSum(phoneNumbers, 0));
This function will return the cross-sum of
your phone-number.
Just use crossSum(phoneNumers, 0) // 0 is the fist number of phoneNumbers.
This will return the crossSum.
Adding on #millerbr answer. If you don't want to use .replace you can just use parseInt/parseFloat on every char, if it is not a number those functions returns NaN which can be checked with isNaN() function
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
for (var i=0; i < phoneNumbers.length; i++) { //For every phone number
var total=0; //create a total variable
for (var j=0; j < phoneNumbers.length; j++) { //loop for all digits
var parsedNumber = parseInt(phoneNumbers[j]); // parse string to number or NaN if "-"
if (!isNaN(parsedNumber)) { // Check if result is NaN (Not a Number).
total += parsedNumber; //add each digit to total
}
}
console.log(total);//do stuff with it here
}
Assuming that phoneNumbers is an array of strings, you can indeed loop through the entire array and then in each element in the array you can loop through the string and check if the character is a number. If so, add it to your sum and then when you finish each element in the array you have the total sum for it and you can add it to another array full of your sums.

Check lines A and count it until it changes to lines B javascript

I am sorry in advance if my title is somehow misleading and I am really sorry for my English if you wouldn't understand me, it's just not my native language!
I will try to explain as better as I can about what I try to achieve. I try to do this for past two entire days and I really need your help!
Let's say I have array with the following numbers:
2 4 6 8 10 1 3 5 2 4
I am trying to count how many even and odd numbers are here in a row, and when even/odd changes - count it again. So my answer from the array above should be:
5 (5 even numbers in a row) 3 (3 odd lines in a row) (2 even lines in a row)
Also when the counting isn't stopped it should post "<br>" instead of counted evens/odds, so it could show me results one time near to each line.
Check this example image:
I have this script which is counting, but it has a few issues: when number is even, it shows counting twice. Next, I can't figure it out how to add <br> to these lines where counting and add result only at the last line of counting. Also my counting result should be at the top, so the script should count from the end as I guess, and when I try i-- it starts the infinite loop...
var digits = ["2, 4, 6, 8, 10, 1, 3, 5, 2, 4"]
var evenCount=1, oddCount=1;
for(var i =0; i < digits.length; i++){
if(digits[i] % 2 ==0){
var oddCount=1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
}
else
var evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
Check my fiddle to see it in action:
https://jsfiddle.net/xk861vf9/8/
First, I think your code show counting twice because you misses two '{' after "for loop" and "else". After I fix the code format, I don't see it counting twice anymore.
$(document).ready(function() {
$("#sub").bind("click", function() {
$("#res").html("");
var digits = $('#content').find("span").map(function() {
return $(this).text();
});
var evenCount = 1;
var oddCount = 1;
for(var i =0; i < digits.length; i++) {
if (digits[i] % 2 ==0) {
oddCount = 1;
$("#res").append(evenCount + " (l) <br>");
evenCount++;
} else {
evenCount=1;
$("#res").append(oddCount + " (n) <br>");
oddCount++;
}
}
});
});
Second, they are many ways to implement that. Take a look at this jsfiddle code as an example.
https://jsfiddle.net/xk861vf9/11/
The concept is to print the counted number after even/odd number changes. Then use for loop to print <br> x times (counted number - 1) so if counted number is 4, there will be 3 <br> tags followed.We also have to check if current number is the last number in array and print the counted number or else the last counted number will be skipped.
Hope this help! :)
Ps. Sorry for my bad English, not my native language too.

Counter variable in for/loop. Why does one program work and the other fails? [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 7 years ago.
So, in writing a program - in javascript - that sums numbers from 1 to N (number given by user), I have written a working program, but I am still confused as to why one proposed solution that I wrote works, and the other doesn't.
This version works:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = 0;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
This one does not:
function spitback(){
var theNum = prompt("Give me a number");
var onwards = theNum;
for(i = 0; i <= theNum; i++){
onwards += i;
}
console.log(onwards);
}
spitback();
Why doesn't the second one work? If I initially set var onwards as theNum (inputted by a user) and then have the function add onwards to the iterations of 'i' up until the counter reaches theNum, I will see a concatenation between theNum and all the iterations of i next to it, like it is a string. In my mind, setting a variable to the same value and then having that value change to add the counter's iteration should work! Why doesn't it work? Please share.
This is because prompt returns a string, not a number. And when you use "+" operation on a string, you get concatenation, not integer increment. Javascript will not magically convert your string into integer even if it looks like it.

Categories