java - Concatenate and sort two int arrays in to one int array -
i know similar question has been asked , have researched website. have tried use of answers syntax still not working.
i going through previous examination paper build knowledge of java. please forgive errors in code, still learning java syntax.
here question:
implement method static int[] splice(int[] v, int[] w) (assuming lengths of v , w same) returns array in elements if v , w interleaved, starting first element of v, followed first element of w, followed second element of v, etc. example, if v = { 1, 3, 5 } , w = { 2, 4, 6 } call splice should return { 1, 2, 3, 4, 5, 6 }.
if input arrays have different lengths, method should return null.
here code:
import java.util.*; public class twoarraysbecomeone { public static void main(string[] args) { int[] v = { 1, 3, 5 }; int[] w = { 2, 4, 6 }; splice(v,w); } public static int[] splice(int[] v, int[] w){ if(v != w) { return null; } int[] x = new int[v.length + w.length]; (int = 0; < v.length; i++) { x[i] = v[i] + w[i]; } (int j = 0; j < x.length; j++) { system.out.println(x[j]); } return x; } }
i aware current syntax producing new array x = { 3, 7, 11 }. have removed various attempts try , concatenate code causing errors in code. require pointers answer question.
again, please forgive errors in code, still learning java.
thank you.
try this
public static void main(string[] args) throws exception { int[] v = { 1, 3, 5 }; int[] w = { 2, 4, 6 }; int[] res = splice(v, w); system.out.println(arrays.tostring(res)); } private static int[] splice(int[] v, int[] w) { if (v.length != w.length) { return null; } int[] = new int[v.length + w.length]; (int = 0; < v.length; i++) { a[i * 2] = v[i]; a[i * 2 + 1] = w[i]; } return a; }
output
[1, 2, 3, 4, 5, 6]
Comments
Post a Comment