Essentially what you are describing is Fuzzy Logic.
I wrote you a fuzzy logic rules class which should handle what you are wanting to do.
Features:
- You can add your own custom rules easily with a method I've provided.
- You can check a value with a single
method
and get a string result (or nil
if it matches no rules).
- As it uses rules you can define whatever interval periods you wish.
Add a new rule:
[logic addRule:@"2.0" forLowerCondition:14.5 forUpperCondition:17.0];
Sample output (from the code below):
Result for 15.20 is: 2.0
Here is the code implementation.....
In your Main:
FuzzyLogic *logic = [[FuzzyLogic alloc] initWithRule:@"1.0" forLowerCondition:10.0 forUpperCondition:14.5];
[logic addRule:@"2.0" forLowerCondition:14.5 forUpperCondition:17.0];
[logic addRule:@"2.5" forLowerCondition:17.0 forUpperCondition:23.0];
double input1 = 15.2f;
NSLog(@"Result for %.2lf is: %@", input1, [logic fuzzyResultForValue:input1]);
[logic release];
FuzzyLogic.h:
#import <Foundation/Foundation.h>
@interface FuzzyLogic : NSObject {
NSMutableArray *conditions;
}
- (id) initWithRule:(NSString*)result forLowerCondition:(double)lower forUpperCondition:(double)upper;
- (void) addRule:(NSString*)result forLowerCondition:(double)lower forUpperCondition:(double)upper;
- (NSString*) fuzzyResultForValue:(double)input;
@end
FuzzyLogic.m:
#import "FuzzyLogic.h"
@implementation FuzzyLogic
enum {
lowerIndex = 0,
upperIndex,
resultIndex
};
- (id) initWithRule:(NSString*)result forLowerCondition:(double)lower forUpperCondition:(double)upper {
self = [super init];
if (self != nil) {
[self addRule:result forLowerCondition:lower forUpperCondition:upper];
}
return self;
}
- (void) addRule:(NSString*)result forLowerCondition:(double)lower forUpperCondition:(double)upper {
NSArray *rule = [[NSArray alloc] initWithObjects:[NSString stringWithFormat:@"%lf",lower],[NSString stringWithFormat:@"%lf",upper],result,nil];
if (conditions == nil) {
conditions = [[NSMutableArray alloc] initWithObjects:rule,nil];
} else {
[conditions addObject:rule];
}
}
- (NSString*) fuzzyResultForValue:(double)input
{
NSString *returnable = nil;
// Find the result
for (NSArray *cond in conditions) {
double lower = [[cond objectAtIndex:lowerIndex] doubleValue];
double upper = [[cond objectAtIndex:upperIndex] doubleValue];
if ( (input >= lower && input < upper) ) {
returnable = [cond objectAtIndex:resultIndex];
break;
}
}
if (returnable == nil)
{ NSLog(@"Error: Input met no conditions!");}
return returnable;
}
@end