Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update isMadhavArray.java #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 26 additions & 48 deletions Solutions/isMadhavArray.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,52 +17,30 @@ public static void main(String[] args){
}

static int isMadhavArray(int[] a){
int isMadhavArray = 0;
int arrayLength = a.length;
int startIndex = 0; // start index of current array elements under consideration
int endIndex = 0; // end index of current array elements under consideration
int n = 1; // track current length of array elements between start and end index
int currentSum = 0; // current sum of array elements
int sum = 0; // sum of elements of array between startIndex and endIndex
int currentLengthOfArray = 1; // length of array from index 0 to endIndex
int calculatedLengthOfArray = 1; // length calculating n * (n+1)/2
while(currentLengthOfArray <= arrayLength){
if(currentLengthOfArray == calculatedLengthOfArray){
for(int index = startIndex; index <= endIndex; index++){
sum += a[index];
}
}else{
// Fail ::: The length of a Madhav array must be n*(n+1)/2 for some n
isMadhavArray = 0;
break;
}
if((currentSum == sum) || (startIndex == endIndex)){ // startIndex == endIndex to satisfy initial condition
currentSum = sum;
sum = 0;
isMadhavArray = 1;
}else{
// Fail ::: The sum is not equal
isMadhavArray = 0;
break;
}
if(currentLengthOfArray == arrayLength){
// already at the end of the array
break;
}else{
startIndex = endIndex + 1;
endIndex = startIndex + n;
if((startIndex < arrayLength && endIndex < arrayLength)){
// operating inside the array bounderies
n++;
}else{
// adjusting boundries; so that lastIndex points last element of array
endIndex = arrayLength - 1;
n = endIndex - startIndex;
}
calculatedLengthOfArray = n * (n + 1)/2;
currentLengthOfArray = endIndex + 1;
}
}
return isMadhavArray;
boolean flag = false;
for (int i = 1; i <= a.length; i++) {
if (a.length == i * (i + 1) / 2)
flag = true;
}

if (!flag)
return 0;

for (int i = 1; i < a.length; i++) {
int sum = 0;
int x = i * (i + 1) / 2;

if (x >= a.length) {
break;
}

for (int j = x; j <= (x + i); j++) {
sum += a[j];
}

if (a[0] != sum)
return 0;
}
return 1;
}
}
}