View Full Version : recursive و StackOverflowError
biodread
سه شنبه 18 شهریور 1393, 15:37 عصر
سلام دوستان
من یه فانکشن دارم که خودشو صدا میزنه
و در صدا زدن من محاسباتی رو انجام میدم
از اونجایی که تعداد صدا زدن های فانکشن زیاده اررور StackOverflowError نمایان میشه
آیا راهی داره که من بتونم تا موقعی که به تمامی محاسباتم برسم این اررور نیاد؟
ممنون
Nevercom
سه شنبه 18 شهریور 1393, 19:47 عصر
می تونید الگوریتم رو تغییر بدید که بجای Recursion از Iteration استفاده کنه.
مثلاً یه لیست یا پشته داشته باشید که هربار نیاز شد، عنصری بهش Push بشه و Iteration تا زمانی که عنصری در لیست موجود باشه ادامه پیدا می کنه.
و خب انجام اینکار تو یه ترد هم منطقی بنظر میرسه.
biodread
چهارشنبه 19 شهریور 1393, 11:07 صبح
من با گذاشتن یه تایم اوت مشکل حجم استک رو حل کردم
Iteration رو اگر با یه مثال بگی ممنون میشم
یعنی این میاد تو لوپ کار میکنه؟
biodread
چهارشنبه 19 شهریور 1393, 11:15 صبح
بله متوجه منظورت شدم
یه نمونه
import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Recursion vs Iteration
Compared the two processes, we can find that they seem almost same, especially in term of mathematical function. They both require a number of steps proportional to n to compute n!. On the other hand, when we consider the running processes of the two programs, they evolve quite differently.
In the iterative case, the program variables provide a complete description of the state. If we stopped the computation in the middle, to resume it only need to supply the computer with all variables. However, in the recursive process, information is maintained by the computer, therefore "hidden" to the program. This makes it almost impossible to resume the program after stopping it.
vBulletin® v4.2.5, Copyright ©2000-1404, Jelsoft Enterprises Ltd.