What is the Logic behind " i = (i + 1) % word.length " - javascript

Im new to Coding. can someone explain ("i = (i + 1) % word.length")
var text = document.querySelector('#text-wrap');
var word = text.getElementsByTagName('span');
var i = 0;
function run(){
word[i].style.display = 'none';
i = (i + 1) % word.length
word[i].style.display = 'initial';
}
setInterval(run,800)

if (i < word.length - 1):
  i = i + 1; // increment
else if (i == word.length - 1):
  i = 0; // go back to 0
For example, if word.length is 5 and the initial i is 0, then
the output sequence of i is 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, ....

It resets i to 0 ( to select the first word ) after the last word is selected.
var text = document.querySelector('#text-wrap');
var word = text.getElementsByTagName('span');
var i = 0;
function run(){
// hide i-th word
word[i].style.display = 'none';
// set i to
// if the last word is selected select the first word ( reset to 0 )
i = (i + 1) % word.length
// display i-th word
word[i].style.display = 'initial';
}
setInterval(run,800)
I would not recommend doing it like this. An if statement is much clearer. This should do the same:
var text = document.querySelector('#text-wrap');
var word = text.getElementsByTagName('span');
var i = 0;
function run(){
word[i].style.display = 'none';
if( i+1 !== word.length )
i++;
else // if i+1 === word.length
i = 0;
word[i].style.display = 'initial';
}
setInterval(run,800)
Still you shouldn't use i as a global variable. At least use a variable name that is incredibly unlikely to exist in other code instead.
a quick modulus explanation
the modulus is what is leftover when you cannot iteratively remove an amount. Some examples:
6 % 2 = 0 ( 6 - 2 - 2 - 2 = 0)
5 % 2 = 1 ( 5 - 2 -2 = 1 )
1 % 2 = 1 ( cannot substract 2 from 1 so the value is 1 )
simplified example
var word = [ '1', '2', '3'];
var i = 0;
function run(){
console.log( word[i] );
if( i+1 !== word.length )
i++;
else // if i+1 === word.length
i = 0;
}
setInterval(run,1000);

Related

How to solve Jumping on the Clouds from Hacker Rank? JavaScript

I'm trying to solve the Jumping on the Clouds problem from Hackerrank, but even though it passes the Sample Test cases, it fails when submitting the code.
My code is as follow:
function jumpingOnClouds(c) {
var current;
var next;
var jumps = 0;
let potentialNext;
for(let i = 0; i < c.length; i++){
current=c[i];
next=c[i == c.length -1 ? 0 : i+1];
if(!next && next === 0){
jumps++;
potentialNext = c[ i == c.length -1 ? 0 : i+2];
if(potentialNext !== undefined && potentialNext === 1){
i = i + 1;
}
if(potentialNext !== undefined && potentialNext === 0){
i = i + 3;
}
}
if(next !== undefined && next === 1){
jumps++;
i = i + 2;
}
}
return jumps;
}
I can't figured what I am missing.
Your code didn't passed the "Sample Input 0". It returned 3, where 4 was expected.
I have modified your code, and it works for all input cases. I have left comments at places explaining the code.
function jumpingOnClouds(c) {
var current;
var next;
var jumps = 0;
let potentialNext;
let i = 0;
while(i < c.length){ //Use a while loop, since it gives more control on adding a dynamic value to a variable.
current = c[i];
if(i+2 < c.length && c[i+2] == 0){ //check if 2 clouds ahead from current index is jumpable or not
i+=2; //Set the current index to 2 places ahead
jumps += 1; //Make one jump
} else if(i+1 < c.length && c[i+1] == 0){ //Else Check if next cloud is jumpable or not
i+=1; //set current index to index of next cloud
jumps += 1; //Again, make one jump
} else i+= 1; //If none of above if conditions are satisfied, add 1 to index.
}
return jumps;
}
console.log(jumpingOnClouds([0, 0, 1, 0, 0, 1, 0])) //Sample Input 0
console.log(jumpingOnClouds([0, 0, 0, 0, 1, 0])) //Sample Input 1
I just finished this task and this is my code. I hope this can help you and I will explain the idea in comments. And I very appreciated if someone can tell me the more efficient code. Thank you.
function jumpOnTheClouds(c){
let path1 = []; //variable for 1 jump
let j = 0; //variable for index path1
let path2 = []; //variable for potential jump
let k = 0; //variable for index path2
let jump = 0; //variable for jump count
for(let i = 1;i < c.length;i++){ //I use for loop to count with +1 jump only, and start in index 1 because starting point always index 0
if(c[i] == 0){
path1[j] = i ; //If cloud not a thunderhead (0), path1 index j = index cloud
j++; //Set for next path1 index
}
}
for(let i = 1;i < c.length;i++){ //I use this for loop to count potential jump.
if(c[i + 1] == 0){ //Check if 2 clouds ahead not a thunderhead (0)
path2[k] = i + 1; //If 2 clouds ahead not a thunderhead (0), path2 index k = index cloud
i += 1 //Set index where we now
k++; //Set for next path2 index
}else if(c[i] == 0){
path2[k] = i; //If 2 clouds ahead is thunderhead (1), path2 index k = index cloud
k++; //Set for next path2 index
}
}
if(path1.length > path2.length){ //Screening for the less jump
jump = path2.length;
}else{
jump = path1.length;
}
return jump;
}

How to find a first occurrence of double digit number

So, I am pushing elements into array through prompt until getting 0. After that I am trying to find the first double digit number. For example if the array is [2,3,55,0] my program should return 55.
function findFirstDouble() {
var niz = []
var a = 1;
for (var i = 1; a != 0; i++) {
var unos = parseInt(prompt("Enter number :"))
niz.push(unos)
a = unos
}
alert(niz);
for (var i = 0; i < niz.length; i++) {
if (niz[i] / 10 > 0 && niz[i] / 100 == 0) {
console.log(niz[i]);
break;
}
else {
alert("No double digit numbers!")
break;
}
}
}
findFirstDouble();
Please use built in js function find.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Here is the solution
// I assume that you already have an array
const niz = [2,3,55,0]
const firstDoubleDigit = niz.find(num => num < 100 && num >= 10)
console.log(firstDoubleDigit)
Here is the answer I think you are looking for.
I omitted the array filling part.
Why would you do any kind of division if you just need to check every number and if the first one matches the criteria then you've got your double digit number hence exit the loop with break or return keyword.
var niz = [1, 2, 55, 13];
for (var i = 0; i < niz.length; i++) {
if (niz[i] > 9 && niz[i] < 100) {
console.log('Pronadeni broj je:', niz[i]);
break;
}
}
You can also convert to string: if (niz[i].toString().length===2){ // your number }
Easy way without math is just to convert it to a string.
const data = [2,3,55,0];
const res = data.findIndex(n=>`${n}`.length===2);
console.log(res > -1 ? "Exists at position " + res : "Doesn't exist");
Mathematically:
const data = [2,111,3,55,0];
const res = data.find(n=>n<100&&n>9);
console.log(res ? "Exists " + res : "Doesn't exist");

How find the length of the longest substring?

Need find the length of the longest substring that consists of the same letter. For example, line "aaabbcaaaa" contains four substrings with the same letters "aaa", "bb","c" and "aaaa".
i found two way to do that, but all not so good;
At first way i don't make check previos similar letters here sdsffffse;
Because i check only current element and second element if(line[i] === line[i+1]).
At second way i fail when i try to check how many aa i found in that string abababaab but in object i add all a letters and length = 5;
function longRepeat(line) {
let count = {};
let letter = [];
for (let i=0; i<line.length; i++) {
count[line[i]] = i;
if(line[i] === line[i+1]){
letter.push([line[i], line[i+1]])
}
}
/*
second way
for (let x of line) {
count[x] = ~~count[x] + 1;
} */
return letter;
}
console.log(longRepeat('sdsffffse')); f = 4
console.log(longRepeat('ddvvrwwwrggg')); = 3
console.log(longRepeat('abababaab')); // last two a = 2
Possible solution:
function longestSubstr(str) {
if (!str) return 0
let maxL = 1
let curL = 1
for (let i = 0; i < str.length - 1; i++) {
let cur = str[i]
let next = str[i + 1]
if (cur === next) {
curL++
} else {
if (maxL < curL) maxL = curL
curL = 1
}
}
if (maxL < curL) maxL = curL
return maxL
}
console.log(longestSubstr("abababaab")) // 2
If you don't mind using regular expressions.
function func(line) {
let reg = /(\w)\1+/g;
let longest = line.match(reg).sort((a, b) => {
a.length - b.length
}).pop();
console.log(line + ' : ' + longest);
}
func('ddvvrwwwrggg');
func('sdsffffse');
func('abababaab');
func('aaabbcaaaa');
func('aaaasdfbbbbyyyweryyyuurweuuuuuu');
/(\w)\1+/g will match a sequence of the same character, using the match() method we get all the sequences, sort them by length, and get the last item in the array, i didn't know what to do in case of equal length, so i'll leave that you, i'm merely presenting an idea, and it's for you to improve it :)
#python
def long_repeat(line):
line = line.lower()
max = 1
if len(line) == 0:
return 0
for i in range(0, len(line) - 1):
count = 1
while line[i] == line[i + 1]:
count += 1
if max < count:
max = count
if i < len(line) - 2:
i += 1
else:
break
return max

How do you make every 9th element in Math.random array to be the same element?[javascript]

I have this bit of code here
<script language='javascript' type='text/javascript'>
var imagesArray = ["1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png","9.png","10.png","11.png","12.png","13.png","14.png","15.png","16.png","17.png","18.png","19.png","20.png","21.png" ];
var newArray = new Array(100);
for (i = 0; i < 100; i++)
{
if (i % 9 === 0)
{
}
else
{
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
}
}
</script>
the idea behind is that i need it so that every 9th number that would be randomly chosen would remain the same, but i have no idea what do i put there so it would work.
Do you got any advice?
Thanks!
Here is a sample of what you can do :
First fill your array with Math.random() or whatever you want.
imagesArray[i] = Math.floor((Math.random() * 10) + 1);
If you want the value to be the same every 9 elements , use a loop starting at 9 and going through every 9 elements with i+9
for(var i = 9; i < yourArray.length ; i = i + 9){
imagesArray[i] = imagesArray[9];
}
Actually you can start the loop at 18 as well
Demo
Try defining a variable outside of for loop to store value at first i % 9 === 0
var newArray = new Array(100), ninth = null;
for (i = 0; i < 100; i++) {
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
if (i % 9 === 0 && ninth === null && i === 9) {
ninth = newArray[i]
};
if (i % 9 === 0 && i >= 9) {
newArray[i] = ninth;
};
}

A while loop to add the digits of a multi-digit number together? (Javascript)

I need to add the digits of a number together (e.g. 21 is 2+1) so that the number is reduced to only one digit (3). I figured out how to do that part.
However,
1) I may need to call the function more than once on the same variable (e.g. 99 is 9+9 = 18, which is still >= 10) and
2) I need to exclude the numbers 11 and 22 from this function's ambit.
Where am I going wrong below?
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i];
};
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
};
} else {
xResult = x;
};
console.log(xResult);
//repeat while loop for y and z
Here are the problems with your code
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i]; // indentation want awry
}; // don't need this ; - not a show stopper
// you're not returning anything!!!!
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
}; // ; not needed
// because x never changes, the above while loop would go on forever
} else { // this else has no if
xResult = x; // even if code was right, x remains unchanged
};
console.log(xResult);
Hope that helps in some way
Now - here's a solution that works
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
while (num > 9) {
if (num == 11 || num == 22) {
return num;
}
var proc = num.toString().split("");
num = proc.reduce(function(previousInt, thisValueString) {
return previousInt + parseInt(thisValueString);
}, 0);
}
return num;
}
console.log(numberMagic(x));
console.log(numberMagic(y));
console.log(numberMagic(z));
I'm not sure to understand what you want..
with this function you reduce any number to one single digit
while(num > 9){
if(num == 11 || num == 22) return;
var proc = num.toString();
var sum = 0;
for(var i=0; i<proc.length; i++) {
sum += parseInt(proc[i]);
}
num = sum;
}
is it what you are looking at?
I wrote an example at Jsfiddle that you can turn any given number into a single digit:
Example input: 551
array of [5, 5, 1] - add last 2 digits
array of [5, 6] - add last 2 digits
array of [1, 1] - add last 2 digits
array of [2] - output
Here is the actual code:
var number = 1768;
var newNumber = convertToOneDigit(number);
console.log("New Number: " + newNumber);
function convertToOneDigit(number) {
var stringNumber = number.toString();
var stringNumberArray = stringNumber.split("");
var stringNumberLength = stringNumberArray.length;
var tmp;
var tmp2;
var tmp3;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
while (stringNumberLength > 1) {
tmp = parseInt(stringNumberArray[stringNumberLength - 1]) + parseInt(stringNumberArray[stringNumberLength - 2]);
stringNumberArray.pop();
stringNumberArray.pop();
tmp2 = tmp.toString();
if (tmp2.length > 1) {
tmp3 = tmp2.split("");
for (var i = 0; i < tmp3.length; i++) {
stringNumberArray.push(tmp3[i]);
}
} else {
stringNumberArray.push(tmp2);
}
stringNumberLength = stringNumberArray.length;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
}
return stringNumberArray[0];
}
function addDigits(n) {
let str = n.toString().split('');
let len = str.length;
let add,
acc = 0;
for (i=0; i<=len-1; i++) {
acc += Number(str[i]);
}
return acc;
}
console.log( addDigits(123456789) ); //Output: 45
Just make it a While loop, remember a While loops it's just the same as a For loop, only you add the counter variable at the end of the code, the same way you can do with a Do{code}while(condition) Only need to add a counter variable at the end and its gonna be the same. Only that the variable its global to the loop, I mean comes from the outside.
Ej.
let i = 0; //it's global to the loop, ( wider scope )
while (i<=x) {
//Code line;
//Code line;
//Code line;
//Code line;
i++
}
Now this is working with an outside variable and it's NOT recommended.. unless that var its local to a Function.
Please look at the this solution also
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var total = 0;
while (num != 0) {
total += num % 10;
num = parseInt(num / 10);
}
console.log(total);
if (total > 9)
numberMagic(total);
else
return total;
}
//Call first time function
numberMagic(z);

Categories

Resources