Running the rest code after condition is met - javascript

please how can i make the second if condition run after i is greater than 9
var i = 0;
var x = document.querySelector(".start");
x.addEventListener("click", function () {
if (i < 10) {
console.log(i);
i++;
}
})
if (i === 10) {
console.log(i);
}
<button class="start">start</button>

You could move the check inside of the event callback and check if the value is ten, then return early.
Otherwise increment i and make the wanted output.
var i = 0;
var x = document.querySelector(".start");
x.addEventListener("click", function () {
if (i === 10) return;
i++;
if (i < 10) {
console.log(i);
} else {
console.log('ten');
}
})
<button class="start">start</button>

Related

Happy numbers - recursion

I have an issue with a recursive algorithm, that solves the problem of finding the happy numbers.
Here is the code:
function TestingFunction(number){
sumNumberContainer = new Array(0);
CheckIfNumberIsHappy(number);
}
function CheckIfNumberIsHappy(number){
var sumOfTheNumbers = 0;
for (var i = 0; i < number.length; i++) {
sumOfTheNumbers += Math.pow(parseInt(number[i]), 2);
}
console.log(sumOfTheNumbers);
if(sumOfTheNumbers == 1){
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
//return true;
} else {
sumNumberContainer.push(sumOfTheNumbers);
if(sumNumberContainer.length > 1){
for (var i = 0; i < sumNumberContainer.length - 1; i++) {
for (var j = i + 1; j < sumNumberContainer.length; j++) {
if(sumNumberContainer[i] == sumNumberContainer[j]){
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
//return false;
}
}
}
}
CheckIfNumberIsHappy(sumOfTheNumbers.toString());
}
}
Algorithm is working ALMOST fine. I've tested it out by calling function with different numbers, and console was displaying correct results. The problem is that I almost can't get any value from the function. There are only few cases in which I can get any value: If the number is build out of ,,0", and ,,1", for example 1000.
Because of that, I figured out, that I have problem with returning any value when the function is calling itself again.
Now I ended up with 2 results:
Returning the
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
which is giving an infinity looped number. For example when the number is happy, the function is printing in the console number one again and again...
Returning the
//return true
or
//return false
which gives me an undefined value
I'm a little bit in check by this problem, and I'm begging you guys for help.
I would take a step back and reexamine your problem with recursion in mind. The first thing you should think about with recursion is your edge cases — when can you just return a value without recursing. For happy numbers, that's the easy case where the sum of squares === 1 and the harder case where there's a cycle. So test for those and return appropriately. Only after that do you need to recurse. It can then be pretty simple:
function sumSq(num) {
/* simple helper for sums of squares */
return num.toString().split('').reduce((a, c) => c * c + a, 0)
}
function isHappy(n, seen = []) {
/* seen array keeps track of previous values so we can detect cycle */
let ss = sumSq(n)
// two edge cases -- just return
if (ss === 1) return true
if (seen.includes(ss)) return false
// not an edge case, save the value to seen, and recurse.
seen.push(ss)
return isHappy(ss, seen)
}
console.log(isHappy(23))
console.log(isHappy(22))
console.log(isHappy(7839))
Here's a simplified approach to the problem
const digits = x =>
x < 10
? [ x ]
: [ ...digits (x / 10 >> 0), x % 10 ]
const sumSquares = xs =>
xs.reduce ((acc, x) => acc + x * x, 0)
const isHappy = (x, seen = new Set) =>
x === 1
? true
: seen.has (x)
? false
: isHappy ( sumSquares (digits (x))
, seen.add (x)
)
for (let n = 1; n < 100; n = n + 1)
if (isHappy (n))
console.log ("happy", n)
// happy 1
// happy 7
// happy 10
// ...
// happy 97
The program above could be improved by using a technique called memoization
Your code is almost correct. You just forgot to return the result of the recursive call:
function TestingFunction(number){
sumNumberContainer = new Array(0);
if (CheckIfNumberIsHappy(number))
console.log(number);
}
function CheckIfNumberIsHappy(number){
var sumOfTheNumbers = 0;
for (var i = 0; i < number.length; i++) {
sumOfTheNumbers += Math.pow(parseInt(number[i]), 2);
}
if(sumOfTheNumbers == 1){
return true;
} else {
sumNumberContainer.push(sumOfTheNumbers);
if(sumNumberContainer.length > 1){
for (var i = 0; i < sumNumberContainer.length - 1; i++) {
for (var j = i + 1; j < sumNumberContainer.length; j++) {
if(sumNumberContainer[i] == sumNumberContainer[j]){
return false;
}
}
}
}
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
}
}
for (let i=0; i<100; ++i)
TestingFunction(i.toString()); // 1 7 10 13 ... 91 94 97
I've got the solution, which was given to me in the comments, by the user: Mark_M.
I just had to use my previous
return true / return false
also I had to return the recursive statement in the function, and return the value of the CheckIfTheNumberIsHappy function, which was called in TestingFunction.
The working code:
function TestingFunction(number){
sumNumberContainer = new Array(0);
return CheckIfNumberIsHappy(number);
}
function CheckIfNumberIsHappy(number){
var sumOfTheNumbers = 0;
for (var i = 0; i < number.length; i++) {
sumOfTheNumbers += Math.pow(parseInt(number[i]), 2);
}
console.log(sumOfTheNumbers);
if(sumOfTheNumbers == 1){
return true;
} else {
sumNumberContainer.push(sumOfTheNumbers);
if(sumNumberContainer.length > 1){
for (var i = 0; i < sumNumberContainer.length - 1; i++) {
for (var j = i + 1; j < sumNumberContainer.length; j++) {
if(sumNumberContainer[i] == sumNumberContainer[j]){
return false;
}
}
}
}
return CheckIfNumberIsHappy(sumOfTheNumbers.toString());
}
}
Thanks for the great support :)

- I am trying to write a code where input should be abbbcc and output should be a1b3c2

I am new to js.
I am trying to write a code where input should be abbbcc and output should be a1b3c2.
not sure how to get it
providing code below
var word = "abbbcc";
var countword = [];
for (i=0; i < word.length; i++) {
if (word[i] === charAt && word[i] != word[i+1]) {
countword.push(word[i]);
countword.push(i++);
}
else (word[i] === charAt && word[i] != word[i+1]) {
countword.push(word[i]);
for (i=0; i < word.length; i++) {
if (word[i+1] === word[i+2]) {
countword.push(i++);
}
else{
break;
}
}
}
}
console.log("result----->" + countword);
It can be done using a for loop and a counter like this.
var word = "abbbcc";
var countword = "";
var counter = 1;
for (i=0; i < word.length; i++) {
if ( word[i] != word[i+1]) {
// Save the letter and the counter
countword += word[i]+counter;
// Reset the counter
counter=1;
}else{
// Increment counter
counter++;
}
}
console.log("result-----> " + countword );
Alternative solution using Array#reduce. I've described each step, I hope you will get my point and understand how does it works.
var word = "abbbcc".split(''),
res = '',
counter = 1;
word.reduce(function(s, a, i, r) {
if (s !== a) { //if the succeeding element doesn't match the previous one
res += s + counter; //concat it to the string + the amount of appearances (counter)
counter = 1; //reset the counter
} else {
counter++; //the succeeding element matches the previous one, increment the counter
}
if (i === r.length - 1 && counter > 0) { //if the loop is over
res += s + counter; //add the last element
}
return a;
})
console.log(res);

print number from 1 to 10 after every 2 seconds

i want to print number after every n number of seconds and based on few conditions i am changing the timer as well as i am stopping the print function. i have done like this --
var myfunc = {
value : 1,
running : false,
timer : 1000,
start : function(){
this.running = true;
clearInterval(this.timeout);
this.timeout = setTimeout(function() {
myfunc.execute(myfunc);
}, myfunc.timer);
},
execute : function(){
if(!this.running) return false;
console.log( 'Currently at -- ' + (this.value++) );
if (this.value > 5 ){
this.changetiming();
}
if (this.value > 10 ){
this.stop();
return;
}else{
this.start();
}
},
changetiming : function(){
this.timer = 3000;
},
stop : function(){
this.running = false;
clearTimeout(this.timeout);
}
};
myfunc.start();
Now i want to know what is wrong with following code --
for(var i = 0; i <= 10; i++){
print(i);
}
function print(i){
setTimeout(function(){
console.log(i)
},2000);
}
here is the right way and easy way to do this in ES6+:
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) {
setTimeout( () =>{
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);
by multiplying i , each setTimeout() to be delayed 2 to 20 seconds (2000 x 1, 2000 x 2…) respectively.
I'm pretty sure the question "Why does this JavaScript code
for (var i = 0; i <= 10; i++){
print(i);
}
function print(i) {
setTimeout(function(){
console.log(i)
},2000);
}
print out the values 1 through 10 at once, after 2 seconds have elapsed?" has been asked before.
It is a common mistake.
What you are doing is calling print 10 times. Each call to print takes only a few microseconds. Why? Because it just calls setTimeout. Executing setTimeout takes only a few microseconds to complete. All the call does is schedule something to take place in the future. So within a few microseconds you have scheduled 10 things to take place at about 2 seconds in the future. All the schedulings happen at about the same time. So all the console logs take place at about the same time, two seconds after you scheduled them.
See Satapal's comment to your question for a nice way to do what you want to do.
#easiestway
for (var i = 0; i <= 10; i++){
print(i);
}
function print(i) {
setTimeout(function(){
console.log(i)
},i*2000);
}
Using IIFE, Clouser, and Global Scoping
(function(numbers){
for(var i=0; i<numbers.length; i++){
(function(i){
setTimeout(console.log, i*2000, i+1)
})(i);
}
})(new Array(10))
OR IIFE and Local Scoping
(function(numbers){
for(let i=0; i<numbers.length; i++){
setTimeout(console.log, i*2000, i+1)
}
})(new Array(10))
for(var i = 0 ; i <= 10 ; i++) {
setTimeout( () => { console.log(i) }, i * 1000 );
}
Why we are not able to print 0 to 10 no with the help of var?
Why we are able to do with let?
You might want to try this:
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) setTimeout(console.log, i * 1000,i)
}
printNumbersForEvery2Sec(10);```
You can use timeout of javascript
function timer(n) {
for (let i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i);
}, i * n);
}
}
timer(2000);
In the above code timing is not coded so you can decide how much interval you want.
A more generalised solution:
function printNumbers(start, end, delay=1){
const interval = delay*1000
for(let i=start; i<=end; i++){
setTimeout(console.log, (i-start)*interval, i)
}
}
printNumbers(3, 10, 2) // firstNumber, lastNumber, timeInSeconds
for (let i = 1; i <= 10; i++) {
setTimeout(() => {
console.log(i)
}, (i * 2000) )
}
Far best! and easy solution... Checkout snippet...
for (let i = 1; i <= 10; i++) {
setTimeout(() => {
console.log(i)
}, (i * 2000) )
}
const RandomUnderHundredNumber = (min,max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; /*min and max numbers are included */
}
let inter
const testFunction = () => {
inter = setInterval(() => console.log(RandomUnderHundredNumber(0,99)), 1000) // generate number between 0 and 99 every 1 sec
}
testFunction();
setTimeout(function( ) { clearInterval(inter); }, 5000); /* clear interval after 5 sec delay (optional) */
const printNumbersForEvery2Sec = (n)=>{
for (let i = 1; i <= n; i++) {
setTimeout( () =>{
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);
There are two solution to this problem.
Using let keyword, local scope.
const printNumbers = (n) => {
for (let i = 1; i <= n; i++) {
setTimeout( () => {
console.log(i);
}, i * 2000);
}
}
printNumbers(5);
Using var keyword, functional scope with the help of closures.
Wrap the setTimeout function with another function which has the value of the variable at that instance. Which console's log the correct value.
Example is shown below.
const printNumbers = (n) => {
for (var i = 1; i <= n; i++) {
function helper(num){
setTimeout( () => {
console.log(num);
}, num * 2000);
}
helper(i);
}
}
printNumbers(5);

Displaying Prime Numbers Using document.write()

I have an assignment for school that I seem to be stuck on.
Write a script that prints the prime numbers between 1 and 999 in a table that consists >of 10 columns. Use document.write() statements to create the table elements and a >counter variable to create the table so that it consists of 10 columns. The counter >variable should start with an initial value of 0 and be incremented by one each time your >code identifies a prime number and prints it in a table cell. Once the counter variable >reaches a value of 10 (meaning that 10 cells have been added to the current row), print >to start a new row and reset the variable to 0.
I cannot figure out where my error or errors are with the table row and counter. Also, I might have placed the document.write() methods in the wrong places. Currently, the table only displays vertically.
Here is what I have:
<script>
function primeNumbers(num) {
document.write('<table>');
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
Please, push me in the right direction and don't give me the answer. I want to see if I can figure this out.
Thanks!
There were some errors in your code:
The <table> opener was inside the function, so actually it was opening 1000 times.
The counter is reset, so you don't need to use modulus (%), just compare to 10.
A </tr> was missing in the end
Your function primeNumbers is misnamed, the best would be call isPrime
Here's the code:
function isPrime(num) {
if (num < 2) return false;
for (var i = 2; i < num; i++) {
if (num % i == 0) return false;
}
return true;
}
document.write("<table><tr>");
var counter = 0;
for (var i = 0; i < 999; i++) {
if (isPrime(i)) {
if (counter == 10) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</tr></table>');
Here's the fiddle working (I can't use document.write here, but you get the idea) http://jsfiddle.net/bortao/D2bzk/
Try this: http://jsfiddle.net/ezn7f/
<script>
function primeNumbers(num) {
if (num < 2)
return false;
for (var i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
document.write('<table><tr>');
var counter = 0;
for (var i = 0; i < 999; i++) {
if (primeNumbers(i)) {
if (counter % 10 == 0) {
document.write('</tr><tr>');
counter = 0;
}
counter++;
document.write('<td>' + i + '</td>');
}
}
document.write('</table>');
</script>
I wonder if this is what you are looking for though. I didn't change much in your code.

javascript show in cycle with delay

Simple example:
for (var i = 0; i < 10; ++i) {
console.log(i); // <--- should be show with delay in 300ms
}
Simple setTimeout using of course doesn't work... I guess there's should be using closures..
It's a simple matter of writing a recursive function:
function display(i)
{
if (i == 10) return;
setTimeout(function(){ console.log(i); display(i+1); }, 300);
}
Should do the job:
for (var i = 0; i < 10; ++i) {
(function(i) {
setTimeout(function(){console.log(i);}, i*300);
})(i);
}
You could use setInterval, like so:
var i = 0;
var id = setInterval(function(){
if (i == 9) clearInterval(id);
console.log(i);
i++;
}, 300);
Example here http://jsfiddle.net/MLWgG/2/

Categories

Resources