-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSumsUtil.m
91 lines (75 loc) · 1.81 KB
/
SumsUtil.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
// SumsUtil.m
// MacSums
//
// Created by Michael on 3/6/10.
// Copyright 2010 Michael Turner. All rights reserved.
//
#import "SumsUtil.h"
#import "My09Set.h"
@implementation SumsUtil
+(int) factorial:(int)n
{
if(n == 0) return 1;
return n * [self factorial:n-1];
}
+(int) minSum:(int)n
{
int s = 0;
for(int i = 0; i <= n; i++)
{
s += i;
}
return s;
}
+(int) maxSum:(int)n
{
int s = 0;
for(int i = 10 - n; i <= 9; i++)
{
s += i;
}
return s;
}
// generates sets not preserving order
+(NSPointerArray*) newCombinationCount:(int)selectionCount taken:(int)takenTimes
{
int n = selectionCount;
int r = takenTimes;
int nF = [self factorial:n];
int rF = [self factorial:r];
int nmrF = [self factorial:n - r];
int tc = nF / (rF * nmrF);
NSMutableArray *a = [[NSMutableArray alloc] initWithCapacity:r];
NSPointerArray* c = [[NSPointerArray alloc] init];
for(int i = 0; i < takenTimes; i++)
{
//a[i] = i;
[a insertObject:[NSNumber numberWithInt:i] atIndex:i];
}
[c addPointer:[[[My09Set alloc] initWithNSArray:a] autorelease]]; // start with first array
for(int t = 1; t < tc; t++)
{
int i = takenTimes - 1;
while ([[a objectAtIndex:i]intValue] == selectionCount - takenTimes + i) {
i--;
}
//while(a[i] == selectionCount - takenTimes + i) { i--; }
[a replaceObjectAtIndex:i withObject:[NSNumber numberWithInt:[[a objectAtIndex:i] intValue]+1]];
//a[i] = a[i]+1;
for(int j = i + 1; j < takenTimes; j++)
{
[a replaceObjectAtIndex:j withObject:[NSNumber numberWithInt:[[a objectAtIndex:i] intValue] + j - i]];
//a[j] = a[i] + j - i;
}
[c addPointer:[[[My09Set alloc] initWithNSArray:a ] autorelease]];
}
[a release];
return c;
}
+(id)alloc
{
[NSException raise:@"Cannot be instantiated" format:@"Static class SumsUtil cannot be instantiated"];
return nil;
}
@end