Java > Array-1 > middleWay (CodingBat Solution)

Problem:

Given 2 int arrays, a and b, each length 3, return a new array length 2 containing their middle elements.

middleWay({1, 2, 3}, {4, 5, 6}) → {2, 5}
middleWay({7, 7, 7}, {3, 8, 0}) → {7, 8}
middleWay({5, 2, 9}, {1, 4, 5}) → {2, 4}


Solution:

public int[] middleWay(int[] a, int[] b) {
  return new int[] {a[1], b[1]};
}



4 comments :

  1. int lenA = a.length / 2;
    int lenB = b.length / 2;

    int arr[] = new int[2];


    for (int i = 0; i < lenA; i++) {
    arr[0] = a[lenA-1];


    }
    for (int i = 0; i < lenB; i++) {
    arr[1] = b[lenB];


    }


    return arr;
    }

    ReplyDelete
  2. int arr[]= new int[2];
    int lenA = a[a.length / 2];
    int lenB = b[b.length / 2];
    arr[0]=lenA;
    arr[1]=lenB;
    return arr;

    ReplyDelete
  3. public int[] middleWay(int[] a, int[] b)
    {
    return new int[]{a[a.length/2], b[b.length/2]};

    }

    ReplyDelete
  4. class MiddleWay
    {
    public static void main(String args[])
    {
    int a[]=new int[]{5,2,9};
    int b[]=new int[]{1,4,5};
    int lenA = a.length / 2;
    int lenB = b.length / 2;
    int arr[] = new int[2];
    for (int i = 0; i < lenA; i++)
    {
    arr[i] = a[lenA];
    System.out.print(+arr[i]);
    }
    for (int j = 0; j < lenB; j++)
    {
    arr[j] = b[lenB];
    System.out.print(","+arr[j]);
    }
    }
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact