Created
March 27, 2017 16:22
-
-
Save deyindra/ea6acce3a304c1f693691162e0424d23 to your computer and use it in GitHub Desktop.
Associative Operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
//Space and time complexity O(n) | |
public abstract class AssociativeOperation { | |
protected int intVar; | |
protected AssociativeOperation(int intVar) { | |
this.intVar = intVar; | |
} | |
protected abstract int operation(int a, int b); | |
public static class AddOperation extends AssociativeOperation{ | |
public AddOperation() { | |
super(0); | |
} | |
@Override | |
protected int operation(int a, int b) { | |
return a+b; | |
} | |
} | |
public static class MultiplyOperation extends AssociativeOperation{ | |
public MultiplyOperation() { | |
super(1); | |
} | |
@Override | |
protected int operation(int a, int b) { | |
return a*b; | |
} | |
} | |
public int getIntVar() { | |
return intVar; | |
} | |
public static int[] getOutput(int[] array, AssociativeOperation associativeOperation){ | |
int[] finalOutput = new int[array.length]; | |
int temp = associativeOperation.getIntVar(); | |
for(int i=0; i<finalOutput.length;i++){ | |
finalOutput[i] = temp; | |
} | |
for(int i=0;i<finalOutput.length;i++){ | |
finalOutput[i] = temp; | |
temp = associativeOperation.operation(temp , array[i]); | |
} | |
temp = associativeOperation.getIntVar(); | |
for (int i = finalOutput.length - 1; i >= 0; i--) | |
{ | |
finalOutput[i] = associativeOperation.operation(finalOutput[i], temp); | |
temp = associativeOperation.operation(temp, array[i]); | |
} | |
return finalOutput; | |
} | |
public static void main(String[] args) { | |
AssociativeOperation operation = new AddOperation(); | |
int[] array = AssociativeOperation.getOutput(new int[]{4,5,6,7}, operation); | |
System.out.println(Arrays.toString(array)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment