![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Professional Programmer
Join Date: Mar 2005
Posts: 298
Rep Power: 4
![]() |
Recursion with int arrays
So I was playing around with the scrabble problem that was posted, but playing in C# and ran into a quandry, that I'm not 100% sure how to get out of
I have a recursion routine to figure out all the possible permutations of an array of int's as follows public static ArrayList permute(int[] v,int start, int n)
{
ArrayList data = new ArrayList();
if (start == n-1)
{
for (int i=0;i<v.Length;i++)
System.Console.Write("{0} ",v[i]);
System.Console.WriteLine();
data.Add(v);
}
else
{
for (int i= start; i<n; i++)
{
ArrayList back = new ArrayList();
int tmp = v[i];
v[i]=v[start];
v[start]=tmp;
back = permute(v,start+1,n);
foreach(object fromPermute in back)
data.Add(fromPermute);
v[start] = v[i];
v[i]=tmp;
}
}
return data;
}The problem is that when it does the data.Add(v) it's not really adding v to the data ArrayList, it's just adding a pointer to v to the ArrayList, as such when v gets updated, every pointer to v is pointing to a new version of it, and as such while this returns the right number of records, they are all the same. Is there any easy way I should be getting around this? Playing around with it some I know I CAN get around it but making it a comma delimited string, but that's not exactly elegant. |
|
|
|
|
|
#2 |
|
Professional Programmer
Join Date: Mar 2005
Posts: 298
Rep Power: 4
![]() |
Re: Recursion with int arrays
See and I answered my own question.
Changing the line from data.Add(v) to data.Add(v.Clone()) resolved the issue, as the return isn't v, it's a clone of v, as such and future changes to v don't effect the clone that was added to data. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Recursion to compute sequences. | emdiesse | Java | 4 | Mar 10th, 2008 6:18 PM |
| prime numbers now with arrays | gmann145 | C++ | 2 | Feb 19th, 2008 5:55 PM |
| probs w/ linked list and char arrays | bldnfx | C++ | 4 | Dec 31st, 2007 12:48 PM |
| Passing int arrays as arguments... | Soulstorm | C++ | 9 | Sep 3rd, 2007 9:13 AM |
| Arrays in PHP | MrMan9879 | PHP | 6 | Jan 12th, 2006 10:18 PM |