Java > Array-2 > sameEnds (CodingBat Solution)

Problem:

Return true if the group of N numbers at the start and end of the array are the same. For example, with {5, 6, 45, 99, 13, 5, 6}, the ends are the same for n=0 and n=2, and false for n=1 and n=3. You may assume that n is in the range 0..nums.length inclusive.

sameEnds({5, 6, 45, 99, 13, 5, 6}, 1) → false
sameEnds({5, 6, 45, 99, 13, 5, 6}, 2) → true
sameEnds({5, 6, 45, 99, 13, 5, 6}, 3) → false


Solution:

public boolean sameEnds(int[] nums, int len) {
  boolean foo = true;
  
  for (int i = 0; i < len; i++) {
    if (nums[i] == nums[nums.length-len+i])
      foo = true;
    else
     foo = false; 
  }  
  return foo;
}


5 comments :

  1. public boolean sameEnds(int[] nums, int len) {

    for(int i = 0, j = nums.length - len; i < len; i++, j++) {
    if(nums[i] != nums[j]) return false;
    }
    return true;

    }

    ReplyDelete
  2. public boolean sameEnds(int[] nums, int len) {
    int[] arr1 = new int[len];
    int[] arr2 = new int[len];
    boolean check = true;

    for (int i = 0; i < len; i++){
    arr1[i] = nums[i];
    arr2[i] = nums[nums.length-1];
    }

    for (int i = 0; i < len; i++){
    if (arr1[i] == arr2[i])
    check = true;
    else
    check = false;
    }
    return check;


    }

    ReplyDelete
  3. public boolean sameEnds(int[] nums, int len) {

    int [] A = new int[len];
    int [] B = new int[len];


    for(int i=0;i<len;i++){
    A[i] = nums[i];}


    for(int i=0;i<len;i++){
    B[i] = nums[nums.length-len+i];}



    return Arrays.equals(A, B);

    }

    ReplyDelete
  4. public boolean sameEnds(int[] nums, int len) {
    int count=0;
    if (len==0) return true;
    for (int i=0; i<len; i++) {
    if (nums[i] == nums[nums.length-len+i]) count++;
    }
    if(count==len) return true;
    else return false;
    }

    ReplyDelete
  5. public boolean sameEnds(int[] nums, int len) {
    int length = nums.length;
    boolean isSame = false;
    int[] newArr1 = new int[len];
    int[] newArr2 = new int[len];

    for(int index = 0; index < len; index++) {
    newArr1[index] = nums[index];
    }

    for(int index = 0; index < len; index++){
    newArr2[index] = nums[length - len + index];
    }

    if(Arrays.equals(newArr1, newArr2)) {
    isSame = true;
    }

    return isSame;
    }

    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