In: Computer Science
Write a method weave that takes two arrays of ints, a and b, and that returns an array that contains the elements of a and b in the order a[0], b[0], a[1], b[1], etc.
If one of the arrays a or b is longer than the other, just add the extra elements at the end of the array.
In your solution, you can use only 3 arrays, namely the two arrays a, and b passed to the method and the array returned by the method.
You can't use any ArrayList, String, or Collection object.
You may assume that none of the arrays passed to the method are null, though one of them or both of them may be empty. If both arrays passed to the method are empty, just return an empty array.
Login to solve the question:
Step 1: As we have two arrays with different lengths, find the maximum length array size.
Step 2: Iterate a loop on the maximum length and start inserting elements in the result/final array, one by one.
Step 3: Check before appending the value whether the loop has reached the size of the array or not.
Step 4: Print the array.
Python Code, for the above logic:
#Weave method in python
----------------------------------
def weave(a, b):
result_array = []
for i in range(max(len(a),len(b))):
if(i<len(a)):
result_array.append(a[i])
if(i<len(b)):
result_array.append(b[i])
print(result_array)
----------------------------------
If we take an test case like:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [1, 2, 3]
Result:
[1, 1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9]
Snapshot of Code and result in Python 3.5 IDLE
Result:
Given that empty arrays are passed:
a=[]
b=[]
Result:
Note: The login is same whatever the programming language be. The above code is written in Python 3.5