targeting the last item in an array in javascript - javascript

I got a function that's half working:
function prevTrack() {
if (playlist_index == (playlist.length - 0)) {
playlist_index = -1;
} else {
playlist_index--;
}
playlist_status.innerHTML = playlist[playlist_index];
audio.src = dir + playlist[playlist_index] + ext;
audio.play();
}
I'm sure the error is in the playlist_index = -1;
can anyone please tell me how to target the last item in the array?
so it would be playlist_index = ???;

Setting the index to -1 to get the last element reminds me of python ... in any case that doesn't work in JS. You have to set the index to playlist.length - 1.

i think playlist_index = playlist.legth - 1

Do you want to set the playlist_index to the last item in the array if the index is zero or the first item in the array?
const playlist_index = playlist_index === 0
? playlist_index = plalist.length - 1
: playlist_index--;
or
const playlist_index = playlist_index === firstValueOfArray
? playlist_index = playlist.length - 1
: playlist_index--;

It looks like you're trying to make the index go "around the world" so to speak. There is an easy way to do that with the modulo % operator.
const list = ['a', 'b', 'c']
for (let offset = 0; offset < 10; offset++) {
const item = list[offset % list.length];
console.log(item);
}
so you can replace
if (playlist_index == (playlist.length - 0)) {
playlist_index = -1;
} else {
playlist_index--;
}
with
playlist_index = (playlist.length + playlist_index - 1) % playlist.length;

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;
}

Iterate over uneven array

So I have a dataset of 16 items, I want to loop through them every 5 items after the first set of 6 so the columns are 6 5 5.
Initially I tried something like this, but then I remembered I had that one orphaned item.
if(thisI <= 6) {
y = prevtitle.position[0];
} elseif(thisI % 5 == 0) {
y = prevtitle.position[0] + w + (p *3);
} else {
y = prevtitle.position[0];
}
Not sure if there is a simple way to do the first 6 and then the next ones in five without a bunch of nested if statements.
Using Array#splice:
const splitArr = (arr = []) => {
const array = [...arr];
const res = array.length ? [array.splice(0, 6)] : [];
while(array.length) res.push(array.splice(0, 5));
return res;
}
console.log( splitArr([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) );
Would a simple ternary expression work for you?
let num = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
num.forEach((n,i) => {
y = (i<=6 || i % 5 == 0) ? prevtitle.position[0] : prevtitle.position[0] + w + (p *3) ;
})
I presume that you're skipping the first position, and jumps directly to the 6th position.
Just use a normal for loop.
Calculate the remainder for the number of steps that you will make. 16 % 5 results in 1 remainder.
step - countForZero + remainder sets the start point in the for loop.
i += step replaces the typical i++ in the for loop.
The method below can make any kind of leap, and it doesn't matter how many items there are in the array.
let num = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
function getEvery(step, arr) {
let newArr = [],
remainder = arr.length % step,
countForZero = 1;
for (let i = step - countForZero + remainder; i < arr.length; i += step) {
newArr.push(arr[i]);
}
return newArr;
}
console.log( getEvery(5, num) );

Persistent Bugger - Help to get rid of some 0

I need some help with a task which is about creating a function that only accepts integer numbers to then multiply each other until getting only one digit. The answer would be the times:
Example: function(39) - answer: 3
Because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4 and 4 has only one digit
Example2: function(999) - answer: 4
Because 9 * 9 * 9 = 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2
Example3: function(4) - answer: 0
Because it has one digit already
So trying to figure out how to solve this after many failures, I ended up coding this:
function persistence(num) {
let div = parseInt(num.toString().split(""));
let t = 0;
if(Number.isInteger(num) == true){
if(div.length > 1){
for(let i=0; i<div.length; i++){
div = div.reduce((acc,number) => acc * number);
t += 1;
div = parseInt(div.toString().split(""))
if(div.length == 1){
return t } else {continue}
} return t
} else { return t }
} else { return false }
}
console.log(persistence(39),3);
console.log(persistence(4),0);
console.log(persistence(25),2);
console.log(persistence(999),4);
/*
output: 0 3
0 0
0 2
0 4
*/
It seems I could solve it, but the problem is I don't know why those 0s show up. Besides I'd like to receive some feedback and if it's possible to improve those codes or show another way to solve it.
Thanks for taking your time to read this.
///EDIT///
Thank you all for helping and teaching me new things, I could solve this problem with the following code:
function persistence(num){
let t = 0;
let div;
if(Number.isInteger(num) == true){
while(num >= 10){
div = (num + "").split("");
num = div.reduce((acc,val) => acc * val);
t+=1;
} return t
}
}
console.log(persistence(39));
console.log(persistence(4));
console.log(persistence(25));
console.log(persistence(999));
/*output: 3
0
2
4
*/
You've got a few issues here:
let div = parseInt(num.toString().split("")); You're casting an array to a number, assuming you're trying to extract the individual numbers into an array, you were close but no need for the parseInt.
function persistence(input, count = 0) {
var output = input;
while (output >= 10) {
var numbers = (output + '').split('');
output = numbers.reduce((acc, next) {
return Number(next) * acc;
}, 1);
count += 1;
}
​
return count;
};
For something that needs to continually check, you're better off using a recurssive function to check the conditions again and again, this way you won't need any sub loops.
Few es6 features you can utilise here to achieve the same result! Might be a little too far down the road for you to jump into es6 now but here's an example anyways using recursion!
function recursive(input, count = 0) {
// convert the number into an array for each number
const numbers = `${input}`.split('').map(n => Number(n));
// calculate the total of the values
const total = numbers.reduce((acc, next) => next * acc, 1);
// if there's more than 1 number left, total them up and send them back through
return numbers.length > 1 ? recursive(total, count += 1) : count;
};
console.log(recursive(39),3);
console.log(recursive(4),0);
console.log(recursive(25),2);
console.log(recursive(999),4);
function persistance (num) {
if (typeof num != 'number') throw 'isnt a number'
let persist = 0
while(num >= 10) {
let size = '' + num
size = size.length
// Get all number of num
const array = new Array(size).fill(0).map((x, i) => {
const a = num / Math.pow(10, i)
const b = parseInt(a, 10)
return b % 10
})
console.log('here', array)
// actualiser num
num = array.reduce((acc, current) => acc * current, 1)
persist++
}
return persist
}
console.log(persistance(39))
console.log(persistance(999))
console.log() can take many argument...
So for example, console.log("A", "B") will output "A" "B".
So all those zeros are the output of your persistence function... And the other number is just the number you provided as second argument.
So I guess you still have to "persist"... Because your function always returns 0.
A hint: You are making this comparison: div.length > 1...
But div is NOT an array... It is a number, stringified, splitted... And finally parsed as integer.
;) Good luck.
Side note, the calculation you are attempting is known as the Kaprekar's routine. So while learning JS with it... That history panel of the recreational mathematic wil not hurt you... And may be a good line in a job interview. ;)
My best hint
Use the console log within the function to help you degug it. Here is your unchanged code with just a couple of those.
function persistence(num) {
let div = parseInt(num.toString().split(""));
let t = 0;
console.log("div.length", div.length)
if (Number.isInteger(num) == true) {
if (div.length > 1) {
for (let i = 0; i < div.length; i++) {
div = div.reduce((acc, number) => acc * number);
t += 1;
div = parseInt(div.toString().split(""));
if (div.length == 1) {
console.log("return #1")
return t;
} else {
continue;
}
}
console.log("return #2")
return t;
} else {
console.log("return #3")
return t;
}
} else {
console.log("return #4")
return false;
}
}
console.log(persistence(39), 3);
console.log(persistence(4), 0);
console.log(persistence(25), 2);
console.log(persistence(999), 4);

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 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;
};
}

Categories

Resources