1)Given a string, return a string made of the chars at indexes 0,1, 4,5, 8,9 ... so "kittens" yields "kien".
altPairs("kitten") → "kien"
altPairs("Chocolate") → "Chole"
altPairs("CodingHorror") → "Congrr
public String altPairs(String str) {
int a = 0;
String bricks = "";
for(int i = 0;i <str.length();i++){
if(a == 0 || a == 1){
bricks += str.substring(i,i+1);
}else if(a == 3){
a = -1;
}
a++;
}
return bricks;
}
2)Given an array of ints, return the number of times that two 6's are next
to each other in the array. Also count instances where the second "6"
is actually a 7.
array667({6, 6, 2}) → 1
array667({6, 6, 2, 6}) → 1
array667({6, 7, 2, 6}) → 1
public int array667(int[] nums) {
int a = 0;
for(int i = 0;i < nums.length -1; i++){
if (nums[i] == 6 &&(nums[i+1] == 6 || nums[i+1] == 7)){
a += 1;
}
}
return a;
}
3)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
public boolean noTriples(int[] nums) {
for(int i = 0; i < nums.length-2;i++){
if (nums[i] == nums[i+1] && nums[i] == nums[i+2]){
return false;
}
}
return true;
}
4)
Yup, that'll work ;-)
ReplyDelete