We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi,
I have an array of Strings, {a,b,c,b,a,d,a,c,a}. I wanted to sort and replace them with integers, and change it as {0,1,2,1,0,3,0,2,0}
As the first step I tried removing the repeating elements from the array and made another array of strings {a,b,c,d}. Then I used a for loop and assigned values for these strings as {0,1,2,3}.
Now I wanted to replace the individual members in the first array of strings, where "a" is replaced with "0", "b" with "1", "c " with "2" and "d" with "3", and make an array {0,1,2,1,0,3,0,2,0}
String [] name = {"a", "b", "c", "b", "a", "d", "a", "c", "a"};
IntDict sortedName;
IntDict finalNameList;
void setup() {
size(600, 600);
smooth();
sortedName = new IntDict();
finalNameList = new IntDict();
for (int i=0; i<name.length; i++) {
finalNameList.increment(name[i]);
}
String [] names = sortedName.keyArray(); //// sorted array of strings {a,b,c,d}
for (int i=0; i<names.length; i++) {
finalNameList.set(names[i], i);
}
int [] values = finalNameList.valueArray(); ///// assigned values for a,b,c,d-- 0,1,2,3
////// now i wanted to replace the strings in the first array, name with the integers
for (int i =0; i<name.length; i++) {
name[i]= name[i].replaceAll(names[i], i-names.length);
println(name[i]);
}
}
void draw() {
background(125);
}
would be great if someone can help me with this. many thanks in advance :)
Answers
Hey.
In this special case, this can be really straight forward.
Note, that the example above only works if your "names" are single characters and the mapping is exactly as you described above (a:0, b:1, c:2, d:4).
@benja Thank you for the reply! :)
But I would like to know how it could be done if i replace the a,b,c, with some other names :) like tomato, potato,ginger,potato,tomato :)
Ok, then the approach with an IntDict would work.
I don't know what name should be mapped to what number, at the moment the first occurence in names has the lowest number.
Or could use a HashMap
@benja and @quark. Thanks a lot! :)
This is exactly what i wanted :) :)
Thank you @GoToLoop