user1927368
user1927368

Reputation: 55

how to shift strings from one array to another in java?

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.

Upvotes: 0

Views: 826

Answers (3)

Bernhard Barker
Bernhard Barker

Reputation: 55609

A faster version:

public String[] shiftRightX(String[] words, String[] data)
{
  if (data.length < words.length)
     System.arraycopy(words, 0, words, data.length, words.length - data.length);
  for (int i = Math.max(0, data.length - words.length); i < data.length; i++)
     words[data.length - i - 1] = data[i];
  return words;
}

Upvotes: 1

Apropos
Apropos

Reputation: 516

I think what you're trying to do is something like this:

 public String[] shiftRightX(final String[] words, final String[] data){
        String[] result = new String[words.length];
        int i = 0;
        for(String str : data){
            result[i] = str;
            i++;
        }
        for(int j=0;i<words.length;j++){
            result[i] = words[j];
            i++;
        }
        return result;
    }

Upvotes: 0

Mikita Belahlazau
Mikita Belahlazau

Reputation: 15434

Try to swap loops:

public String[] shiftRightX(String[] words, String[] data)
{
    for (int x = 0; x < data.length; x++)
    {
        for(int i= words.length - 1; i>0; i--)
        {
            words[i]=words[i-1];
        } 
        words[0] = data[x];
    } 
    return words;  
}

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 words array to data.length position instead of 1. But you need to be more careful in this case, because you can get ArrayOutOfBoundException.

Upvotes: 0

Related Questions