pls I want this function to loop through any array and output a new array base on the logic written but am only getting the initial array when I call the function with the array as argument, pls I need help. Below is the code
const scores = [35, 68, 70, 38];
const scores1 = [89, 42, 33];
function gradingStudents(...grades) {
const newScores = grades.map(function (grade) {
if (grade + 2 >= 40 && grade % 5 >= 3) {
return grade % 5 == 3 ? grade + 2 : grade + 1;
} else if (grade + 2 >= 40 && grade % 5 < 3) {
return grade;
} else {
return grade;
}
});
return newScores;
}
console.log(gradingStudents(scores1));
Rest Paramanter syntax (...) is used when you are handling with dynamic number of arguments. Here you are passing only one argument to the function. Remove the ... from the function param and your function will work as expected.
const scores = [35, 68, 70, 38];
const scores1 = [89, 42, 33];
function gradingStudents(grades) {
const newScores = grades.map(function (grade) {
if (grade + 2 >= 40 && grade % 5 >= 3) {
return grade % 5 == 3 ? grade + 2 : grade + 1;
} else if (grade + 2 >= 40 && grade % 5 < 3) {
return grade;
} else {
return grade;
}
});
return newScores;
}
console.log(gradingStudents(scores1));
If you are handling the function using Rest Paramanter syntax as you did now, the parameter in the function written as ...grades will combine all the paramaters in the function to a single array. Which means your paramater scores1 will be there inside the grades array as in the below console.
const scores1 = [89, 42, 33];
function gradingStudents(...grades) {
// grades will be an array with scores1 as a sigle element in 0th index
console.log(grades)
}
gradingStudents(scores1);
Looping through grades in the above condition, the each node will be an array which will not satisfy any of the if statement, hence it will return the array itself. Thats why you are getting the output as an array with the parementer as the single node.
When declaring your function with rest parameters, you're expected to give your data as multiple arguments that will be automatically wrapped in an array
When giving it an array, you'l get a nested array
function restParamFunc(...params) {
console.log(params)
}
restParamFunc([1, 2])
You should either transform the rest parameters to a classic parameter
function restParamFunc(params) {
console.log(params)
}
restParamFunc([1, 2])
or use array destructuring when calling the function
function restParamFunc(...params) {
console.log(params)
}
restParamFunc(...[1, 2])
since you are returning grade if the first condition didn't meet. The rest operator is not needed. You can write it as follow:
function gradingStudents(grades) {
const newScores = grades.map(function (grade) {
if (grade + 2 >= 40 && grade % 5 >= 3) {
return grade % 5 == 3 ? grade + 2 : grade + 1;
}else {
return grade;
}
});
return newScores;
}
You can use forEach also
const scores = [35, 68, 70, 38];
const scores1 = [89, 42, 33];
function gradingStudents(grades) {
let newScore = [];
grades.forEach(function (grade) {
if (grade + 2 >= 40 && grade % 5 >= 3) {
grade = grade % 5 == 3 ? grade + 2 : grade + 1;
newScore.push(grade);
} else if (grade + 2 >= 40 && grade % 5 < 3) {
newScore.push(grade);
} else {
newScore.push(grade);
}
});
return newScore;
}
console.log(gradingStudents(scores));
console.log(gradingStudents(scores1));
Related
Given an circular array & calculate the diff between two consecutive number. & if diff is greater than ‘k’, print 1 else print 0
Input Description:
You are given two numbers ‘n’, ’m’. Next line contains n space separated integers.
Output Description:
Print 1 if the difference is greater than ‘m’.
Can Anyone help with the code for easy Understanding for beginners
Sample Input :
5 15
50 65 85 98 35
Sample Output :
0 1 0 1 0
Code:
let cirluarArray = (data) => {
let n=data[0].split(" ").map(Number);//(sample input 1)
let arr = data[1].split(" ").map(Number);//(sample input 2)
let i,arr1=[];
for(i=0;i<arr.length-1;i++){
let x=arr[i]-arr[i+1];
if((x>0 && x<n[1])||(x<0 && x>-n[1])){
arr1.push(0);
}
else{
arr1.push(1);
}
}
if(((arr[arr.length-1]-arr[0])>0 && (arr[arr.length-1]-arr[0])<n[1])||((arr[arr.length-1]-arr[0])<0 && (arr[arr.length-1]-arr[0])>-n[1])){
arr1.push(0);
}
else{
arr1.push(1);
}
return arr1.join(" ");
};
console.log(cirluarArray(userInput));
I think that is
const circularArray = (array, k) => {
array.push(array.at(0)); // circular array
let output = [];
for (let i = 1; i < array.length; i++) {
const currentNumber = array[i];
const prevNumber = array[i-1];
let diff = currentNumber - prevNumber;
if (diff < 0) {
diff *= -1; // if negative, change to positive
}
if (diff > k) {
output.push(1);
} else {
output.push(0);
}
}
return output;
}
const result = circularArray([50, 65, 85, 98, 35], 15);
console.log(result);
I have tried so many time to solve this question but I couldn't accomplish the expected outcome.
Here's the question in a nutshell:
Count all the values that are divisible by 11 in a given array
Return 0 if you encounter a number that is greater than or equal 111 regardless of the other divisible numbers of 11.
For example:
Input: [11,12,22,33]
Output: 3
Input: [11,12,22,33,136]
Output: 0
I could solve the first part but failed with the second one.
Here is my code.
function div(list) {
let counter = 0
list.forEach((value) => {
if (value % 11 === 0) {
counter++
return counter
}
if(value>=111){
return 0
}
})
return counter
}
div([11, 22, 33, 44 , 116])
// OUTPUT : 4
Use a for loop instead so you can return inside if the break condition is found. Otherwise, return only at the end, not inside the loop.
function div(list) {
let counter = 0;
for (const value of list) {
if (value % 11 === 0) {
counter++
}
if (value >= 111) {
return 0
}
}
return counter
}
console.log(div([11, 22, 33, 44, 116]));
All the above answers works great, adding a different approach, letting the inbuilt method do the looping
function div(total, value) {
if (value % 11 === 0) {
total++;
}
if(value>=111){
total=0
}
return total;
}
console.log([11,12,22,33].reduce(div,0));
Use for...of loop to iterate over list and return inside loop when value is >= 111, otherwise keep counting the values divisible by 11.
function div(list) {
let count = 0;
for (const value of list) {
if(value >= 111){
return 0;
} else if (value % 11 === 0) {
count++;
}
}
return count;
}
console.log(div([11, 22, 33, 44 , 116]));
All of the other answers are great. Here's a solution that is a bit more condensed and offers a single return statement.
function div(list) {
let counter = 0;
let oversized = false;
for (let i = 0; (i < list.length) && !oversized; i++) {
counter += (list[i] % 11) ? 0 : 1;
oversized = (list[i] >= 111);
}
return oversized ? 0 : counter;
}
console.log(div([11, 22, 33, 44 ]));
I was trying to work on this hackerrank problem.
Every student receives a grade in the inclusive range from
0-100 to .
Any less than 38 is a failing grade.
Sam is a professor at the university and likes to round each student's according to these rules:
If the difference between grade the and the next multiple of
5 is less than 3, round up to the next multiple of 5. If the value of grade is less than 38, no rounding occurs as the
result will still be a failing grade.
Given the initial value of for each of Sam's students, write code to
automate the rounding process.
My code is:
function gradingStudents(grades) {
const roundup = y => y + 1;
{
if ( grades < 38 || grades % 5 === 0) return grades;
else if ( grades % 5 < 4 && grades % 5 !== 0) return roundup(grades);
}
{
if (roundup % 5 === 0) return roundup;
else { gradingStudents(roundup + 1) }
}
}
gradingStudents(38) // -> 39
I tried to use Math.ceil(grades) inside the variable roundup but output didnt change. So, when you invoke the function with a number that is not before a multiple of 5 (e.g. 43) it returns the proceeding number. However, if it is the number before a multiple of 5 it gives a range error. "maximum call stack size reached."
As far as I got, the code doesnt proceed to the second part. Even if it did, I am not sure if it would fetch the current value of the function roundup when dealing with if statements in the second block.
What do I dont get in here?
Also, this is actually meant for an array output but since I am a beginner I am pretty much okay with this one for the start as well :D .
Javascript solution:
function gradingStudents(grades) {
return grades.map((grade) => {
if (grade > 37) {
const offset = 5 - (grade % 5);
if (offset < 3) {
grade += offset;
}
}
return grade;
});
}
Try this:
function gradingStudents(grades) { //input: 43
var finalGrade;
if(grade < 38)
return grades;
else{
var gradeDif = grades % 5; //3
if(gradeDif > 3){
return grades;
}
else {
return grades + (5 - gradeDif); //Output: 45
}
}
}
One solution calculates the next multiple of 5 no bigger than the grade and uses that value to test whether or not to round up (next5 - grade < 3).
We write a simple function to round an individual grade and then for a list of grades use .map with that function.
const roundGrade = (grade) => {
const next5 = 5 * Math.ceil (grade / 5)
return (grade < 38) ? grade : (next5 - grade < 3) ? next5 : grade
}
const gradingStudents = (grades) =>
grades .map (roundGrade)
console .log (gradingStudents ([73, 67, 38, 33]))
Note that, like most solutions to this problem, no recursion is needed.
1-Use the Array.prototypt.map according to the question logic.
const gradingStudents = (grades) => grades
.map(n => (n >= 38 && n % 5 >= 3)?(n + ( 5 - ( n % 5 ) )):n )
let result = gradingStudents([0,25,38,56,89,77,78,57,58])
console.log(result)
My solution is this
function gradingStudents(grades) {
grades.map((grade,i)=>{
if(grade >= 38){
let fg = (grade/5).toString().split('.');
if(fg[1]>5){
grades[i]=((parseInt(fg[0],10)+1) * 5);
};
}
});
return grades;
}
console.log(gradingStudents([73,67,38,33]));
my solution:
function gradingStudents(grades) {
return grades.map(function(grade) {
return (grade >= 38 && grade % 5 >= 3) ? grade + 5 - (grade % 5) : grade;
});
}
I want to get a random number from the Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, ...
Here is my code:
var number = Math.floor(Math.random() * 100000);
var series_element = -1;
if (number < 1) {
series_element = 1;
} else {
if (number < 2) {
series_element = 2;
} else {
if (number < 3) {
series_element = 3;
} else {
if (number < 5) {
series_element = 5;
} else {
if (number < 8) {
series_element = 8;
} else {
if (number < 13) {
series_element = 13;
} else {
if (number < 21) {
series_element = 21;
}
////// series continues to 317811
}
}
}
}
}
}
alert(series_element);
But I never got the value of series_element less than 100. It always shows me higher values.
I think you mean that you're not getting a random number less than 100 from the Math.random() function. So you're not getting your variable series_element to be 11 or less (the first 11 terms of the Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 55 89).
In fact, it's a matter of probabilities.
100 / 1000000 = 0.0001
If you keep executing it you'll get a value less than 100 at some point... approximately 1 from 10000 times you do it.
There's nothing wrong with your code, but it could be improved so you don't have to put so much ifs.
First, let's define a function to calculate the fibonacci numbers. Details on how to do that can be find here: https://medium.com/developers-writing/fibonacci-sequence-algorithm-in-javascript-b253dc7e320e
function fibonacci(num){
var a = 1, b = 0, temp;
while (num >= 0){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
To get a random Fibonacci number you can call this function with a random number.
var number = Math.floor(Math.random()*100);
var result = fibonacci(number);
I don't recommend going after 100 as your computer may take too much time to process the result...
You are using with poorly structured code to generate fabonacci series. Try something like following, you will get value under 100 and 1000
Where N is position of Fibonacci number from 1 to N and X is actual number.
var n = function getRandomNum() {
return Math.floor(Math.random()*100) +1;
}
var result = [];
result[0] = 1;
result[1] = 1;
function fib(x) {
var ix, ixLen;
for(ix = 0, ixLen = x; ix < ixLen; ix++){
if(!result[ix]){
result[ix] = result[ix-2] + result[ix-1];
}
}
console.log('n:', x, ' result: ', result[ix-1]);
return result[ix-1];
}
console.log(fib(n()));
This is one of those times where the solution is staring me right in the face but I can't seem to find it! So please be patient with me. The kata instruction is the following:
Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade.
Numerical Score Letter Grade
90 <= score <= 100 'A'
80 <= score < 90 'B'
70 <= score < 80 'C'
60 <= score < 70 'D'
0 <= score < 60 'F'
Tested values are all between 0 and 100. There is no need to check for negative values or values greater than 100.
Here is my solution:
function getGrade (s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (90 <= score && score >= 100) {
return 'A';
} else if (80 <= score && score > 90) {
return 'B';
} else if (70 <= score && score > 80) {
return 'C';
} else if (60 <= score && score > 70) {
return 'D';
} else if (0 <= score && score > 60) {
return 'F';
}
}
getGrade(5,40,93);
getGrade(30,85,96);
getGrade(92,70,40);
Can't for the life of me figure out what I am doing wrong.
Your conditions in if statement are all wrong. These are the right conditions
function getGrade (s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (score >= 90 && score <= 100) {
return 'A';
} else if (score >= 80 && score < 90) {
return 'B';
} else if (score >= 70&& score < 80) {
return 'C';
} else if (score >= 60 && score < 70) {
return 'D';
} else {
return 'F';
}
}
your conditions are wrong and you don't need multiple check in same if .Change your code to this:
function getGrade (s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (score >= 90 && score <= 100) {
return 'A';
} else if (score >= 80 ) {
return 'B';
} else if (score >= 70 ) {
return 'C';
} else if (score >= 60) {
return 'D';
} else{
return 'F';
}
}
console.log(getGrade(5,40,93));
console.log(getGrade(30,85,96));
console.log(getGrade(92,70,40));
You could use only if clauses without else parts and check only the lower bound, because you have already checked the upper bound.
The check for upper 100 is missing, because your given range is between 0 and 100.
function getGrade(s1, s2, s3) {
var score = (s1 + s2 + s3) / 3;
if (score >= 90) {
return 'A';
}
if (score >= 80) {
return 'B';
}
if (score >= 70) {
return 'C';
}
if (score >= 60) {
return 'D';
}
return 'F';
}
console.log(getGrade(5, 40, 93));
console.log(getGrade(30, 85, 96));
console.log(getGrade(92, 70, 40));
Whenever you find yourself writing long chains of if-else statements, see if you can find a pattern and use a lookup table. Here, we have only 5 grade buckets, but what if we had 20 or 100? You can see the if-else approach isn't scalable.
In this case, if we use the string "FFFFFFDCBAA" then we've enumerated all 5 grade buckets in a way that lets us index into after dividing the score by 10. The code for that would be: "FFFFFFDCBAA"[score/10|0] where | 0 is the floor operation, chopping off the decimal. The extra "A" handles the case of 100.
Secondly, the arguments to the function (s1, s2, s3) make no sense. Why 3 scores? If we have 4 score, or 20 scores, the function can't be used and we have to rewrite the whole function with the right number of arguments (and the 20-argument one will be pretty ugly). I realize this header is what the kata author gave you, but there's no reason we can't make it handle any number of arguments using (...args) and still pass the tests. If we take the average of the arguments using args.reduce((a, e) => a + e, 0) / args.length, we're left with the following solution:
const sum = a => a.reduce((a, e) => a + e, 0);
const avg = a => sum(a) / a.length;
const getGrade = (...args) => "FFFFFFDCBAA"[avg(args)/10|0];
[
[0],
[0, 100, 50],
[90, 95, 100],
[80, 60],
[81, 79],
[80, 59],
].forEach(test => console.log(`${test} => ${getGrade(...test)}`));