Counting number of unique adjacent pairs of same elements in an array - java

My function does not return the correct answer. My task is to count the two numbers in an array that are the same and next to each other here is a sample:
array_1 = {1,2,2,3,4,4,2}; ans = 2
array_2 = {2,2,3,4,4}; ans = 2
array_3 = {1,1,1,1,1,1,1}; ans = 1
array_4 = {1,2,3,4,2}; ans = 0
Here is my function. Observed output is given as comments.
public class countClampsTest
{
public static void main(String[] args)
{
int array_1[] = {1,2,2,3,4,4,2}; // expected result: 2
int array_2[] = {2,2,3,4,4}; // expected result: 2
int array_3[] = {1,1,1,1,1,1,1}; // expected result: 1
int array_4[] = {1,2,3,4,2}; // expected result: 0
System.out.println(countClamps(array_1)); // Returns 2
System.out.println(countClamps(array_2)); // Returns 1
System.out.println(countClamps(array_3)); // Returns 1
System.out.println(countClamps(array_4)); // Returns 0
}
static int countClamps(int[] arr) {
int result = 0;
int nextNext = 0;
for (int current = 0; current < arr.length - 1; current++) {
for (int next = current; next <= current + 1; next++) {
nextNext = next + 1;
if(nextNext >= arr.length) {
nextNext = arr.length -1;
}
if (arr[current] == arr[next] && current != next) {
if(arr[next] != arr[nextNext]) {
result++;
} else if(arr[next] == arr[nextNext] && arr.length % 2 == 0) {
result = 1;
}
}
}
}
return result;
}
}

I see a few issues in your code.
In the test:
if (arr[current] == arr[next] && current != next) {
you compare current with next; you could obtain the same result by starting the next loop at current+1 instead of current:
for (int next = current+1; next <= current + 1; next++) {
nextNext = next + 1;
...
if (arr[current] == arr[next]) {
...
}
}
which makes the loop redundant: it's only executed once, so the code above is equivalent to:
int next = current+1;
nextNext = next + 1;
...
if (arr[current] == arr[next]) {
...
}
Now in your inner test:
if(arr[next] != arr[nextNext]) {
result++;
} else if(arr[next] == arr[nextNext] && arr.length % 2 == 0) {
result = 1;
}
You can see that the first part of the second condition is always true, so it's equivalent to:
if(arr[next] != arr[nextNext]) {
result++;
} else if(arr.length % 2 == 0) {
result = 1;
}
The remaining condition means that you reset result to 1 if the array has an even number of elements (why?).
at the end of the array, result will not be incremented if the last two elements are equal, which is why you don't get the correct result in the second case.
Here is my solution:
static int countClamps(int[] arr) {
int result = 0;
for (int i = 1; i < arr.length; ++i) {
if (arr[i] == arr[i-1]
&& (i == arr.length-1 || arr[i] != arr[i+1])) {
++result;
}
}
return result;
}

A possible solution is: Stop you loop still one iteration earlier: use current < arr.length - 2 (this will cause nextNext to be within the array always). After your outer loop, just compare the last two elements of the array. If they are equal, add 1 to result. Done.
Except if the array has length 0 or 1, you will need to treat that specially.

I've added an extra boolean to keep track of already counted duplicates after each other.
static int countClamps(int[] arr) {
int result = 0;
int prev = 0;
boolean same = false;
for(int i = 0; i < arr.length; i++) {
if (i == 0) {
prev = arr[i];
} else {
if (arr[i] == prev) {
if (!same) {
result++;
same = true;
}
} else {
prev = arr[i];
same = false;
}
}
}
return result;
}

Once you've found a pair skip an index in loop.
public static int pairs(int[] list){
int pairs = 0;
for(int x = 1; x < list.length; x++){
if(list[x] == list[x-1]){
pairs++;
x=x+1;}
}
return pairs;
}

Related

How to check if every other element is even

My code only works for the first index, which just returns 8 true.
If I change the first index (nums[0]) to 9 for example, it skips the 3 and prints 4 true.
How do I make so that it checks the rest of them (every other element that is) so that it works for every other index?
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 == 0) {
System.out.print(nums[i] + " ");
return true;
}
}
return false;
}
public static void main(String args[]) {
int[] nums = {8,3,4,1,6,5,12,1};
System.out.println(solution(nums));
}
You have one (logical) error in your code, and one part that can be improved:
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 == 0) {
System.out.print(nums[i] + " ");
return true;
}
}
return false;
}
In your current code, true is returned on the first valid test, which means, you don't test the following cases. Change your code so you'll test them all, and only return during the flow, if you encounter an invalid value.
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 != 0) {
System.out.print(nums[i] + " ");
return false;
}
}
return true;
}
A second thing you can improve, is not checking for even indices each iteration. Just augment your i value by two instead of one:
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i+=2) {
if( nums[i] % 2 != 0) {
System.out.print(nums[i] + " ");
return false;
}
}
return true;
}
I think what you want to do is check all the even index and look if there are even you can do like this :
public static boolean solution(int[] nums) {
for(int i = 0; i < nums.length; i++) {
if(i % 2 == 0 && nums[i] % 2 != 0) {
System.out.print(nums[i] + " ");
return false;
}
}
return true;
}

Q: Solve almostIncreasingSequence in Java (Codefights)

I can't pass the final hidden test.Could you tell me what I miss?Thanks in advance.
Here are the statements: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
boolean almostIncreasingSequence(int[] sequence)
{
boolean increase = true;
List<Integer> list = new ArrayList<>();
for (int a :sequence )
{
list.add(a);
}
System.out.println(list);
if(list.size()==1)
{
return false;
}
for (int i = 0;i < list.size()-1 ;i++ )
{
if (list.get(1)<=list.get(0))
{
list.remove(0);
break;
}
if(list.get(i+1)<=list.get(i))
{
if (list.get(i+1)>list.get(i-1))
{
list.remove(i);
}
else
{
list.remove(i+1);
}
break;
}
}
for (int i =0;i<list.size()-1 ;i++ )
{
if (list.get(i+1)<list.get(i) || list.get(i+1)==list.get(i) )
{
increase = false;
}
}
return increase;
}
This is the linear solution I came up with. It involves muting the array so you don't have to loop through the array again.
boolean almostIncreasingSequence(int[] sequence) {
int removed = 0;
for (int i = 0; i < sequence.length - 2 && removed <= 2; i ++) {
int a = sequence[i];
int b = sequence[i+1];
int c = sequence[i+2];
if (a >= b) {
removed++;
sequence[i] = b -1;
}
if (b >= c){
removed++;
if (a == c) {
sequence[i+2] = b +1;
} else {
sequence[i+1] = a;
}
}
}
return removed <= 1;
}
Here's my solution with O(n) complexity
`
boolean almostIncreasingSequence(int[] sequence) {
int flag = 0;
int i = 0;
while(i<sequence.length-1){
if(sequence[i] < sequence[i+1]){
i = i+1;
continue;
} else {
flag = flag + 1;
if(i>0 && i+2 < sequence.length && sequence[i+1] <= sequence[i-1] && sequence[i+2] <= sequence[i]){
flag = flag + 1;
} else {
i = i+1;
}
if(flag > 1){
return false;
}
}
}
return true;
}
`
This worked for me
boolean almostIncreasingSequence(int[] sequence) {
int failed = 0;
boolean one_chance;
for(int i = 0; i < sequence.length - 1; i++){
int curr=i,next=i+1;
if(sequence[curr] >= sequence[next]) {
failed++;
if( curr > 0 && next < sequence.length - 1 ){
// Problem is not on head neither tail
// So check if removing one of 2 problematic numbers solves the issue
one_chance = false;
if( sequence[curr - 1] < sequence[next] )
one_chance = true ;
if ( sequence[curr] < sequence[next+1] )
one_chance = true ;
if( one_chance == false ) return false;
}
}
if( failed > 1 ) return false;
}
return true;
}
Spoiler Alert!
I could not pass the last hidden test either. So I spent 10,000 of my 12,300 coins (ouch!) to unlock them.
It turns out, the last test (#34) is expecting an outcome of true, and is passing an array of ints 100,000 long, in order from 1 to 100000! (So big that the only way I could see this was to do this in my code:
System.out.printf("length: %d%nlastValue:%d%n",
sequence.length, sequence[sequence.length - 1]);
I'm not sure why my code didn't pass, but I did at least unlock that hidden test, so now you can know what it is without having to spend coins to unlock it yourself.
I then got lazy and added this line at the top of my method to make it pass:
if (sequence.length == 100000
&& sequence[sequence.length - 1] == 100000) {
return true;
}
Here is a solution that works by using recursion to check the remainder of the array.
The issue is when the code hits a number that doesn't belong it can't be sure which of the two numbers is the offender so I just check the array starting from where the problem was detected and skipping the "bad" numbers. If it fails again while skipping a number it's game over.
This is in JavaScript, but it can easily be translated.
function almostIncreasingSequence(sequence) {
if(!sequence || sequence.length < 3) return true;
return checkSorted(sequence);
}
function checkSorted(arr, start = 0, skip) {
let last = arr[start === skip ? skip + 1 : start];
for(let i = start + 1; i < arr.length; i++) {
if(skip === i) continue;
let current = arr[i];
let lastIndex = skip === i - 1 ? i - 2 : i - 1;
let last = arr[lastIndex];
if(current <= last) {
if(skip !== undefined) return false;
return checkSorted(arr, i - 1, i) || checkSorted(arr, i - 1, i - 1);
}
}
return true;
}
def almostIncreasingSequence(sequence):
initial_length = len(sequence)-1
length = len(sequence)-1
count = 0
i = 0
while i < length:
if sequence[i] >= sequence[i+1]:
if i == 0:
sequence.pop(0)
count +=1
length = len(sequence)-1
i =0
elif sequence[i] == sequence[i+1]:
sequence.pop(i+1)
length = len(sequence)-1
i -= 1
count += 1
elif sequence[i] > sequence[i+1]:
if count ==0 and i + 1 == length:
return True
else:
if max(sequence) == sequence[i] and count == 0:
sequence.pop(i)
length = len(sequence)-1
i -= 1
count += 1
else:
sequence.pop(i+1)
length = len(sequence)-1
i -= 1
count +=1
else:
i += 1
length = len(sequence)-1
if count == 1:
if initial_length - length == 1:
return True
else:
return False
elif count > 1:
if initial_length - length > 1:
return False
else:
return True
boolean almostIncreasingSequence(int[] sequence) {
int count = 0;
int size = sequence.length;
if(size==1)
return true;
for(int i=0;i<size-1 && count<=1;i++){
if(sequence[i]>=sequence[i+1]) {
count++;
if(i>0 && (i+2)<size && sequence[i-1]>=sequence[i+1] && sequence[i]>=sequence[i+2]) {
count++;
}
}
}
return (count<=1);
}
boolean solution(int[] sequence) {
boolean increasing = true;
boolean isany = false;
for(int i=0;i<sequence.length;i++){
ArrayList<Integer> sequenceArrayList = new ArrayList();
for(int a : sequence){
sequenceArrayList.add(a);
}
sequenceArrayList.remove(i);
for(int j=0;j<sequence.length-2;j++){
if(sequenceArrayList.get(j)>=sequenceArrayList.get(j+1)){
increasing = false;
break;
}else{
increasing = true;
}
}
if(increasing){
isany = true;
}
}
return isany;
}

Double a decimal string

I am writing my own big integer class in java without imports and need a method for doubling a number of any size that is represented by a string. The code I have for this now works, but begins to take a long time once the numbers get bigger and bigger. I essentially create two arrays: the main array and the countdown array which both start as the same thing. Then, I run a while loop and increment the main array up and increment the countdown array down. When the countdown array reaches "0", I terminate the loop and the result is a new array with the new number doubled in size. Then of course I have if statements checking whether the arrays need to change the ten's place, etc.... here's what I have... Is there any way I can make it more efficient and quick?
public static String doubleDecimalString (String main) {
String countdown = main;
String finalBuild = "";
boolean runLoop = true;
//if zero is supplied, skip all the nonsense and just return 0
//else, loop through and find the true double
//was having trobule getting single digits to double correctly so i had to hard code this for now.
if (main.equals("0")) {
return main;
} else if (main.equals("5")) {
return "10";
} else if (main.equals("6")) {
return "12";
} else if (main.equals("7")) {
return "14";
} else if (main.equals("8")) {
return "16";
} else if (main.equals("9")) {
return "18";
} else {
//Array for ORIGINAL NUMBER
int[] mainPiece = new int[main.length()+2];
int arrayLength = mainPiece.length;
for ( int i = 0; i < main.length(); i++ ) {
mainPiece[i+2] = Integer.parseInt(main.substring( i, i+1));
}
mainPiece[0] = -1;
mainPiece[1] = -1;
//Array for COUNTDOWN NUMBER
int[] countdownPiece = new int[main.length()+2];
for ( int i = 0; i < main.length(); i++ ) {
countdownPiece[i+2] = Integer.parseInt(main.substring( i, i+1));
}
countdownPiece[0] = -1;
countdownPiece[1] = -1;
while ( runLoop ) {
//Increment and decrement the two arrays
mainPiece[arrayLength-1] += 1;
countdownPiece[arrayLength-1] -= 1;
//UPDATE MAIN ARRAY
if ( mainPiece[arrayLength-1] == 10 ) {
for (int x = arrayLength-1; x > 0; x--) {
if ( (mainPiece[x] == 10) && (mainPiece[x-1] != 9) ) {
mainPiece[x] = 0;
mainPiece[x -1] += 1;
} else if ( (mainPiece[x] == 10) && (mainPiece[x-1] == 9) ) {
mainPiece[x] = 0;
mainPiece[x -1] += 1;
x = arrayLength;
}
if ( (mainPiece[2] == 10) ) {
mainPiece[1] = 1;
mainPiece[2] = 0;
}
}
} // end main array
//UPDATE SIDE ARRAY
if ( countdownPiece[arrayLength-1] == -1 ) {
for (int x = arrayLength-1; x > 0; x--) {
if ( (countdownPiece[x] == -1) && (countdownPiece[x-1] > 0) && (x > 1) ) {
countdownPiece[x] = 9;
countdownPiece[x -1] -= 1;
} else if ( (countdownPiece[x] == -1) && (countdownPiece[x-1] == 0) && (x > 1) ) {
countdownPiece[x] = 9;
countdownPiece[x -1] -= 1;
x = arrayLength;
}
}
} //end side array
//tests whether the pieces need to be switched to -1 for scanning
for (int x = 0; x < arrayLength - 1; x++) {
if ( (countdownPiece[x] == -1 ) && (countdownPiece[x+1] == 0 ) ) {
countdownPiece[x+1] = -1;
}
}
//if the side array has reached "0" then the loop will stop and the main array will return the new doubled value
if ( (countdownPiece[arrayLength-1] == -1) && (countdownPiece[arrayLength-2] == -1) ) {
break;
}
} //end while loop
//transform array into string
finalBuild = "";
for (int T = 0; T < arrayLength; T++) {
finalBuild += (mainPiece[T] != -1) ? mainPiece[T] : "";
}
return finalBuild;
}
}
How about something like this (it basically does a multiply by two and accounts for carries):
private String doubleNumber(String number)
{
int doubleDig = 0;
int carry = 0;
StringBuilder sb = new StringBuilder();
for (int i = number.length() - 1; i >= 0; --i)
{
char c = number.charAt(i);
int origNum = Character.getNumericValue(c);
doubleDig = origNum * 2 + carry;
carry = doubleDig / 10;
doubleDig = doubleDig % 10;
sb.append(doubleDig);
}
if (carry > 0)
{
sb.append(carry);
}
return sb.reverse().toString();
}
Obviously this only handles integers.
I would use StringBuilder or List to build your doubled value.
Use a carry variable to store the carry amount and initialize to 0.
Start at the least significant digit, double the digits and add the carry.
Then set the carry to digit / 10, then the digit to digit % 10
Append digit to your builder or list.
After you loop through all your digits, check if carry is > 0 and append if needed.
Reverse the StringBuilder or list and join and you have your answer.
public class Doubler {
public static void main(String[] args) {
System.out.println(doubleDec("9123123123087987342348798234298723948723987234982374928374239847239487.23233099"));
}
public static String doubleDec(String dec) {
StringBuilder builder = new StringBuilder();
int carry = 0;
for (int i = dec.length() - 1; i > -1 ; i--) {
char charDigit = dec.charAt(i);
if (charDigit == '.') {
builder.append(charDigit);
} else {
int digit = Character.getNumericValue(charDigit);
if (digit == -1) {
throw new IllegalStateException("Invalid character in decimal string.");
}
digit = digit * 2 + carry;
carry = digit / 10;
digit = digit % 10;
builder.append(digit);
}
}
if (carry != 0) {
builder.append(carry);
}
return builder.reverse().toString();
}
}
// 18246246246175974684697596468597447897447974469964749856748479694478974.46466198

Need help count inversions with merge sort

The following code counts inversions in an array nums (pairs i,j such that j>i && nums[i] > nums[j]) by merge sort.
Is it possible to use the same approach to count the number of special inversions like j>i && nums[i] > 2*nums[j]?
How should I modify this code?
public static void main (String args[])
{
int[] nums = {9, 16, 1, 2, 3, 4, 5, 6};
System.out.println("Strong Inversions: " + countInv(nums));
}
public static int countInv(int nums[])
{
int mid = nums.length/2;
int countL, countR, countMerge;
if(nums.length <= 1)
{
return 0;
}
int left[] = new int[mid];
int right[] = new int[nums.length - mid];
for(int i = 0; i < mid; i++)
{
left[i] = nums[i];
}
for(int i = 0; i < nums.length - mid; i++)
{
right[i] = nums[mid+i];
}
countL = countInv (left);
countR = countInv (right);
int mergedResult[] = new int[nums.length];
countMerge = mergeCount (left, right, mergedResult);
for(int i = 0; i < nums.length; i++)
{
nums[i] = mergedResult[i];
}
return (countL + countR + countMerge);
}
public static int mergeCount (int left[], int right[], int merged[])
{
int a = 0, b = 0, counter = 0, index=0;
while ( ( a < left.length) && (b < right.length) )
{
if(left[a] <= right[b])
{
merged [index] = left[a++];
}
else
{
merged [index] = right[b++];
counter += left.length - a;
}
index++;
}
if(a == left.length)
{
for (int i = b; i < right.length; i++)
{
merged [index++] = right[i];
}
}
else
{
for (int i = a; i < left.length; i++)
{
merged [index++] = left[i];
}
}
return counter;
}
I tried this
while ((a < left.length) && (b < right.length)) {
if (left[a] <= right[b]) {
merged[index] = left[a++];
} else {
if (left[a] > 2 * right[b]) {
counter += left.length - a;
}
merged[index] = right[b++];
}
index++;
}
but there's a bug in the while loop, when left[a]<2*right[b] but left[a+n] maybe>2*right[b], for instance left array is {9,16} and right array is {5,6}, 9<2*5 but 16>2*5. My code just skip cases like this and the result number is less than it should be
The while loop in mergeCount serves two functions: merge left and right into merged, and count the number of left–right inversions. For special inversions, the easiest thing would be to split the loop into two, counting the inversions first and then merging. The new trigger for counting inversions would be left[a] > 2*right[b].
The reason for having two loops is that counting special inversions needs to merge left with 2*right, and sorting needs to merge left with right. It might be possible to use three different indexes in a single loop, but the logic would be more complicated.
while ( ( a < left.length) && (b < right.length) ) {
if(left[a] <= right[b]) {
merged [index] = left[a++];
} else {
counter += updateCounter(right[b],a,left);
merged [index] = right[b++];
}
index++;
//Rest of the while loop
}
//Rest of the mergeCount function
}
public static int updateCounter(int toSwitch, int index, int[] array) {
while(index < array.length) {
if(array[index] >= 2*toSwitch)
break;
index++;
}
return array.length-index;
}
Not very efficient, but it should do the work. You initialise index with a, because elements lower than a will never will never meet the condition.

Solution of twoTwo riddle on codingBat in Java

The question is about Solving this problem from codingBat in Java.
Problem Statement:
Given an array of ints, return true if every 2 that appears in the array is next to another 2.
twoTwo({4, 2, 2, 3}) → true
twoTwo({2, 2, 4}) → true
twoTwo({2, 2, 4, 2}) → false
First of all going by the problem statement that every 2 that appears in the array is next to another 2. then
do you think as suggested the outcome for the first inputs shown above
should be true?
twoTwo({4, 2, 2, 3}) → true
Because as I see it it the first 2 itself that appears in the array is next to 4 not 2
am I confused or it's a wrongly stated question? I had to grapple with the problem to somehow get the right code to crack the problem as below but it seems a hotch potch:
public boolean twoTwo(int[] nums) {
if(nums.length==0)
{
return true;
}
if(nums.length==1)
{
return !(nums[0]==2);
}
if((nums.length==2))
{
if((nums[1]==2)&&(nums[0]==2))
return true;
else
return false;
}
for(int i=0;i+2<nums.length;i++)
{
if((nums[i]!=2)&&(nums[i+1]==2)&&(nums[i+2]!=2))
return false;
}
if((nums[nums.length-2]!=2)&&(nums[nums.length-1]==2))
return false;
return true;
}
Any efficient alternate solutions are welcome.
Thanks!
Here's how I would do it. It's a bit easier to follow I think:
public boolean twoTwo(int[] nums)
{
for (int i=0; i<nums.length; i++)
{
if (nums[i] != 2)
continue;
if (i >= 1 && nums[i-1] == 2)
continue;
if (i < (nums.length-1) && nums[i+1] == 2)
continue;
return false;
}
return true;
}
The solution I got to the problem is below:
public boolean twoTwo(int[] nums) {
final int length = nums.length;
for (int i = 0; i < length;){
int count = 0; // Used to count following 2's
while(i < length && nums[i++] == 2){
count++;
}
if(count == 1){ // No adjacent 2's! Set doesn't work.
return false;
}
}
return true; // Didn't come across a lone 2
}
The way that I handle this, is that I count all the adjacent 2's. If the count is not 1, we are good. This means that there was either no 2 at that index, or a group of 2's was present. This holds, since we traverse the array in a single direction.
A good thing about this solution is that it will work for an array of any size. Note that it would have a linear complexity, even though 2 loops are present. They both just traverse using the same index value, only ever sweeping over the array once.
If at any time we find a 2, then check the following only to find there are 0 following 2's (denoted by count), we return false.
public boolean twoTwo(int[] nums) {
for (int i=0; i<nums.length; i++) {
if(nums[i] == 2) { //If current number is 2
if (
// if prev or next is not 2 return true
!(i-1>=0 && nums[i-1] == 2) &&
!(i+1<nums.length && nums[i+1] == 2)
) { return false; }
}
}
return true;
}
For the sake of simplicity and clean code, this code forces the check
i-1>=0 and i+1<nums.length in every iteration.
This can be avoided by iterating from (1...nums.length-1) and checking the edge cases separately.
I know this is an old question, but I came up with a new solution. Short, and with no complicated conditionals.
public boolean twoTwo(int[] nums) {
int position = -2;
boolean result = true;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 2) {
result = position == i - 1;
position = i;
}
}
return result;
}
Next to means either before or after. Loop through each number and check the values before and after to see if there's an adjacent 2. The special cases are when you're checking the 1st and last element because there won't be an element before or after to check.
public boolean twoTwo(int[] nums) {
if(nums.length == 1 && nums[0] == 2)
return false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 2) {
if(i == 0) { // check the next element
if(nums[i+1] != 2)
return false;
}
else if(i == (nums.length - 1)) { // check the previous element
if(nums[i-1] != 2)
return false;
}
else { // check both
if(nums[i+1] != 2 && nums[i-1] != 2)
return false;
}
}
}
return true;
}
Here is mine solution to two two's problem. I think my solution is clear i.e. understandable.
package codingbat.array2;
public class TwoTwo
{
public static void main(String[] args)
{
}
public boolean twoTwo(int[] nums)
{
boolean twoTwo = true;
for (int i = 0; i < nums.length; i++)
{
if (2 == nums[i])
{
if (i > 0 && 2 == nums[i - 1]
|| nums.length > i+1 && 2 == nums[i+1])
{
twoTwo = true;
i++;
}
else
{
twoTwo = false;
break;
}
}
}
return twoTwo;
}
}
public boolean twoTwo(int[] nums) {
for(int i = 0 ; i < nums.length; i++ ) {
int count = 0;
if(nums[i] == 2 ) {
while(i+1 < nums.length && nums[i+1] == 2 ) {
count ++;
i++;
}
if (count == 0 ) {
return false;
}
}
}
return true;
}
public boolean twoTwo(int[] nums) {
for(int i = 0;i<nums.length;i++)
if(nums[i]==2 && !isTwoBeforeOrAfter(nums,i))
return false;
return true;
}
private boolean isTwoBeforeOrAfter(int[] nums,int i){
return i+1<nums.length && nums[i+1]==2 || i-1>=0 && nums[i-1]==2;
}
public boolean twoTwo(int[] nums) {
float two = 0;
double count = 0;
for (int i = 0; i < nums.length; i++) {
if (i < nums.length - 2 && nums[i] == 2 && nums[i + 1] == 2 && nums[i + 2] == 2) {
return true;
}
if (i < nums.length - 1 && nums[i] == 2 && nums[i + 1] == 2) {
count++; //count the pair
}
if (nums[i] == 2) {
two++;
}
}
return ((count * 2) == two);
//each pair contain 2 ,two"s .so pair*2=total two counts
//count
}
public boolean twoTwo(int[] nums) {
boolean two = false;
boolean result = true;
for (int i=0; i<nums.length; i++) {
if (nums[i] == 2) {
if (two) {
result = true;
} else {
result = false;
}
two = true;
} else {
two = false;
}
}
return result;
}
Here's my solution. Enjoy.
public boolean twoTwo(int[] nums)
{
//If the length is 2 or more
if (nums.length >= 2)
{
//If the last char is a 2, but the one before it is not a char, we return false;
if (nums[nums.length - 1] == 2 && nums[nums.length - 2] != 2)
{
return false;
}
//If larger than three, we create a for loop to test if we have any 2s that are alone.
if (nums.length >= 3)
{
for (int i = 1; i < nums.length-1; i++)
{
//If we find a two that is alone, we return false;
if ((nums[i] == 2) && (nums[i-1] != 2 && nums[i+1] != 2))
{
return false;
}
}
}
//If we don't return false, we return true;
return true;
}
//If we have less than two characters, we return true if the length is 0, or \
//One the one number there is not a 2.
else
{
return ((nums.length == 0) || !(nums[0] == 2));
}
}
public boolean twoTwo(int[] nums) {
int len = nums.length;
Boolean check = false;
int count = 0;
for(int i=0; i<len ; i++){
if(nums[i]==2){
count++;
if((i<len-1 && nums[i+1]==2) || (i>0 && nums[i-1]==2)) check = true;
else check = false;
}
}
if(count==0) check = true;
return check;
}
public boolean twoTwo(int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++)
if (nums[i] == 2) count++;
else if (count == 1) return false;
else count = 0;
return count != 1;
}
Every time we encounter a 2, we increase the counter of consecutive 2s.
When it's not a 2 — but the counter indicates that there was a single 2 before it —, we know we've found a lonely 2.
Otherwise the search continues, resetting the 2-counter.
easy to understand)
static boolean twoTwo(int[] nums) {
int len = nums.length;
boolean result = true;
boolean found = false;
for(int i=0; i<len; i++){
//if it not 2, no meaning to go true other if-s
if(nums[i] !=2) {found = false; continue;}
// if current element is 2 and found is true(last element is 2)
if(nums[i] ==2 && found) result = true;
// if current element is 2, but last element not
if(nums[i] ==2 && !found){
found = true;
result = false;
}
}
return result;
}
This might be easier to follow if the other suggestions confuse you..
public boolean twoTwo(int[] nums) {
int len = nums.length;
if(len == 0) return true; // no 2's to worry about
if(len == 1) return nums[0] != 2; // make sure it's not a single 2
for(int i = 1; i < len -1; i++){ // loop for each except edge cases
if(nums[i] == 2 && nums[i-1] != 2 && nums[i+1] != 2) return false; // check surrounding
}
if(nums[len - 1] == 2) return nums[len - 2] == 2; //if last num is 2 check for 2 before it
return true; // made it here it's true
}
that one was tough for me... here's mine:
public boolean twoTwo(int[] nums) {
boolean two = false, res = true;
for (int i : nums) {
if (i == 2) {
if (two)
res = true;
else {
two = true;
res = false;
}
} else {
two = false;
}
}
return res;
}
One more alternative. Here is the main idea:
Convert array into String. Add a character different from "2" at the beginning and end of the string, to avoid going out of bounds.
Look for standalone "2" - if element of the string is equal to 2, check whether chars immediately before and after are also equal to "2". If they are it means that not all "2" are adjacent, and therefore method returns false.
public boolean twoTwo(int[] nums) {
// convert array to string
String text = "";
for (int i = 0; i < nums.length; i++) {
text += String.valueOf(nums[i]);
}
text = " " + text + " ";
// find standalone "2"
for (int i = 1; i < text.length() - 1; i++) {
if (text.charAt(i) == '2' && text.charAt(i - 1) != '2' && text.charAt(i + 1)
!= '2') {
return false;
}
}
return true;
}

Categories

Resources