0
我有這個揹包邏輯代碼工作在我的應用程序,但如果數組太大,我會經常在C數組上得到exc_bad_access code=2
,我找不到原因並希望你們可以啓迪我的代碼出了什麼問題。在客觀上創建一個適當的揹包邏輯C
//main chunk of code for Knapsack logic
-(NSMutableArray*)knapsackWithWeightArray:(NSMutableArray*)weightArray andLimits:(NSInteger)WLimits
{
NSMutableArray *keepSongs = [[NSMutableArray alloc]initWithCapacity:WLimits];//array to keep songs
NSInteger N = [weightArray count]; // number of items
NSInteger option[N+1][WLimits+1]; // opt[n][w] = max profit of packing items 1..n with weight limit w
bool sol[N+1][WLimits+1]; //does opt solution to pack items 1..n with weight limit w include item n?
NSInteger totalDuration = 0;
for (NSInteger n = 1; n<= N; n++) // no of items
{
for (NSInteger w = 1; w <= WLimits; w++) // loop for weights
{
WeightObject *wObj = weightArray[n-1];
NSInteger opt1 = option[n-1][w]; // crash here
NSInteger opt2 = INT32_MIN;
NSInteger knWeight = wObj.weight;
if (knWeight <= w)
{
opt2 = wObj.Value + option[n-1][w - knWeight]; // crash here
}
// select better of two options
option[n][w] = MAX(opt1, opt2); // crash here
sol[n][w] = opt2 > opt1; // ensure opt & sol same size. // crash here
}
}
// determine which items to take
for (NSInteger n = N, w = WLimits; n > 0; n--)
{
if (sol[n][w])
{
w = w - [weightArray[n-1]weight];
WeightObject *obj = weightArray[n-1];
totalDuration = totalDuration + obj.weight;
[keepSongs addObject:obj.songObj];
}
}
NSLog(@"knapsackWithWeightArray totalDuration %d",totalDuration);
return keepSongs;
}
有多大 「大」?在什麼尺寸的陣列中工作,在什麼尺寸的陣列中,它會破裂? – nhgrif
@nhgrif計數總是顯示n = 931 – Desmond