Having problems with output - javascript

I build the code, which should return Knick if the number is odd, Knack if it's multiple of five and KnickKnack if it's either odd and multiple of five. The problem is that it returns line to line in console, I want it to concatenate in a string.
Here's the code:
function knickKnack(maxValue) {
const numbers = [];
for (var i = 1; i <=100; i++) {
if (i % 5 === 0 ) {
console.log ('KnickKnack, ');
} else if (i % 10 === 0) {
console.log ('Knack, ');
} else if (i % 2 === 1) {
console.log ('Knick, ');
} else {
console.log (i + ', ');
}
}
return numbers;
}
knickKnack();

function knickKnack(maxValue) {
var knickKnackString = '';
for (var i = 1; i <= maxValue; i++) {
if (i % 5 === 0 && i % 2 === 1)
knickKnackString += 'KnickKnack, ';
else if (i % 10 === 0)
knickKnackString += 'Knack, ';
else if (i % 2 === 1)
knickKnackString += 'Knick, ';
else
knickKnackString += i + ', ';
}
console.log(knickKnackString);
}
Try like this.

Related

How do i return the result of all loops in javascript?

I am trying to insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers, but I am only getting the last result.
I want to print out all the elements in the array.
For example: if num is 4546793 the output should be 454*67-9-3. I Did not count zero as an odd or even number.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i] === 0) {
continue;
}
if (num[i - 1] % 2 == 0 && num[i] % 2 == 0) {
result = num[i - 1] + "*" + num[i];
continue;
}
if (num[i - 1] % 2 == !0 && num[i] % 2 == !0) {
result = num[i - 1] + "-" + num[i];
continue;
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
You do not need to check as if&continue. Inserting given numbers to the result string and only adding "-" when index and previous are odd, and "*" when index and previous are even.
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
if (num[i]%2 ===0) {// even
if(i !== 0 && num[i-1]%2===0){// previous is even either
result+="*"+num[i];
}else{
result+=num[i];
}
}else{// odd
if(i !== 0 && num[i-1]%2===1){// previous is odd either
result+="-"+num[i];
}else{
result+=num[i];
}
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Try this :)
function test(a){
let result=""
for(let i=0; i < a.length; i++){
if(a[i] != 0 && a[i-1] % 2 == 0 && a[i] % 2 == 0){
result = result + '*' + a[i]
}
else if (a[i] != 0 && a[i-1] % 2 != 0 && a[i] % 2 != 0){
result = result + '-' + a[i]
}
else{
result = result + a[i]
}
}
return result
}
console.log(test([4,5,4,6,7,9,3]));
As everyone has identified, the problem is you are not adding to result.
But here is a suggestion to make your code easier to read
// These one line functions make your code easier to read
function IsEven(num){
return num % 2 === 0;
}
function IsOdd(num){
return num % 2 !== 0;
}
function StringChallenge(numArray) {
// return empty string if not an array or empty array
if(!Array.isArray(numArray) || numArray.length === 0) return "";
let result = "" + numArray[0]; // use "" to coerce first element of numArray from number to string
for (let i = 1; i < numArray.length; i++) {
// focus on the conditions to determine the separator you want between each element
separator = "";
if (numArray[i] !== 0) {
if (IsEven(numArray[i]) && IsEven(numArray[i - 1])) {
separator = "*";
} else if (IsOdd(numArray[i]) && IsOdd(numArray[i - 1])){
separator = "-";
}
}
// build the result
result += separator + numArray[i];
}
return result;
}
I will do that this way :
== some advices for 2 cents ==
1 - try to make your code as readable as possible.
2 - use boolean tests rather than calculations to simply do a parity test
3 - ES7 has greatly improved the writing of JS code, so take advantage of it
console.log(StringChallenge([4,5,4,6,7,9,3])); // 454*67-9-3
function StringChallenge( Nums = [] )
{
const
isOdd = x => !!(x & 1) // Boolean test on binary value
, isEven = x => !(x & 1) && x!==0 // zero is not accepted as Even value
;
let result = `${Nums[0]??''}`; // get first number as
// result if Nums.length > 0
for (let i=1; i<Nums.length; i++)
{
if ( isOdd(Nums[i-1]) && isOdd(Nums[i]) ) result += '-';
if ( isEven(Nums[i-1]) && isEven(Nums[i]) ) result += '*';
result += `${Nums[i]}`; // same as Nums[i].toString(10);
}
return result
}
I hope this helps. I tried to keep it as simple as possible.
function StringChallenge(num) {
//start with a string to concatenate, or else interpreter tries to do math
operations
let result = num[0].toString();
function checkOdd(num){ //helper function to check if odd
return num % 2
}
for (let i = 0; i < num.length - 1; i++) {
if (checkOdd(num[i]) && checkOdd(num[i+1])) { //checks if both odd
result += `-${num[i+1]}`; //adds - and next number
} else if (!checkOdd(num[i]) && !checkOdd(num[i+1])) { //checks if both even
result += `*${num[i+1]}`; //adds * and next number
} else { //otherwise
result += num[i+1]; //just add next number
}
}
return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));
Use +=. And, change your logic, your code prints out "4*67-99-3".
The zero check was pretty hard for me I hope the variables in my code explain itself. If not, let me know.
function even(num) {
return num % 2 === 0;
}
function odd(num) {
return num % 2 !== 0;
}
function StringChallenge(num) {
let result = "";
for (let i = 0; i < num.length; i++) {
var currentZero = num[i] === 0
var previousZero = num[i-1] === 0
var bothEven = even(num[i]) && even(num[i-1])
var bothOdd = odd(num[i]) && odd(num[i-1])
var firstNumber = (i === 0)
if (!currentZero) {
if (firstNumber) {
result += num[i]
} else {
if (bothEven && !previousZero) {
result += "*" + num[i]
} else if (bothOdd && !currentZero) {
result += "-" + num[i]
} else {
result += num[i]
}
}
}
}
return result;
}
console.log(StringChallenge([0,4,5,0,4,6,7,9,3]));

Given n as input, print the following pattern -1+2-3+4-5+....(+/-)n = n, with JavaScript

I have tried many times but I can't find the values, how can I solve this? Here's my code:
var number = prompt("");
for (var count = 1; count <= number; count++) {
if (count % 2 != 0) {
console.log("-");
document.write("-");
// console.log(count);
document.write(count);
} else {
console.log("+");
document.write("+");
// console.log(count);
document.write(count);
}
}
document.write("=", );
Try this out:
var number = prompt("");
var result = 0;
for (var count = 1; count <= number; count++) {
if (count % 2 != 0) {
document.write("-");
document.write(count);
result -= count;
} else {
document.write("+");
document.write(count);
result += count;
}
}
document.write("=" + result);
A declarive solution. (as a fan of declarative programming)
const func = (n) => {
[...Array(n)].map( (_,i) => (
i%2 === 0 ? console.log(`-${i+1}`) : console.log(`+${i+1}`)
))}
func(6)
This should do the trick.
Here's your solution (with fiddle).
function expandString(n) {
let str = '';
for (let i = 1; i <= n; i++) {
if (i % 2 === 1) {
str += `-${i}`; // Even
} else {
str += `+${i}`; // Odd
}
}
return str += ` = ${n}`;
}
console.log(expandString(5));
Hope this will help you.
var flag = true;
var result=0;
var str = "";
var n=10;
for(let i=1;i<n;i++){
if(flag){
str += "-";
result -= i;
}
else{
str += "+";
result += i;
}
str += i;
flag = !flag
}
str += "="+result;
console.log(str);

JavaScript- get sum of values inside a for loop

I'm trying to sum all the variables,
as many times as they appear in the loop,
that is- for example if hitpoints appears
3 times(as in my code) sum -12 + -12 + -12;
And then at the end I need a final result - a
sum of all of the variable values as many
times as they appear.
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
console.log( i + "-" + hitpoints);
} else if ((i % 3 === 0) && (i% 5 ===0)) {
console.log( i + "-" + pointsx);
} else if (i %3 ===0) {
console.log ( i + "-" + points3);
} else if (i%5 ===0) {
console.log( i + "-" + points5);
} else {
console.log( i + "-" + points1);
}
}
}
calculate(30);
I assume you want the sum of the points.
Declare a variable sum and keep incrementing
function calculate(number) {
var hitpoints = -12;
var points1 = 1;
var points3 = 5;
var points5 = 10;
var pointsx = 15;
var sum=0;
for (var i =1; i <= number; i++) {
if ( i%10 ===0) {
sum += hitpoints;
} else if ((i % 3 === 0) && (i% 5 ===0)) {
sum += pointsx;
} else if (i %3 ===0) {
sum += points3;
} else if(i%5 ===0) {
sum += points5;
} else {
sum += points1;
}
}
console.log(sum)
}
calculate(30);

Bug while trying to find sum of primes with javascript

I am trying to get the sum of an array of prime numbers, and I understand there are more elegant ways to do that and have seen the links to those solutions.
My problem is something that's wrong within this specific script, and I'm trying to understand what's causing THIS code to fail.
The issue is that the numbers 9, 15 and many others are being being added into the primes array, even though they all, correctly, fail a test to check if they're prime numbers. I can't wrap my head around what in the script is causing the numbers to push to the array despite failing that test. Again, I'm not looking for a completely different/better approach to summing the primes, but some help in identifying what exactly is wrong in this script would be really appreciated.
function totalPrime(num) {
var nums = [];
var primes = [];
for (var i = 1;
(num - i) > 1; i++) {
nums.push(num - i);
}
nums.forEach(isPrime);
function isPrime(n) {
var a = [];
var test;
if (n === 1) {} else if (n === 2) {
primes.push(n);
} else {
for (var i = 1;
(n - i) > 1; i++) {
a.push(n - i);
}
a.forEach(function(x) {
if ((n % x) === 0) {
test = false;
} else {
test = true;
}
});
if (test) {
primes.push(n);
} else {}
};
}
console.log(primes.reduce(function(a, b) {
return a + b
}));
}
totalPrime(5);
Same script with logging I was using to debug:
function totalPrime(num) {
var nums = [];
var primes = [];
for (var i = 1;
(num - i) > 1; i++) {
nums.push(num - i);
}
nums.forEach(isPrime);
function isPrime(n) {
var a = [];
var test;
if (n === 1) {
console.log(n + ' is NOT a prime number');
} else if (n === 2) {
console.log(n + ' IS a prime number');
primes.push(n);
} else {
for (var i = 1;
(n - i) > 1; i++) {
a.push(n - i);
}
a.forEach(function(x) {
if ((n % x) === 0) {
test = false;
console.log(n + ' % ' + x + ' equals 0');
console.log(x + ' fails check');
} else {
test = true;
console.log(n + ' % ' + x + ' does NOT equal 0');
console.log(x + ' passes check');
}
});
if (test) {
console.log(n + ' IS a prime number.');
primes.push(n);
} else {
console.log(n + ' is NOT a prime number.');
}
};
}
console.log(primes);
console.log(primes.reduce(function(a, b) {
return a + b
}));
}
totalPrime(5);
Your test value in each test override the previous check. Thus, actualy only the last check (divide in 2) become relevant, and all the odd primes fail.
You can correct it by change the default of test to true, and remove the exist line in the code test = true;.
The corrected code:
function isPrime(n) {
var a = [];
var test = true;
if (n === 1) {} else if (n === 2) {
primes.push(n);
} else {
for (var i = 1;
(n - i) > 1; i++) {
a.push(n - i);
}
a.forEach(function(x) {
if ((n % x) === 0) {
test = false;
}
});
if (test) {
primes.push(n);
}
};
}

Undefined result from Fizz Buzz game Javascript

I'm having an assignment where I have to do the FizzBuzz game in Javascript. The problem is I get 'Answer = undefined' when I run the function. I have to print it with a comma separated value but I think I can figure that out for my self though; Thanks in advance. Regards, Thomas.
function fizzBuzz(start, stop) {
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
document.write("Fizz Buzz");
}else if(i % 3 == 0) {
document.write("Fizz");
}else if(i % 5 == 0) {
document.write("Buzz");
}else {
document.write(i);
}
}
}
ANSWER = (fizzBuzz(4, 22));
Because the fizzBuzz function isn't returning anything. You need to return a result from that function. document.write writes out text to the document.
You aren't returning anything from your function.
ANSWER will be what you 'return' in a function.
If you wanted to return all the values you would need to do somthing like
var ans='';
...
if ( whatever) ans+= 'Fizz Buzz,';
....
return ans.substring(0,ans.length-1);
Some modifications to your code...
function fizzBuzz(start, stop) {
var i;
var results = [];
for (i = start; i <= stop; i++) {
if (i % 15 == 0) {
results.push('Fizz Buzz');
} else if (i % 3 == 0) {
results.push('Fizz');
} else if (i % 5 == 0) {
results.push('Buzz');
} else {
// cast to string just so all the results in the array are string
results.push(i + '');
}
}
return results;
}
ANSWER = fizzBuzz(4, 22); // output: [ '4', 'Fizz', 'Buzz', '7', '8', ...etc ]
<html>
<script>
function fizzBuzz(start, stop) {
var str = 'ANSWER = ';
for(var i = start; i <= stop; i++) {
if (i % 3 == 0 && i % 5 == 0) {
str += "Fizz Buzz";
}else if(i % 3 == 0) {
str += "Fizz";
}else if(i % 5 == 0) {
str += "Buzz";
}else {
str += i;
}
if (i<stop)
str += ", ";
}
document.getElementById('writeto').innerHTML += str;
}
fizzBuzz(4, 22);
</script>
<body>
<a id='writeto'></a>
</body>
</html>

Categories

Resources