I was wondering if there is a way or a library I can use to do the following:
I have an arraylist of objects where each obj has a name.
The list needs to always be unique with a maximum of 5 elements like [E1,E2,E3]
If for example the list has initial form [E3,E5]
and I add an object, its name should be E1 and the list will be [E1,E3,E5]
or [E3,E5,E1]
it doesn't matter, as long as the name is unique and the item is added to the list starting from 1 to 5.
If add another item, it should be [E3,E5,E1,E2]
, always a unique name and between 1 and 5
These are my failed attempts,
StartNode node = new StartNode();
node.setName("E1");
for (int i = 0; i < circuit.getNbStartNodes(); i ) {
for (int j = 1; j <= circuit.getNbStartNodes(); j ) {
String test = ((StartNode) circuit.getStartNode(j)).getName();
if (("E" j).equalsIgnoreCase(test) && ("E" j).equalsIgnoreCase(node.getName()) ) {
break;
}
else
node.setName("E" j);
}
}
/*while (t <= circuit.getNbStartNodes()) {
for (int j = 0; j < circuit.getNbStartNodes(); j ) {
String test = ((StartNode) circuit.getStartNode(j)).getName();
if (("E" t).equalsIgnoreCase(test) || ("E" t).equalsIgnoreCase(node.getName()))
break;
else {
node.setName("E" t);
}
}
t ;
}
*/
/* for (int i = 1; i <= circuit.getNbStartNodes(); i ) {
for (int j = 0; j < circuit.getNbStartNodes(); j ) {
String test = ((StartNode) circuit.getStartNode(j)).getName();
if (!("E" i).equalsIgnoreCase(test)) {
node.setName("E" i);
t=0;
break;
}
}
if (t==0)
break;
else
continue;
*/
//String test = ((StartNode) circuit.getStartNode(i)).getName();
//for (int j = 1; j <= circuit.getNbStartNodes(); j ) {
// if (!("E" j).equalsIgnoreCase(test))
// node.setName("E" j);
//}
What did I do wrong in my code?
CodePudding user response:
- Create a small boolean array to track which names are already used and populate it with accordingly
- Find the first unused element and use it as id.
boolean[] used = new boolean[circuit.getNbStartNodes()];
for (int i = 0; i < used.length; i ) {
int index = Integer.parseInt(((StartNode) circuit.getStartNode(j)).getName().substring(1)) - 1; // should be in range 0..4
used[index] = true;
}
String name = "E";
for (int i = 0; i < used.length; i ) {
if (!used[i]) {
name = String.valueOf(i 1); // starting from 1
break;
}
}
System.out.println("free name: " name);
StartNode node = new StartNode();
node.setName(name);
// add new node to circuit, etc.