I have two arrays, one called words, the other called data. I have trouble shifting the strings from data into words. so far I have
public String[] shiftRightX(String[] words, String[] data)
{
for(int i= words.length - 1; i>0; i--)
{
words[i]=words[i-1];
for (int x = 0; x < data.length; x++)
{
words [0] = data[x];
}
}
return words;
}
it should result for example in this:
shiftRightX({"1", "2", "3"}, {"1", "2"}) → {"2", "1", "1"}
shiftRightX({"1", "2", "3"}, {"1"}) → {"1", "1", "2"}
shiftRightX({"1", "2"}, {"1", "2"}) → {"2", "1"}
however, it is shifting one extra time at the end.
Try to swap loops:
But this algorithm can be improved. Now it’s complexity is O(n*m) but it can be improved to O(n + m) if shift elements in
wordsarray todata.lengthposition instead of 1. But you need to be more careful in this case, because you can getArrayOutOfBoundException.