Reputation: 2102
Problem Statement:
Given an array of ints, compute if the array contains somewhere a value followed in the array by that value times 10. We'll use the convention of considering only the part of the array that begins at the given index.The initial call will pass in index as 0.
Examples:
public boolean array220(int[] nums, int index)
array220({1, 2, 20}, 0) → true
array220({3, 30}, 0) → true
array220({3}, 0) → false**
I'm stuck with the problem with no approach to solve it.
Upvotes: 0
Views: 1037
Reputation: 40336
for (int i = index; i < nums.length - 1; i++)
if (nums[i] * 10 == nums[i + 1]) return true;
return false;
Upvotes: 2
Reputation: 17826
Recursive answer just for the hell of it... also I wouldn't post this is there weren't already valid answers. Make an attempt and post what you tried.
public boolean array220(int[] nums, int index){
if(index >= nums.length - 1)
return false;
if(nums[index] * 10 == nums[index + 1]){
return true;
} else {
return array220(nums, ++index);
}
}
Upvotes: -1
Reputation: 52984
I'm not going to give you the answer as a Java program, since a number of folks have already done that.
When in doubt, try writing out the program in English (or any other native tongue). If you can't write it out in complete detail, write out what you can, and then refine in pieces.
Given an array of ints, compute if the array contains somewhere a value followed in the array by that value times 10. We'll use the convention of considering only the part of the array that begins at the given index.The initial call will pass in index as 0.
What do we know here? We have an array and a starting index. So, what do you want to do? Maybe that's a bit complicated, so if we were doing it by hand, how would you start?
Then refine that further:
You may notice that there is a small issue with step #2: You don't want to loop all the way to the end. Because if you do that, there won't be any "next" element to compare it to. So really you want to loop to the second-to-last element.
Continue refining. At some point you can translate directly to Java or whatever programming language you want. (If you can't do this last step, you need to add an additional step 0: Learn the programming language first)
Upvotes: 1
Reputation: 13672
I'll give you some psuedo code to work with.
Let `nums` be my array
Let `i` be the starting index
Let `index` be `i + 1`
for all indices < array's length, iterate
Let currNum be `array[index - 1]`
if currNum times 10 equals `array[index]`
return true
increment index
return false because we found no numbers that we true
Upvotes: 2