Java > Warmup-2 > array123 (CodingBat Solution)

Problem:

Given an array of ints, return true if .. 1, 2, 3, .. appears in the array somewhere.

array123({1, 1, 2, 3, 1}) → true
array123({1, 1, 2, 4, 1}) → false
array123({1, 1, 2, 1, 2, 3}) → true


Solution:

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


2 comments :

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

    ReplyDelete
  2. With Java Stream

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

    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