Tuesday, October 13, 2015

coding bat for loops 2: electric boogaloo

)1)Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".

stringBits("Hello") → "Hlo"
stringBits("Hi") → "H"
stringBits("Heeololeo") → "Hello"

public String stringBits(String str) {
String a = "";
  for(int i = 0;i < str.length();i++){
    if(i == 0 || (i % 2)== 0){
      a += str.substring(i,i+1);
    }
  }
return a;
}

2)Given a non-empty string like "Code" return a string like "CCoCodCode".

stringSplosion("Code") → "CCoCodCode"
stringSplosion("abc") → "aababc"
stringSplosion("ab") → "aab"

public String stringSplosion(String str) {
  String a ="";
  for (int i = 0; i <= str.length();i++){
  a += str.substring(0,i);
  }
  return a;
}
 3)Given an array of ints, return the number of 9's in the array.

arrayCount9({1, 2, 9}) → 1
arrayCount9({1, 9, 9}) → 2
arrayCount9({1, 9, 9, 3, 9}) → 3

public int arrayCount9(int[] nums) {
int a = 0;
  for(int i = 0; i< nums.length;i++){
    if(nums[i] == 9){
    a ++;
    }
  }
  return a;
}
4)Given an array of ints, return true if one of the first 4 elements in the array is a 9. The array length may be less than 4.

arrayFront9({1, 2, 9, 3, 4}) → true
arrayFront9({1, 2, 3, 4, 9}) → false
arrayFront9({1, 2, 3, 4, 5}) → false

public boolean arrayFront9(int[] nums) {
  for( int i = 0;i < nums.length;i++){
    if(i <= 3 && nums[i] == 9){
     return true;
    }
  }
  return false;
}
5)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

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









1 comment:

  1. For your first example, a simpler version might look like this:

    public String stringBits(String str) {
    String a = "";

    for(int i = 0; i < str.length(); i += 2) {
    a += str.substring(i, i+1);
    }
    return a;
    }

    You don't have to count by 1 in running through the for loop. Knowing that is a useful pattern for many other problems.

    This is a fine post for one day's work. Four more would make a set.

    ReplyDelete