Reputation:
if I have the following 2D object of char
type:
aaaa...||
bbb..|ccc
ddddd..|d
the method countChars()
returns the number of the letters which are different, i.e. in the example above the result returned is 4
because there are a,b,c,
and d
characters. It does not count every single character ('.'
and '|'
are not included while counting) but counts the number of different characters in the array. Another example:
zzz.zz||
....tt|.
wwwwwwww
The above result returned by the method is 3
(z
, t
and w
)
In my code, I'm not getting the desired result.
public int countChars()
{
char originalChar = 0;
char anotherChar = 0;
int count = 0;
for(int r = 0; r < height; r++)
{
for(int c = 0; c < width; c++)
{
if(space[r][c] != '.' || space[r][c] != '|')
{
space[r][c] = originalChar;
}
count++;
space[r][c] = originalChar;
}
}
return count;
}
Upvotes: 1
Views: 78
Reputation: 136
Make an array of characters to hold unique characters. Each time you come to a char that is not a '.' or a '|' compare it to each character of the array, and if there is no match, add it to the array and increase your count. Here is some psudo code.
char[] uniqueChars = new char[26];
boolean unique = true;
int count = 0;
while(!at the end of the arrays){
char c = next character in the arrays;
for(int i = 0; i<count; i++){
if(uniqeChars[i]==c){
unique = false
}
}
if(unique){
uniqueChars[count] = c;
count++;
}
unique = true;
}
Upvotes: 0
Reputation: 26198
The problem is that you are trying to loop every single chars in the loop without even checking if they are already counted:
what you need to do is to create an array that will hold the already counted char:
sample below is without using any Collections framework.
public int countChars()
{
char originalChar = 0;
char anotherChar = 0;
int count = 0;
char [] countedChar = new char[255] //max char array
for(int r = 0; r < height; r++)
{
for(int c = 0; c < width; c++)
{
if(space[r][c] != '.' || space[r][c] != '|')
{
space[r][c] = originalChar;
continue;
}
if(countedChar[space[r][c]] != null) continue; //if char is already counted then continue;
countedChar[space[r][c]] = 's'; //add the index of the char array as the char number.
count++;
space[r][c] = originalChar;
}
}
return count;
}
Upvotes: 1
Reputation: 522741
I would use a Set
to handle this problem, since it eliminates the problem of counting duplicates.
public int countChars() {
Set<Character> set = new HashSet<Character>();
for (int r = 0; r < height; ++r) {
for (int c = 0; c < width; ++c) {
if (space[r][c] != '.' && space[r][c] != '|') {
set.add(new Character(space[r][c]));
}
}
}
return set.size();
}
This solution assumes that .
and |
are the only two characters which you want to exclude. If you had it in mind to count only letters (or letters and numbers) then please update your problem statement.
Upvotes: 2