RosettaCodeData/Task/LZW-compression/Objective-C/lzw-compression-1.m

87 lines
1.6 KiB
Mathematica
Raw Permalink Normal View History

2013-04-10 22:43:41 -07:00
#import <Foundation/Foundation.h>
#import <stdio.h>
@interface LZWCompressor : NSObject
{
@private
NSMutableArray *iostream;
NSMutableDictionary *dict;
NSUInteger codemark;
}
2014-04-02 16:56:35 +00:00
-(instancetype) init;
-(instancetype) initWithArray: (NSMutableArray *) stream;
2013-04-10 22:43:41 -07:00
-(BOOL) compressData: (NSData *) string;
-(void) setArray: (NSMutableArray *) stream;
-(NSArray *) getArray;
@end
@implementation LZWCompressor : NSObject
2014-04-02 16:56:35 +00:00
-(instancetype) init
2013-04-10 22:43:41 -07:00
{
self = [super init];
if ( self )
{
iostream = nil;
codemark = 256;
dict = [[NSMutableDictionary alloc] initWithCapacity: 512];
}
return self;
}
2014-04-02 16:56:35 +00:00
-(instancetype) initWithArray: (NSMutableArray *) stream
2013-04-10 22:43:41 -07:00
{
self = [self init];
if ( self )
{
[self setArray: stream];
}
return self;
}
-(void) setArray: (NSMutableArray *) stream
{
2014-04-02 16:56:35 +00:00
iostream = stream;
2013-04-10 22:43:41 -07:00
}
-(BOOL) compressData: (NSData *) string;
{
// prepare dict
2014-04-02 16:56:35 +00:00
for(NSUInteger i=0; i < 256; i++)
2013-04-10 22:43:41 -07:00
{
2014-04-02 16:56:35 +00:00
unsigned char j = i;
2013-04-10 22:43:41 -07:00
NSData *s = [NSData dataWithBytes: &j length: 1];
2014-04-02 16:56:35 +00:00
dict[s] = @(i);
2013-04-10 22:43:41 -07:00
}
2014-04-02 16:56:35 +00:00
NSData *w = [NSData data];
2013-04-10 22:43:41 -07:00
2014-04-02 16:56:35 +00:00
for(NSUInteger i=0; i < [string length]; i++)
2013-04-10 22:43:41 -07:00
{
2014-04-02 16:56:35 +00:00
NSMutableData *wc = [NSMutableData dataWithData: w];
2013-04-10 22:43:41 -07:00
[wc appendData: [string subdataWithRange: NSMakeRange(i, 1)]];
2014-04-02 16:56:35 +00:00
if ( dict[wc] != nil )
2013-04-10 22:43:41 -07:00
{
2014-04-02 16:56:35 +00:00
w = wc;
2013-04-10 22:43:41 -07:00
} else {
2014-04-02 16:56:35 +00:00
[iostream addObject: dict[w]];
dict[wc] = @(codemark);
2013-04-10 22:43:41 -07:00
codemark++;
2014-04-02 16:56:35 +00:00
w = [string subdataWithRange: NSMakeRange(i, 1)];
2013-04-10 22:43:41 -07:00
}
}
if ( [w length] != 0 )
{
2014-04-02 16:56:35 +00:00
[iostream addObject: dict[w]];
2013-04-10 22:43:41 -07:00
}
return YES;
}
-(NSArray *) getArray
{
return iostream;
}
@end