I have a 2d-array of variable number of rows and columns. The array is stored as JSON in the database. I have a requiremnt to add given elements after certain element specified by the user or remove a element specified by the user. Each elemet in the array is unique. The sample json value looks like [[4,5],[3,1,6,7],[34,21,55]]. Consider a situation I want to add 2 elements 12,13 after the element 7, the resultant array looks like [[4,5],[3,1,6,7,12,13],[34,21,55]]. And to remove if I given 1 as input the result should be [[4,5],[3,6,7,12,13],[34,21,55]].Using Gson I have parsed the json value stored to an array. How can I achieve it in Java with less time complexity.
My code to parse json data from db looks like
Gson gson = new GsonBuilder().create();
if (myTemplate.getQuestionOrder() != null) {
long[][] questionOrder = gson.fromJson(myTemplate.getQuestionOrder(), long[][].class);
}
Try the following method.
private static void insertAfter(long[][] array, int value, long[] insertion) {
boolean found = false;
for (int i = 0; i < array.length; i++) {
long[] sub = array[i];
for (int j = 0; j < sub.length; j++) {
if (sub[j] == value) {
long[] newSub = new long[sub.length + insertion.length];
System.arraycopy(sub, 0, newSub, 0, j + 1);
System.arraycopy(insertion, 0, newSub, j + 1, insertion.length);
System.arraycopy(sub, j + 1, newSub, j + 1 + insertion.length, sub.length - j - 1);
array[i] = newSub;
found = true;
break;
}
}
if (found) break;
}
}
Example usage:
insertAfter(questionOrder, 7, new long[]{12, 13});
System.out.println(gson.toJson(questionOrder));
This will print [[4,5],[3,1,6,7,12,13],[34,21,55]]
To remove an element you can use similar, but slightly modified, logic:
private static long[][] remove(long[][] array, int value) {
boolean found = false;
int emptyIndex = -1;
for (int i = 0; i < array.length; i++) {
long[] sub = array[i];
for (int j = 0; j < sub.length; j++) {
if (sub[j] == value) {
long[] newSub = new long[sub.length - 1];
System.arraycopy(sub, 0, newSub, 0, j);
System.arraycopy(sub, j + 1, newSub, j, sub.length - j - 1);
array[i] = newSub;
if (array[i].length == 0) emptyIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (emptyIndex >= 0) {
long[][] newArray = new long[array.length - 1][];
System.arraycopy(array, 0, newArray, 0, emptyIndex);
System.arraycopy(array, emptyIndex + 1, newArray, emptyIndex, array.length - emptyIndex - 1);
array = newArray;
}
return array.length == 0 ? null : array;
}
This method will remove the given item from the inner array and, if the inner array becomes empty, removes it from the outer array. It returns the modified array or null if it's empty.
Example usage:
questionOrder = remove(questionOrder, 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With