In: Computer Science
Problem: Given an integer array consisting of only 0’s and 1’s and a value k that denotes distance, determine if all the 1’s are at least k spaces away from each other.
Details:
Sample Input:
Input: {1,1,0,1,0,1}, k=2
Output: False
Input: {1,1,1,1,1}, k=0
Output: True
Input: {1,0,0,1,0,1}, k=1
Output: True
public class kSpace {
public static boolean validateKspace(int ar[], int k)
{
if(k>ar.length)
return
false;
int n=-1;
for(int i=0;i<ar.length;i++)
{
if(ar[i]==1)
{
if(n==-1) {
n=0;
}else {
if(n<k)
return
false;
else {
n=0;
}
}
}else {
n+=1;
}
}
return true;
}
public static void main(String[] args) {
int ar1[]={1,1,0,1,0,1};
System.out.println(validateKspace(ar1, 2));
int ar2[]={1,1,1,1,1};
System.out.println(validateKspace(ar2, 0));
int ar3[]= {1,0,0,1,0,1};
System.out.println(validateKspace(ar3, 1));
}
}