Behaviour of Future.delayed() in dart - asynchronous

I generally program in C++ and aware how the Sleep function work, but learning dart (for flutter) now i came across this delay function
void countSeconds(s) {
for( var i = 1 ; i <= s; i++ ) {
Future.delayed(Duration(seconds: i), () => print(i));
}
}
It prints value of i after ith second, but shouldn't it print 1 after 1 sec, 2 after another 2 sec ( ie 3 ), 3 after another 3 secs (ie 6 sec) etc. How is it working?

This will print 1 after 1s, 2 after another 2s, 3 after 6s.
for( var i = 1 ; i <= 5; i++ ) {
await Future.delayed(Duration(seconds: i), () => print(i));
}
In asynchronous programming you need to await for futures to return result. Otherwise it will return everything immediately

Related

Climbing Stairs Problem ( Access of element in vector )

Below is a code for the problem of CLIMBING STAIRS https://leetcode.com/problems/climbing-stairs/
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n,0);
dp[0] = 1;
dp[1] = 2;
for(int i=2;i<n;i++){
dp[i] = dp[i-2]+dp[i-1];
}
return dp[n-1];
}
};
The code gives a RUNTIME ERROR of HEAP BUFFER OVERFLOW.
Looking at the code , if n==1 the code should return dp[n-1] i.e. dp[0] ,
but that does not seem to be the case.
I'm guessing the issue maybe related to access of elements in vector.
Can anyone please explain what could be the issue here ??
if n==1 the code should return dp[n-1] i.e. dp[0] , but that does not seem to be the case.
Yes.
But when n == 1, you call
dp[1] = 2;
so you access the second element when you have only one element.
And what about the case n <= 0 ?
So, maybe
int climbStairs(int n) {
if ( 0 >= 0 ) {
return ???;
} else if ( 1 == n ) {
return 1;
} else {
vector<int> dp(n,0);
dp[0] = 1;
dp[1] = 2;
for(int i=2;i<n;i++){
dp[i] = dp[i-2]+dp[i-1];
}
return dp[n-1];
}
}
The problem states the constraints are
1 <= n <= 45
You're going out of range when n is 1 (i.e. you only have dp[0] that scenario)

Recursive FIbonacci arm Assembly

Edit: I have removed my code as I do not want to get caught for cheating on my assignment. I will repost the code once my assignment has been submitted. I apologize for posting it on stack overflow, I just had no where else to go for help. Please respect my edit to remove the code. I have tried deleting it, but it will not let me as I need to request it.
[MIPS code I was trying to follow][1]
[C Code I was trying to follow][2]
I am trying to convert recursive fibonacci code into arm assembly but I am running into issues. When running my arm assembly, the final value of the sum is 5 when it should be 2. It seems as though my code loops but maybe one too many times. Any help would be much appreciated as I am new to this.
This is what your code is doing, and below is a test run.  This simply isn't a usual recursive fibonacci.
#include <stdio.h>
void f ( int );
int R2 = 0;
int main () {
for ( int i = 0; i < 10; i++ ) {
R2 = 0;
f ( i );
printf ( "f ( %d ) = %d\n", i, R2 );
}
}
void f ( int n ) {
if ( n == 0 ) { R2 += 0; return; }
if ( n == 1 ) { R2 += 1; return; }
f ( n-1 );
f ( n-2 );
R2 += n-1;
}
f ( 0 ) = 0
f ( 1 ) = 1
f ( 2 ) = 2
f ( 3 ) = 5
f ( 4 ) = 10
f ( 5 ) = 19
f ( 6 ) = 34
f ( 7 ) = 59
f ( 8 ) = 100
f ( 9 ) = 167
Either you started with a broken Fibonacci algorithm, or substantially changed it going to assembly.  I don't know how this can be fixed, except by following a working algorithm.
Note that in the C code the only addition is in the fib(n-1) + fib(n-2). In particular the special cases just do return 0; and return 1; respectively. Thus your else add 0/1 to sum lines are wrong. You should replace your additions with moves.
Also, you do MOV R1, R0 //copy fib(n-1) which is incorrect because the fib(n-1) has been returned in R2 not R0. That should be MOV R1, R2.
With these changes the code works, even if it is slightly non-standard.

Firebase (....ContinueWith(task => ...) in a For-Loop

First, this is the code:
for (int j = 1; j <= count; j++)
{
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
Debug.Log("j: " + j); // Here the Debug will show me that j = count
if (task.IsFaulted)
{
// ERROR HANDLER
}
else if (task.IsCompleted)
{
// Some Code Here
}
});
}
Ok, so my problem is that after the "....ContinueWith(task => ..." ' j ' will become directly equal to the count variable. Why this happens and how to solve it? Or is there another method to do that?
Ok, so my problem is that after the "....ContinueWith(task => ..." ' j
' will become directly equal to the count variable. Why this happens
and how to solve it?
That's because you used <= instead of <. With <=, j must be equals to count for the loop condition to be met and finish. If you want j to be less than count then use count-1 or simply use <.
So, that should be
for (int j = 1; i <= count-1; j++)
Or
for (int j = 1; i < count; j++)
Note that array starts from 0 not 1 so int j = 1; should be int j = 0; but I have a feeling that's what you wanted to do and you are starting the loop from 1 on purpose.
Finally, another problem is your variable being captured in a loop because you are using lambda in the ContinueWith function. See this post for more information. To use the j variable inside the ContinueWith lambda function, make a copy of it then use that copy instead of the j variable.
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
//MAKE A COPY OF IT
int jCopy = j;
Debug.Log("j: " + jCopy); // Here the Debug will show me that j = count
}
Complete fixed code:
for (int j = 1; i < count; j++)
{
db.Child("Some Child").GetValueAsync().ContinueWith(task =>
{
//MAKE A COPY OF IT
int jCopy = j;
Debug.Log("j: " + jCopy);
if (task.IsFaulted)
{
// ERROR HANDLER
}
else if (task.IsCompleted)
{
// Some Code Here
}
});
}

Why is this recursive function exceeding call stack size?

I'm trying to write a function to find the lowest number that all integers between 1 and 20 divide. (Let's call this Condition D)
Here's my solution, which is somehow exceeding the call stack size limit.
function findSmallest(num){
var count = 2
while (count<21){
count++
if (num % count !== 0){
// exit the loop
return findSmallest(num++)
}
}
return num
}
console.log(findSmallest(20))
Somewhere my reasoning on this is faulty but here's how I see it (please correct me where I'm wrong):
Calling this function with a number N that doesn't meet Condition D will result in the function being called again with N + 1. Eventually, when it reaches a number M that should satisfy Condition D, the while loop runs all the way through and the number M is returned by the function and there are no more recursive calls.
But I get this error on running it:
function findSmallest(num){
^
RangeError: Maximum call stack size exceeded
I know errors like this are almost always due to recursive functions not reaching a base case. Is this the problem here, and if so, where's the problem?
I found two bugs.
in your while loop, the value of count is 3 to 21.
the value of num is changed in loop. num++ should be num + 1
However, even if these bugs are fixed, the error will not be solved.
The answer is 232792560.
This recursion depth is too large, so stack memory exhausted.
For example, this code causes same error.
function foo (num) {
if (num === 0) return
else foo(num - 1)
}
foo(232792560)
Coding without recursion can avoid errors.
Your problem is that you enter the recursion more than 200 million times (plus the bug spotted in the previous answer). The number you are looking for is the multiple of all prime numbers times their max occurrences in each number of the defined range. So here is your solution:
function findSmallestDivisible(n) {
if(n < 2 || n > 100) {
throw "Numbers between 2 and 100 please";
}
var arr = new Array(n), res = 2;
arr[0] = 1;
arr[1] = 2;
for(var i = 2; i < arr.length; i++) {
arr[i] = fix(i, arr);
res *= arr[i];
}
return res;
}
function fix(idx, arr) {
var res = idx + 1;
for(var i = 1; i < idx; i++) {
if((res % arr[i]) == 0) {
res /= arr[i];
}
}
return res;
}
https://jsfiddle.net/7ewkeamL/

Maximum no. of nodes reachable from a given source in a Graph

I have a directed graph in which each node has exactly one edge, to one other node. I have to find the node from which the maximum number of nodes can be reached.
I tried to do it using a dfs, and store the information in the array sum[] but I get segmentation faults.
The graph is represented as an adjacency List of pair< int, int >. First is the destination, and second is the weight. In this problem weight = 0.
My dfs implementation:
int sum[V]; // declared globally, initially set to 0
bool visited[V]; // declared globally, initially set to false
int dfs( int s ){
visited[s]= true;
int t= 0;
for( int i= 0; i< AdjList.size(); ++i ){
pii v= AdjList[s][i];
if( visited[v.first] )
return sum[v.first];
t+= 1 + dfs( v.first );
}
return sum[s]= t;
}
Inside main():
int maxi= -1; // maximum no. of nodes that can be reached
for( int i= 1; i<= V; ++i ){ // V is total no. of Vertices
int cc;
if( !visited[i] )
cc= g.dfs( i ) ;
if( cc > maxi ){
maxi= cc;
v= i;
}
}
And the graph is :
1 2 /* 1---->2 */
2 1 /* 2---->1 */
5 3 /* 5---->3 */
3 4 /* 3---->4 */
4 5 /* 4---->5 */
What is be the problem in my dfs implementation?
You exit your dfs when you find any node that was already reached, but I have the impresion that you should run through all adjectent nodes: in your dfs function change the if statement inside for loop:
instead:
if(visited[v.first] )
return sum[v.first];
t+= 1 + dfs( v.first );
if(!visited[v.first] ) {
t+= dfs( v.first );
}
and initialize t with 1 (not 0). This way you will find size of connected component. Because you are not interested in the node from which you started then you have to decrease the final result by one.
There is one more assumption that I made: your graph is undirected. If it's directed then if you are interested in just solving the problem (not about complexity) then just clear visited and sum array after you are done with single run of dfs in main function.
EDIT
One more error in your code. Change:
for( int i= 0; i< AdjList.size(); ++i ){
into:
for( int i= 0; i< AdjList[s].size(); ++i ){
You should be able to trace segfault by yourself. Use gdb it's really usefull tool.

Resources