Java > Warmup-2 > noTriples (CodingBat Solution)

Problem:

Given an array of ints, we'll say that a triple is a value appearing 3 times in a row in the array. Return true if the array does not contain any triples.

noTriples({1, 1, 2, 2, 1}) → true
noTriples({1, 1, 2, 2, 2, 1}) → false
noTriples({1, 1, 1, 2, 2, 2, 1}) → false


Solution:

public boolean noTriples(int[] nums) {
  int count = 0;
  for (int i = 0 ; i < nums.length - 1;i++) { 
    if (i+2 <= nums.length -1) { 
      if (nums[i] == nums[i+1] && nums[i] == nums[i+2]) 
        return false;   
    }
  } return true;
}


2 comments :

  1. public boolean noTriples(int[] nums) {

    for(int i = 0; i < nums.length-2; i++){
    if(nums[i] == nums[i+1] && nums[i+1] == nums[i+2]){
    return false;
    }
    }
    return true;
    }

    ReplyDelete
  2. With Java Stream

    public static boolean noTriples(int[] nums) {
    return java.util.stream.IntStream.range(0, nums.length - 2)
    .noneMatch(i -> nums[i] == nums[i+1] && nums[i] == nums[i+2]);
    }

    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