//*** CODE ***
/*
Online Java - IDE, Code Editor, Compiler
Online Java is a quick and easy tool that helps you to build, compile, test your programs
online.
*/
// This has been created to ensure I can utilize any random functions more efficiently.
// It is a creation of the permutations (with replacement) calculator.

//TEST CASES
// All done, see documentation


import java.math.*;
import java.util.*;

class Staircase
{
    int r;    //this will be equal to size of n since it needs to move through each row
    //of triangle.
    static int triangleNumber;  // from 0 to (triangle[0].length - 1)
    static long permutations;  //as per the calculator
    static StringJoiner sj;  //used to add the moves into the Set
    
    //it mantains this so that it can present values from triangle as part of results.
    static StringJoiner valuesTriangle = new StringJoiner(",");
    
    static StringJoiner indexesTriangle = new StringJoiner("");
    
    //this is to ensure no logical issues when storing maximum paths..
    static boolean processedMax=false;
    
    //stores number of triangles..
    static int numberTriangles;
    
    //these are defined triangles by end user
    static int [][][] triangle;
    
    //This will store detailed information on the triangle number, 
    //subset, subset number, values in triangle, and also if it is maximum value
    static String [][] outcomes;
   
    static int[] max;  //can not re-initialise this.
    
    //used to store the subsets into outcomes array, 
    //if it is the maximum or joint maximum across triangle.
    static int count=0;
    
    static int subsetEntry=0;   //this is required to output the subset entry
   
    int[] S; // this is the array containing the steps
    int p; // this is random number generated
    int cycles=0; // this is number of cycles completed for each c(n,r).. It is reset each time....
    
    static int totalcycles=0;   // this is useful to know the total cycles... Its static, so will keep running..
    
    //it needs to mantain value to ensure the offset from which the successful subsets are returned are not repeated...
    //strictly speaking, it does not need to remain static since this class is only
    //instantiated once.
    static int difference = 0;  //used to get difference in set size and offset to display results on screen...
   
    //it normally has to be static since every time the class is instantiated, it will lose its value otherwise....
    //this is now a good indicator to see the cycle on the screen and occurrence of subset totalling k.
    //since using permutations, static can be removed.
    static int i=0;
    
    //this stores the outcome into the outcomes array.
    static String outcome;
    
    static List <String> backupValuesSet = new ArrayList<>();
    
    //used to hold token.. Tokens are needed to analyse moves (valuesSet[entry])
    String temp;
    
    int temp1;
    
    Set<String> st; // this will contain the combinations for achieving total k
    Random rand = new Random(); // object created of type Random.
    // there is no sense of X getting smaller since its with replacement....
    // r is the sample size... This can not exceed n.. And MUST be equal to n
    
    static String[] valuesSet;   // this will be used to hold all values from the set... this will be modified..
    String []backupValuesSetBeforeModification;  // this will hold all values from set... (this will never be modified...)
    
    public Staircase(long permutations, int[] X, int r, Set<String> st, int[][][] triangle, int numberTriangles, String [][] outcomes, int[] max)
    {
        this.max=max;
        this.outcomes=outcomes;
        this.permutations=permutations;
        this.numberTriangles=numberTriangles;
        this.r=r;
        this.triangle=triangle;
        this.S=S;
        this.st=st;
        
        System.out.println("Testing Permutations: " + permutations);
        System.out.println("***There are triangles configured*** : " + numberTriangles);
       
        sj = new StringJoiner(","); // creating StringJoiner for the final output
        
        //this is used to test if the generated number will exceed the numbers in row for the triangle.
        boolean invalidIndex=false;
        
        int currentSetSize=0; // holds size of set before entry added
        int newSetSize; // holds size of set after entry added
        //int count=0;
        
        //this is used to ensure that subsets contain q valid moves...
        //i.e where q is equal to triangle.length (number rows...)
        int stepsCounter=0;
        
        int steps; // it will hold value of step generated randomly from r
       
        String subsetIntToString=""; //  since it needs to add number back into the StringJoiner, 
        //it has to be converted into a String first....
        
        int pos=0;  // used to index array X. Required so that it can check if previous number holds same value...
        //it will only increment at end of the loop to ensure correct validation check...
     
        int n=0;  // this is index used when comparing the valuesSet with backupValuesSet
       
        System.out.println("*************INITIAL VALUE OF  CYCLES: " + cycles);
        
        do
        {
            for (int q=0; q<r;q++) // processing up to r only since this is the sample size
            {
                //it needs to perform steps.
                //it will enter this if item from the sample does not provide
                //a valid index on the triangle...
                //it has already set the flag as per code outside of the loop.
                // all it does here, is just get the conditions ready as if
                //it was starting again..
                //empties StringJoiner which contains existing selection.
                //sets stepsCounter=0 again
                //invalidIndex=false   since its a new start..
                if (invalidIndex)
                {
                    sj=new StringJoiner(",");
                    invalidIndex=false;
                    stepsCounter=0;
                }
                
                //in ideal world, it would need something like this
                //do while loop since we know that ...
                //on a row 0:  [0][0][0]
                //on a row 1:  [1][0][0]  and [1][0][1]
                //the last index available is less than or equal to row number..
                //i.e  it will not attempt to perform moves such as (1,1,0)
                //since indexing  [0][0][1] is invalid.
                
                //we know that Set size is governed based on P(3,3) = 27
                //if we try to reduce number of entries.. the cycles will
                //be much larger than expectations.
                //since there are no permutations to fulfill 27.
                
                //we can perhaps examine this closer
                //since  (1,X,X) or  (2,X,X) are of no use whatsoever = 66% entries = 18 entries...
                //Also   (0,2,X) = 3 entries
                
                //I am examining this in my documentation..
                 
                 //holds random number
                 temp1 = rand.nextInt(X.length);
                  
                  //as per explanation above.
                  //this is valid selection..
                  if (temp1<=q)
                {
                    
                    p=temp1;
                    
                    //increase the counter
                    stepsCounter++;
                     
                }
                else
                {
                    //it also needs to set a flag here...
                    //since the q=0 will only take effect once it has reached
                    //end of execution of the for loop..
                    //note performing a break is costing one cycle also in
                    //do while loop, this has to be considered if triangle formation become
                    //improbable.. for instance several rows...
                    //We know only 0 is applicable for first row..
                    
                    invalidIndex=true;
                    
                    break;
                    
                   
                    
                }
                
                steps = X[p]; // step value
                //System.out.println("\nrandom number from original subset is : " + steps);
                sj.add(Integer.toString(X[p])); //adds the step into StringJoiner
                
                currentSetSize=st.size(); //current size of set
                
                //System.out.println("This is performing: " + (q+1) +" of " + r + "(r)");

                if (q==r-1) // if its on the last loop..
                {
                    //critical for testing... can not proceed if stepsCounter != triangles.length (number rows)
                    System.out.println("value of stepsCounter: " + stepsCounter);
                    
                //This would be the point where code is changed.
                //it would only perform this condition.
                st.add(sj.toString()); // it will only add it if the conditions are met above (size of r and Total=N)
                    
                    //preparing for next execution. StringJoiner has not been modified yet,
                    //so just performing a cleanse incase...
                    stepsCounter=0;
                    sj = new StringJoiner(",");
                }
            }
            
            newSetSize = st.size(); // new set size
            
            if (newSetSize>currentSetSize) //if larger, i.e a new combination, it will inform end user..
            {
                //System.out.println("This has been added into the set:");
                
            }
            cycles++; //increases cycles
            //it is increasing cycle every time its on the end of completing do while loop
            
            //grand total of cycles completed in the code....
            totalcycles++;
            
            //System.out.println("Number of cycles: " + cycles + "\n");
            
            //strictly speaking, if no modifications were completed above
            //in trying to reduce the subsets (please see documentation and calculator)
            //there were fixed permutations, hence could have set the do while condition to
            //set size < 28
            //However attempting this is no longer viable
            //trying this will cause code execution indefinitely since there are only
            //6 viable outcomes for triangle consisting of 3 rows.
            
            //Need to be careful with speculative amount:
            //Although it will over compensate since the permutations (27) expected is much
            //higher than the narrows subsets (6)
            //Also need to be aware that random number selection can void lots of cycles..
            //for instance if it selects a random number which is ArrayIndexOutOfBoundsException
            //for the triangle row.
        }while (cycles<permutations*40);

        
        // this is now getting the String in the set...
        //initially i will be 0 and it will output entire contents of the set..
        //once it has completed it first time, it will continue from its last position.
        //this is taken to be difference.... 
        
        //At this point in time, both are identical copies....
        valuesSet = st.toArray(new String[st.size()]);
        backupValuesSetBeforeModification = st.toArray(new String[st.size()]);
        
        // This next part was pivotal to ensure my technique was correct.
        //the backupValuesSet is populated below in following technique...
        //basically it is getting an untouched version of the String array above.
        //it is basically copy of the set which occurs several lines down....
        //backupValuesSet= new ArrayList<>(Arrays.asList(backupValuesSetBeforeModification));
        //So as expected when it hits hit and the set is empty, it will always show no content....
        //the reason why backupValuesSet is occuring after the valuesSet is since it can only make a backup once
        //valuesSet has been processed.
        //This also creates an effect of incremental backup in which backupValuesSet is one interation behind the valuesSet.
        //For this exercise it is purposeful since backupValuesSet can be searched against valuesSet
        //for duplicate values and eradicate them....
        
        System.out.println("******************Contents of the backup set");
        
        for (String g: backupValuesSet)
        {
            System.out.println(g);
        }
        
        ///again this is copy of the set.... It can be expected that once it starts populating, the valuesSet
        //will always be larger than backupValuesSet
        
        System.out.println("******************Contents of the valuesSet");
        
        for (String g: valuesSet)
        {
            System.out.println(g);
        }
        
        //checking every value in the backupValuesSet and setting it to ALREADY PROCESSED in 
        //valuesSet if it appears....
        
        for (String m: backupValuesSet)
        {
            n=0;
            do
            {
                if (m==valuesSet[n])
                {
                    //System.out.println("Match found in backupValuesSet: " + m);
                    //System.out.println("Match found in valuesSet: " + valuesSet[n]);
                    
                    //valuesSet[n]="ALREADY PROCESSED";
                    //System.out.println("valuesSet[n]" + " set to " + valuesSet[n]+"\n");
                    
                }
                
                n++;
                
            }while (n<valuesSet.length);
            //keep processing for all items in valuesSet
        }
        
        
        System.out.println("*************NEW VALUE CYCLES: " + cycles);
        System.out.println("*************RUNNING TOTAL CYCLES: " + totalcycles);
        
        System.out.println("***PROCESSING SET AT INDEX: " + (difference));
        System.out.println("**ENDING AT INDEX:***** " + st.size());
        
        
        //need be careful with this code, since if there is "ALREADY PROCESSED IN THE VALUESSET"
        //it will copy it again into the backupValuesSet
        //backup has to be restored from backupValuesSetBeforeModification.
        
        backupValuesSet= new ArrayList<>(Arrays.asList(backupValuesSetBeforeModification)); 
        
        
        //this now processes each String in the ValuesSet (which will be Strings not outputted yet)
        for (int entry=0; entry<valuesSet.length; entry++)
        {
            if (valuesSet[entry]!="ALREADY PROCESSED")    //as per above, it needs bypass these
            {
                subsetEntry++;    //static variable, it will keep track of combinations in the subset...
            
            System.out.println(valuesSet[entry] + "    Subset: " + subsetEntry  + "  at cycle number: " + totalcycles);
            
            
            //MAIN LOGIC OF THE NEW CODE OFFICIALLY STARTS HERE.
            System.out.println("**********THE TRIANGLE COUNT CHALLENGE***********");
            
            //method to obtain moves from the String valuesSet[entry]
            obtainMoves(valuesSet[entry]);
            }
        }
        //on first time it reaches above,    currentSetSize will be 0....
        //next time, currentsetSize will be previously newSetSize....
        //so it will perform incremental difference...
        
        //Set is zero index,  so it would have completed 5 items at  s.get(4)
        //s.size() is actual length...
        //if set size was 5 after  first  C(n,r) ,  it would have processed 0,1,2,3,4
        //difference would  be  5-0 = 5
        //so this is correct start point.....
        
        difference = newSetSize;
        
        }  //end of constructor...
        
        public void obtainMoves(String moves)
        {
            //keeping this local variable, no particular reason..
            int[] nMoves = new int [r];
            //keep this local again, it increments with token found..
            //and provide reference to row in triangle it will be manipulating..
            int i=0;
            
            //performs tokens of valuesSet[entry]
            StringTokenizer sTok = new StringTokenizer(moves,",");
            
            //keeps checking tokens and stores it into temp
            while (sTok.hasMoreTokens())
            {
                temp=sTok.nextToken();
                
                //stores moves in array...
                nMoves[i]= Integer.valueOf(temp);
                i++;
            }
            
            //method call to transpose the moves onto respective rows..
            //sequentially from top to bottom of triangle..
            performMoves(nMoves);
        }
        
        public void performMoves(int[] nMoves)
        {
            //again used local variable for clarity and congested at class level.
            int total=0;
            
            //This is counting through triangles
            //note since if there are multiple triangles, it will influence that
            //maximum totals are restricted for the respective triangle.
            //I introduced multiple triangles since its tidier than having
            //extensive code to initialise each seperately.
            //Also having several triangles has rendered adjustments to coding...
            for (int j=0; j<triangle[0].length; j++)
            {
                //Triangle it is processing.
                System.out.println("TRIANGLE " + (j));
            
            //this is processing the moves..
            for (int k: nMoves)
            {
                //critical to ensure that it follows triangle configuration.
                //although I have not perfomed triangle configuration validation in my code
                //this should ensure it is correct...
                //I will look at impact of changing elements in each row in test case...
                //and implement code to overcome issues..
                //it will most likely be try and catch statement..
                System.out.println("Elements in: " + i + " row of triangle:" + j);
                
                //critical, the indexes should correspond to the value on the triangle...
                System.out.println("Value at triangle: " + j + "  [" + i +  "]" + "[" +j + "]" + "[" +k + "]" + ":  "  + triangle[i][j][k]);
            
              //keeps running total
              total=triangle[i][j][k] + total;
              
              indexesTriangle.add("["+ Integer.toString(i)+"]" + "["+ Integer.toString(j)+"]" + "["+ Integer.toString(k)+"]" );
              
              //at moment, this is first time values are extracted from triangles...
              //and stored in a StringJoiner
              valuesTriangle.add(Integer.toString(triangle[i][j][k]));
              
              i++;  
            }
            
            //resets variable
            i=0;
            
            System.out.println("*******TOTAL: " + total +"\n");
            
            //inline with previous exercises this ensures that maximum value is not
            //applicable in two if scenarios.
            //prevents storing entry multiple times...
            processedMax=false;
            
            //this is critical output with all information...
            // it will be stored in outcomes array..
            
            outcome = "Triangle: " + j +  " | Subset:" + subsetEntry + " " +"(" + valuesTriangle + ")" + " (Indexes: " + indexesTriangle +")" +" | " +  "Max value: " + total;
            
            //critical to reset StringJoiners..
            valuesTriangle = new StringJoiner(",");
            indexesTriangle= new StringJoiner("");
            
            //note the j index represents the triangle number..
            //it has to mantain separate value in the 2D array....
            //if total is greater than existing, it stores as new total.
             if (total>max[j])
            {
                max[j]=total;
                
                //in previous code, I followed this approach to remove all entries
                //in the repository.
                //It can not be completed for this exercise, since it will wipe
                //outcomes for all triangle configurations...
                //outcomes = new String[2][(int)permutations];
                
                //need to wipe max information for that given triangle ONLY
                //need to wipe value in all rows for that given triangle.
                
                //sets index to 0
                int index=0;
                
                //we know the outcome repository is facilitated to support
                //all permutations for each triangle... So do while will execute until
                //it reaches outcomes[j].length.. 
                //it ultimately erases all entries for maximum since there is a new maximum.
                
                    do
                    {
                        //used for testing..
                        //System.out.println("val j: " + j);
                        //System.out.println("val index: " + index);
                        //System.out.println("val perm: " + permutations);
                        //System.out.println("val length row: " + outcomes[j].length);
                        
                        //note it is a String, so null is applicable value.
                        outcomes[j][index]=null;
                        //increments index
                        index++;
                        
                    }while (index<permutations);
                    
               //resets index
                index=0;
                
                //now the first index in outcomes will have the useful information in outcome.
                outcomes[j][0]=outcome;
                
                //System.out.println("IN HERE: " + outcomes[j][0]);
                
                //ensures information ready to store next location in outcomes repository
                count++;
                
                //setting this flag is critical.
                //since otherwise it would discover that the current total
                //is equal to max.. and store value again at next location
                //on outcomes array.
                //this variable is reset to default once it has performe
                //this execution of checking subset total against current maximum.
                processedMax=true;
            }
            
            //if it has identical total to existing (excluding the current item)
            if (total==max[j] && !processedMax)
            {
                //it stores the outcome in next available location..
                outcomes[j][count] = outcome;
                
                //System.out.println("IN HERE1: " + outcomes[j][count]);
                max[j]=total;
                
                //prepares next location
                count++;
            }
            
            //resets the StringJoiner holding values in subset for triangle
            valuesTriangle=new StringJoiner(",");
            total=0;
            }
            
            //a very quick message informing end user of the highest triangle.
            //again this is not scope of the challenge, but easily to gather this information.
            for (int c: max)
            {
                System.out.println("\nHighest total " + "triangle(" + triangleNumber+")" + "is: " + max[triangleNumber]);
                triangleNumber++;
            }
            
            //it has to be reset back to initial since it is ready to process next subset
            //inline with do while loop
            triangleNumber=0;
            
                 }  //end of method
} //end of class.


// I have performed several declarations here so that there is a balance
//in both classes.
//I also found that I was performing several illegal forward references if I tried
//to declare too much in the Staircase class.
//Example is trying to assign array dimensions using a variable which was declared
//a bit later in declarations..
//I also ran into several ArrayIndexOutOfBoundsException issues.. (some I could not resolve)
//Following this approach, eradicated several issues.
//unfortunately it has meant repeat variable names in BOTH classes.

public class Permutation
{
    //triangle number
    static int triangleNumber=0;
    
    static Staircase sc; //object of type Staircase
    
    //number triangles.
    static int numberTriangles;
    
    //array to hold maximum values for triangles..
    static int[] max;
    
    public static void main(String[] args) 
    {
        System.out.println("Welcome to Online IDE!! Happy Coding :)");
        
        
    Set <String> s = new HashSet<>(); // it will contain all combinations...
    int n;
    int r;
    
    int [] X = new int []{0,1,2};  
    // we know on top row of triangle 0 index will cover only 1 element
    //we know on 2nd row, indexes are 0 and 1  = 2 elements
    //we know on 3rd row, index is 0,1,2  = 3 elements.
    
    //This is defining two triangles, it can be increased
    int [ ][ ][ ] triangle = new int[ ][ ][ ] { 
                                        { {1},  {2}  }, 
                                        { {3,3}, {5,6}  },
                                        { {5,5,1}, {7,3,2}  },
                                      };
    
    //this could equally be performed utilizing 1 and 2.
    //lengths expected to be identical if triangles loaded properly...
    numberTriangles=triangle[0].length;
    
    //sets size to accomodate for numberTriangles
    max = new int[numberTriangles];
    
    int counter=0; // used in iterating set to keep count..
    
    //need to understand this example will use permutations with replacement
    //since 0 index for instance is applicable in each row.
    
    Map <Integer, Long> m; // this can stay outside loop since its not impacted by size of n and r
    
    n=X.length; //length of the array X of steps
    
    //System.out.println("Staircase size is:  " + Staircase.k);
    //System.out.println("Steps are: " + Arrays.toString(X));
    
    m= new HashMap<>(); //new instance is required to start process again...
    
     r=n;  // this is using all values 0,1,2  r=n  r=3
     
    //this is a slightly wasted execution..
    //but it is the only way to ascertain the dimension based on permutations.
    //NOTE: I tried to initialise this varaible on the staircase class, but 
    //ran into several ArrayIndexOutOfBoundsException during execution.
    long perms = Permutations(n,r);
    
    //sets dimensions to store outcomes.
    String [][] outcomes = new String[numberTriangles][(int)(perms)];
     
     //it will select an index to represent each row...
     //to ensure that it fulfills, the challenge, it will try
     //value in the set, extract values.. And try numbers in that order
     //and progress through the triangle..
    
    System.out.println("***PERMUTATIONS***(WITH REPLACEMENT)");
    System.out.println("PR(n,r) = nr");
    
    //Important for testing to ensure correct variables passed across
    //System.out.println("PASSING THIS ACROSS: **********");
    //System.out.println(numberTriangles);
    //System.out.println(Permutations (n,r));
    //System.out.println(max.length);
        
    
    //creates instance of Staircase and main execution of code...
    sc = new Staircase (Permutations (n,r), X, r,s, triangle, numberTriangles, outcomes, max);

   //Information to end user..
    System.out.println("\n\n*************SUMMARY HIGHEST RESULTS*************");
    
    System.out.println("*******TRIANGLES*********");
    
    //unfortunately there is no easy way to perform deepToString
    //on a section of the triangle row..
    //this in effect means full content of all rows shown (i.e all triangles)
    //it is not too critical since visually distinctions are prevelant
    
    for (int q=0;q<triangle.length;q++)
    {
      System.out.println(Arrays.deepToString(triangle[q]));
      triangleNumber++;
    
    }
    
    System.out.println("****************\n");
    
    triangleNumber=0;
    
    //Providing there is an entry in the repository, it will display the outcome...
    //the outer do loops ensures it processes triangleNumber until all triangles procesed.
    //since triangle number starts at 0, it will finish 
    //for instance if two triangles:
    //triangleNumber(1) < triangle[0].length (2)
    
    do
    {
    for (String str: sc.outcomes[triangleNumber])
    {
        
        if (str!=null)
        {
            
            System.out.println(str);
        }
    }
    triangleNumber++;
    }while(triangleNumber<triangle[0].length);

   
}
    //this is the simple technique of permutations with replacement.
    public static long Permutations (int n, int r)
    {
        System.out.println("P^R(" + n+","+r+") = " + "Math.pow(n,r)");
        return (long)Math.pow(n,r);
        
    }
}