I need a simplified (Pseudo/C++/JAVA) version of this Ruby code -
def P(a)a.min<0?0:a.max<1?1:(b=a*1;t=k=0;b.map{b[k]-=1;k+=1;t+=P(b)};t)end
def d(n,a)print n>1?((0..a[-1]).map{|i|d(n-1,a+[i])};"\n"):"#{P(a)} "end
d(ARGV[0].to_i,[ARGV[1].to_i])
For context, please visit Code golf- Pascal's pyramid and higher dimensions
Here is what I have so far, Pseudo code-
/**
* This prints out one 'row', specified by indices in array
* for Pascal's triangle of the given dimension
**/
void doit(int dimension, list array){
if(dimension>1){
for(int i=0;i<=array.lastElement();++i){
// Recursively call function with reduced dimension and
// extended array (count index appended)
doit(dimension-1, array.append(i));
}
print a newline;
}
else{
print Pascal(a);
}
}
/**
* This calculates a specific entry in the Pascal's triangle
**/
int Pascal(list array){
// Pascal(...,-1,...) = 0
if(minimum(array)<0){
return 0;
}
// Pascal(0,0,...,0) = 1
else if(maximum(array)<1){
return 1;
}
// Pascal(a,b,c,...) = Pascal(a-1,b,c,...) + Pascal(a-1,b-1,c,...) + Pascal(a-1,b-1,c-1,....)
else{
list work_array = array.copy();
int result = 0;
for(int i=0;i<work_array.length;++i){
// Decrement i'th element in array
work_array[i] = work_array[i]-1;
// Recursively call this function with modified array
// and add return value to result.
result = result + Pascal(work_array);
}
return result;
}
}
void main(firstArg, secondArg){
doit(firstArg.toInt(), new list [secondArg.toInt()]);
}
Implementation of above Pseudo Code in JAVA-
import java.util.*;
public class Pascal {
public static void main(String[] args) {
ArrayList<Integer> power=new ArrayList<Integer>();
power.add(3);
doit(4,power);
}
public static void doit(int dimension, ArrayList<Integer> array){
if(dimension>1){
for(int i=0;i<=(int) array.get(array.size() - 1);++i){
array.add(i);
doit(dimension-1,array);
}
System.out.println();
}
else{
System.out.print(Pa(array));
}
}
public static int Pa(ArrayList<Integer> array){
if((int)Collections.min(array) <0){
return 0;
}
else if((int)Collections.max(array) <1){
return 1;
}
else{
ArrayList<Integer> work_array = new ArrayList<Integer>();
//Collections.copy(work_array, array);
for(int i=0;i<array.size();i++){
work_array.set(i, array.get(i));
}
int result=0;
for(int i=0;i<work_array.size();++i){
work_array.set(i, work_array.get(i)-1);
result=result+Pa(work_array);
}
return result;
}
}
}
But this does not give the same output, it shows an error-
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.set(Unknown Source) at Pascal.Pa(Pascal.java:35) at Pascal.doit(Pascal.java:20) at Pascal.doit(Pascal.java:15) at Pascal.main(Pascal.java:7)
What am I doing wrong?
You don't have any elements in your ArrayList<Integer> work_array = new ArrayList<Integer>();
therefore your index ist out of range, since the size()
returns 0.