Adding an alphagram ivar to Word which is calculated and then stored in the keyed...
[scrabbalize.git] / Source / Word.m
1 /*
2 * Scrabbalize
3 * Copyright (c) 2007, Blue Static <http://www.bluestatic.org>
4 *
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17 #import "Word.h"
18
19 @interface Word (Private)
20 - (void)createAlphagram;
21 @end
22
23
24 @implementation Word
25
26 /**
27 * Creates a new word object
28 */
29 - (id)initWithWord:(NSString *)aWord
30 {
31 if (self = [super init])
32 {
33 word = [aWord retain];
34 }
35 return self;
36 }
37
38 /**
39 * Destructor
40 */
41 - (void)dealloc
42 {
43 [word release];
44 [alphagram release];
45 [super dealloc];
46 }
47
48 /**
49 * Initialize an object from a keyed archive
50 */
51 - (id)initWithCoder:(NSCoder *)coder
52 {
53 self = [super init];
54 word = [[coder decodeObjectForKey:@"KAWord"] retain];
55 alphagram = [[coder decodeObjectForKey:@"KAAlphagram"] retain];
56 return self;
57 }
58
59 /**
60 * Encodes an object for serialization in a keyed archiver
61 */
62 - (void)encodeWithCoder:(NSCoder *)coder
63 {
64 [coder encodeObject:word forKey:@"KAWord"];
65 [coder encodeObject:alphagram forKey:@"KAAlphagram"];
66 }
67
68 /**
69 * Returns the word
70 */
71 - (NSString *)word
72 {
73 return word;
74 }
75
76 /**
77 * Gets the length of the word
78 */
79 - (int)length
80 {
81 return [word length];
82 }
83
84 /**
85 * Returns the alphagram
86 */
87 - (NSString *)alphagram
88 {
89 return alphagram;
90 }
91
92 /**
93 * Generates the alphagram for the word
94 */
95 - (void)createAlphagram
96 {
97 char *str = (char *)[word UTF8String];
98
99 int j;
100 for (int i = 1; i < [word length]; i++)
101 {
102 char temp = str[i];
103 for (j = i; j > 0 && temp < str[j - 1]; j--)
104 {
105 str[j] = str[j - 1];
106 }
107 str[j] = temp;
108 }
109
110 alphagram = [[NSString stringWithUTF8String:str] retain];
111 }
112
113 /**
114 * Description method
115 */
116 - (NSString *)description
117 {
118 return [NSString stringWithFormat:@"<Word:%@/%@>", word, alphagram];
119 }
120
121 @end