i am trying to do project euler # 1 with Javascript in HackerRank. Can someone give me a hints in what's wrong with my code. the result is always zero.
I run my function in my google chrome console, then i input processData(10), it gives me 23. I input processData(100), it gives me 2318.
When i try to use my code in the console from Hacker rank, it output the result as zero, like it didn't pass the first test which is 0.
Did anyone tried to solve some problem in hackerrank in javascript?
function processData(input) {
var result = []
var total=0
function findMultipleThreeAndFive(n){
var i = 0;
for(i ; i < n ;i++){
if(i%3 == 0 || i%5 == 0){
result.push(i);
}
}
}
findMultipleThreeAndFive(input)
function sum(){
for(var j = 0; j< result.length ;j++){
total += result[j]
}
return total;
}
sum()
console.log(total)
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
First off all, your code works: http://jsfiddle.net/azggks5a/ , but I thought I would show you how I would solve it:
I suggest you use ES6 sets, because they handle the uniqueness of your values.
I began by iterating through the multiples I wanted. I then multiplied the iterated multiple by every number upto belowThis. If the result was lower than belowThis I added the result to the set, otherwise I didn't.
Here's the code:
var multiplesOf = [3,5];
var belowThis = 10;
var multiples = new Set();
var totalOfMultiples = 0;
multiplesOf.forEach(function(element, index){
for(var i=0;i<belowThis;i++) {
if(multiplesOf[index]*i<belowThis) {
multiples.add(multiplesOf[index]*i);
}
}
});
multiples.forEach(function(element, index){
totalOfMultiples+=element;
});
console.log(totalOfMultiples);
You can change the multiples you wish to check, and to solve the question you would increase belowThis to 1000, and get a result of 233168.
Related
I need very specific answer to this particular HackerRank problem : https://www.hackerrank.com/challenges/plus-minus/problem.
Why this code is passing all the test-cases ?
function plusMinus(arr) {
let positives = 0
let negatives = 0
let zeros = 0
const length=arr.length
for (var i = 0; i < arr.length;i++){
if (arr[i] > 0) {
positives++
} else if (arr[i] < 0) {
negatives++
} else {
zeros ++
}
}
const positiveRatio = Number(positives / length).toFixed(6)
const negativeRatio = Number(negatives / length).toFixed(6)
const zeroRatio = Number(zeros / length).toFixed(6)
console.log(positiveRatio)
console.log(negativeRatio)
console.log(zeroRatio)
}
And why this code is not passing any test-case ?
(I have edited my code: sorry for earlier wrong code) This code also does not works.
function plusMinus(arr) {
var l = arr.length;
var positiveCounter = 0;
var negativeCounter = 0;
var zeroCounter = 0;
for(var i=0; i<=l; i++) {
if (arr[i]>0) {
positiveCounter+=1;
} else if (arr[i]<0) {
negativeCounter+=1;
} else {
zeroCounter+=1;
}
}
console.log (
(positiveCounter/l).toFixed(6)+ '\n' +(negativeCounter/l).toFixed(6)+ '\n' +(zeroCounter/l).toFixed(6) );
}
I don't want alternative ways to solve this. I just want to know why the first code works and the second code doesnt ???
These 2 codes are different, you are dividing the numbers by the length twice
First in the assignment to a variable (var p= ...)
Second when doing the console.log ((p/l).toFixed(6))
Also, like mentionned by #DhananjaiPai, they have multiple console.log and you only have one with breaking characters which can be differently interpreted by OS (\r\n or \n )
You also have a something wrong in your loop, I will let you find that one but remember that an array begin from the index 0, if the array has 3 elements, that will be [0, 1, 2]
var a = "gsdgtrshghf";
function reverseString(strr){
if (!strr.length){
var result="";
for(var i=strr.length;i>0;i++){
var a=strr.chatAt(i);
result+=a;
}
}return result;
}
console.log(reverseString(a))
When I tried to run it it returned me "undefined". I wonder what's the problem here.
The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.
var a = "gsdgtrshghf";
function reverseString(strr){
var result="";
if (strr.length){
for(var i=strr.length-1;i>=0;i--){
var a=strr.charAt(i);
result+=a;
}
}
return result;
}
console.log(reverseString(a))
Have a look:
var a = "gsdgtrshghf";
function reverseString(strr) {
var result = "";
if (strr.length != null) {
for (var i = strr.length - 1; i >= 0; i--) {
var a = strr.charAt(i);
result += a;
}
}
return result;
}
console.log(reverseString(a));
// Better
const reverse = str => Array.from(str).reverse().join('');
console.log(reverse('foo 𝌆 bar mañana mañana'));
Explanation
It's charAt(i) not chatAt(i)
Loop should start from length - 1 and end at 0 and i should be decremented
And finally declare the variable outside of if
i.e for(var i = strr.length - ; i >= 0; i--){
not for(var i=strr.length;i>0;i++){
Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM
I am trying to create a reverse function to the String type in javascript. My code is like
String.prototype.reverse = function () {
var s = "";
for(var i=this.length;i>=0;i--){
s+=this[i];
}
return s;
}
When I try to use it on for example like "test".reverse();
instead of giving "tset" it's giving "undefinedtset"
I am setting the variable like var s = ""; inside the function, still undefined is coming. Why is it so?
You just need to change var i=this.length to var i=this.length-1, because an array starts at position 0 :
String.prototype.reverse = function () {
var s = "";
for(var i=this.length-1;i>=0;i--){
s+=this[i];
}
return s;
}
this.length gives you 4 (4 letters in test word) and you start iterating from 4 to 0.
The problem is that nothing exists under 4 index (your letters are stored in 0-3 positions).
Try with:
for (var i = this.length - 1; i >= 0; i--) {
s += this[i];
}
The reason why your code isn't working has been answered by the others already, but if you want a shorter version of the reverse, you can do it like this:
String.prototype.reverse = function(){
return this.split('').reverse().join('');
}
console.log('Hello World'.reverse())
I am VERY new to Javascript. I tried to look for an answer here but wasn't very lucky and maybe it's how I am asking. So, now I'm posting.
I have a loop in which I am to get a sum of the arrays. However, if the number 13 is in the array, then the loop stops adding numbers together but still return the numbers it added before it got to the 13. Right now, I have this as my code:
function sumNumbers(array) {
var sum = 0;
for(var i = 0; i < array.length; i++) {
sum += array[i];
if(array[i] == 13) {
break;
}
}
return sum;
}
I set the argument for the function which is 'array'. Then I thought I had to create a variable where the sum of the arrays will appear so I started it at 0 (I did try [] but tested it and it wasn't correct - still wanting to understand that). I understand that for any loop, you have to have the initialization which was i = 0, then the condition and then the final expression. So, since the number of elements is undefined, I used length. So, it says if the variable i is less than that number then it will keep going and keep adding to it. So I asked it to get a sum of all the arrays but if any number in a array is a 13, I need it to stop but still return the numbers it added before it reached 13.
Right now the function is defined, the sum of all arrays are returned and 0 is returned when its empty. But, I get this error
Expected 16 to deeply equal 3.
and can't figure out what I'm doing wrong. If anyone can help and explain it a little that would be awesome. This is my first question on here, so if I did it in an annoying way, thank you in advance!
If you need to stop adding when you find 13 and not include 13 in your sum then you need to check on the value of the next array element before you add it to your sum. I reversed two lines in your code. Please see the new version:
function sumNumbers (array) {
// First check if the array is a valid input to this function
if (typeof array == 'undefined')
return 0; // Or even better throw an exception
var sum = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] == 13) { break; }
sum += array[i];
}
return sum;
}
Array.prototype.some
It's like forEach, but it stops looping whenever you return true. It was created for scenarios like yours.
let total = 0;
[3,7,4,3,2,1,13,44,66,8,408,2].some(num => {
if (num === 13) return true;
total += num;
});
console.log(total); //-> 20
Here's how you would use it:
function sumNumbers (arr) {
let total = 0;
arr.some(num => {
if (num === 13) return true;
total += num;
});
return total;
}
There are plenty ways of doing that... one of them:
function sumNumbers (array) {
var sum = 0;
for (var i = 0; array[i] != 13; i++) {
sum += array[i];
}
return sum;
}
About your:
Then I thought I had to create a variable where the sum of the arrays will appear so I started it at 0 (I did try [] but tested it and it wasn't correct - still wanting to understand that).
Well, if you make a variable initialize with [] you are setting an empty array. Remember that brackets [] are for arrays always.
I want to try and sum up distinct value from a list.. currently i am able to do so if theres only 2 similar record. If theres more than 2 i am not able to do the checking. Following is the javascript code:
function validateData(){
var total = document.frm.size.value;
var msg="";
var tbxA;
var tbxB;
var tbxA2;
var tbxB2;
var tbxC;
var totalValue =0;
var repeatedValue= 0;
var row = 0;
var row2 = 0;
for(var i=0; i<parseInt(total); i++){
tbxA = document.getElementById('tbx_A'+i).value;
tbxB = document.getElementById('tbx_B'+i).value-0;
tbxC = document.getElementById('tbx_C'+i).value;
for(var j=i+1; j<parseInt(total); j++){
tbxA2 = document.getElementById('tbx_A'+j).value;
tbxB2 = document.getElementById('tbx_B'+j).value-0;
if (tbxA==tbxA2) {
totalValue = tbxB + tbxB2;
}
if (totalValue != tbxC) {
repeatedValue= 1;
row = i;
row2 = j;
msg+="*total value does not add up at row " +(row2+1);
break;
}
}
if(repeatedValue== 1){
break;
}
}
return msg;
}
For example A:type of fruit, B: total of each fruit, C: how many bought at a time
total of C should be equal to B. i.e Apple: 3+3+4 = 10. So if the total is not equals to 10 it should prompt me an error.
A B C
Apple 10 3
Orange 10 10
Apple - 3
Apple - 4
My code above will prompt error bt it doesnt go beyond 2nd occurence of Apple.
So yes, how should i go about to ensure it loop through the whole list to sum up all similar values?
Thanks in advance for any possible help!
Try this:
var total = +document.frm.size.value,
data = {};
for(var i=0; i<total; ++i) {
var key = document.getElementById('tbx_A'+i).value;
data[key] = data[key] || {B:0, C:0};
data[key].B += +document.getElementById('tbx_B'+i).value || 0;
data[key].C += +document.getElementById('tbx_C'+i).value || 0;
}
for(var i in data) {
if(data.hasOwnProperty(i) && data[i].B != data[i].C) {
return "total value does not add up";
}
}
return "";
Some comments:
parseInt (and parseFloat) is very slow. + operator before string converts it to a number much faster. But if you really want to make sure the numbers are integers, use Math.floor(), Math.round(), Math.ceil() or the faster but illegible |0.
In case you really want parseInt (e.g. you want to convert '123foobar' into 123), always use a radix. For example: parseInt('123', 10)
Avoid doing calculations at the condition of a loop, because they run at each iteration. Just do the calculation once before the loop and save the result in a variable.