//*** 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 combinations (with replacement) calculator.
// It has used techniques I learnt including recursion and also memoization to speed up execution.
// I will incorporate this into Java applications I created previously..
//TEST CASES
// All done on My Approach

//NOTE THE CODE IS MASSIVELY COMMENTED OUT AND PRESERVED CRITICAL COMMENTS ON THE SCREEN....

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

class Staircase
{

    static boolean executeOnce=false;	

    int count;   
    static int k = 24; // values in subset will add up to value k
    int[] S; // this is the array containing the steps
    int p; // this is random number generated
    int total; // this is running total of the steps
    int cycles=0; // this is number of cycles completed for each c(n,r).. It is reset each time....
    int maxRValue;  // this is defined here also since there are limitations which is up to r=63
    
    static int totalcycles=0;   // this is useful to know the total cycles... Its static, so will keep running..
    
    //this has to be static since class is instantiated on each combination (n,r)
    //it needs to mantain value to ensure the offset from which the successful subsets are returned are not repeated...
    static int difference = 0;  //used to get difference in set size and offset to display results on screen...
   
    //it 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.
    static int i=0;
    
    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....
    // need to only add the stringJoiner (converted into string) into the set if the total is equal to N
    // if total goes over, it will continue adding until all cycles for C^R (n,r) has finished
    // Combinations is total of combinations for C^R(n,r)
    // r is the sample size... This can exceed n.. but there is also limit to r....
    
    String[] valuesSet;   // this will be used to hold all values from the set...
    
    public Staircase(long combinations, int[] X, int r, Set<String> st, int maxRValue)
    {
        this.S=S;
        this.st=st;
        this.maxRValue=maxRValue;
        System.out.println("Combinations: " + combinations);
        StringJoiner sj = new StringJoiner(","); // creating StringJoiner for the final output
        StringJoiner sj1 = new StringJoiner(",");  //creating StringJoiner to construct if all numbers same in X []
        
        int currentSetSize=0; // holds size of set before entry added
        int newSetSize; // holds size of set after entry added
        int count=0;
        int q; //used in the for loop to iterate through r
        int steps; // it will hold value of step generated randomly from r
        boolean allSameDigit=true;  // this is used to check if X array contains all number 1's....
        
        String subsetIntToString=""; //  since it needs to add number back into the StringJoiner, 
        //it has to be converted into a String first....
        
        int countSameNumber=0;
        int pos=0;  // used to index array X. Required so that it can check if previous number holds same value...
        int previousI; //value of previous number in X array
        
        //As per my documentation, there is a serious issue if all the numbers are same in selection..
        // Also it will create a massive hindrance since the r value in combinations will be driven too high...
        
        
        for (int i: X)
        {
            pos++;
            
            //keeps track of previous value in the array...
            previousI=i;
            
            //has to be converted to String in order to store in the StringJoiner....
            subsetIntToString =  Integer.toString(i);
            
            
            //only does previous check if not the first item...
            if (pos>0)
            {
            
            //if it is same number as previously, it mantains boolean true for allSameDigit
            //otherwise sets it to false and locks the loop...
            if (previousI!=i && pos>0 && !executeOnce)
            {
                allSameDigit=false;
            }
            }
        }
        
        
        //expect this to give quick solution.....
        //fills StringJoiner with all repetitive numbers to get total k
        do
        {
            sj1.add(subsetIntToString);
            countSameNumber++;
            
        }while(countSameNumber<(maxRValue/X[0]));
        
        System.out.println("*********************************");
        System.out.println(allSameDigit);
        
        if (allSameDigit)
        {
            System.out.println("\nk is equal to: " + k);
            System.out.println("This is the solution: " +  sj1.toString());
            //allSameDigit=false;
            
            //can also uncomment and continue execution if required...
            System.exit(0);
        }
        
        System.out.println("INITIAL VALUE OF  CYCLES: " + cycles);
        
        do
        {
            count=1;

            //sets count back to 1 when it has finished. This is visual check to ensure that r is not exceeded
            
            for (q=0; q<r;q++) // processing up to r only since this is the sample size
            {
                p= rand.nextInt(X.length); // if length 3, it will give index numbers 0-2... This is suitable
                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
                total=total+steps; //keeps running total
                //System.out.println("This is performing: " + (q+1) +" of " + r + "(r)");

                //reminding end user value N and running total
                //System.out.println("TOTAL HERE: " + total + "    k Value is: " + k);
                //if (total==N /*&& count<=r*/)
                
                if (total==k) // running total equals to defined k
                {
                    //System.out.println("This is stringjoiner right now: " + sj.toString());
                    //System.out.println("Count:" + count);
                    //System.out.println("current:" + currentSetSize);
                    //System.out.println("TOTAL: " + total);
                    //System.out.println("VALUE OF k: " + k);
                    //System.out.println("COUNT: " + count);
                    //System.out.println("r: " + r);
                    st.add(sj.toString()); // it will only add it if the conditions are met above (size of r and Total=N)
                    
                    count++;
                    
                }
                
                if (q==r-1) // if its on the last loop..
                {
                    sj = new StringJoiner(",");
                    total=0;
                    
                }
                
            }
            
            if (total>k)
            {
                
                total=0; //resets total
                sj = new StringJoiner(","); //creates new instance, resets contents...
            }
            
            newSetSize = st.size(); // new set size
            //System.out.println("new size: "+ newSetSize);
            
            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:");
                //System.out.println("Total is " + k +  ":  " + stringWithTotal24);
                
            }
            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");
            // can not set this to a certain set size... since it is giving total combinations (with replacement) and not 
            // related to placing items in certain order in which once combinations are known.
            // There are most likely distributions in statistics which might assist with the cycles...
            // This can only be placed in speculatively like throwing dice (a fixed time) and getting total....
            //the safest option for the maximum iterations is combinations x 10.
            //but in reality there is no guarantee that it would have covered all combinations at least once in that duration...
            
            
        }while (cycles<combinations*500);
        //}while (cycles<70);
        
        // 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.... 
        
        //this is only way to process the set entries readily since the iterator
        //becomes very tricky to control, similar to the StringTokenizer.
        
        //useful code from internet, but it does not appear the values are stored in the same order
        //as the Set (demonstrated in my code)
        valuesSet = st.toArray(new String[st.size()]); 
        
        System.out.println("*************NEW VALUE CYCLES: " + cycles);
        System.out.println("*************RUNNING TOTAL CYCLES: " + totalcycles);
        
        System.out.println("***PROCESSING SET AT INDEX: " + (difference+1));
        System.out.println("**ENDING AT INDEX:***** " + st.size());
        
        
        for (int i=difference+1; i<st.size(); i++)
        {
            
            System.out.println(valuesSet[i] + "    Subset: " + i  + "  at cycle number: " + totalcycles);
            
        }
        //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 class Combination
{
    public static void main(String[] args)
{
    System.out.println("Welcome to Online IDE!! Happy Coding :)");
    int originalNumber=0; // for moment it is declared a 0 to keep next line content...
    
    int n=originalNumber;
    
    int r; // this does not need be in for loop. user defined
    
    Set <String> s = new HashSet<>(); // it will contain all combinations...
    
    
    //int [] X = new int []{12,1,61,5,9,2}; //user defined
    //int [] X = new int []{1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
    int [] X = new int []{1,1,1,1,1,1}; //user defined
    
    
    int minimum; // the smallest value in X. This will assist with generating r value...
    
    int maxRValue; //upper limit for r in the loop to process 0<r<=maxRValue+1
    
    Staircase sc=null; //object of type Staircase
    //need to understand that r can be greater than n in replacement.......
    //r is taken from n objects
    // in this example, r can get larger....
    
    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));
    
    originalNumber=n; // this will remain constant during a full iteration..
    
    m= new HashMap<>(); //new instance is required to start process again...
    //r can be estimated as follows based on:
    //Maximum length of a combination is approximately (N/ minimum value in X)
    
    minimum=X[0];

    for (int i=0; i<X.length;i++)
    {
        if (X[i]<minimum && X[i]!=0)
        {
            minimum=X[i];
            
        }
        
    }
    maxRValue=(Staircase.k)/minimum;
    //informs end user of constraints...
    //System.out.println("Maximum value of r: " + (maxRValue+ 1) + " has been set using minimum value in set: " + minimum + " , which should be in proximity to N(" + Staircase.k + ")");
    //additional 1 added due to potential rounding errors
    
    //as per the findings in the documentation.....
    if (maxRValue>=64)
    {
        System.out.println("Value is too high computationally. It will be reduced to: " + (maxRValue-1));
    }

    
    for (r=0; r<=maxRValue+1; r++)
    {
        System.out.println("\n***COMBINATIONS*** (WITH REPLACEMENT)");
        
        System.out.println("C^R(n + r) = " + "(n+r-1)! / r!(n-1)!");
        
        System.out.println("C^R(" + n+","+r+") = " + (n+r-1)+ "!" + " / " + r+"!"+"("+(n-1)+")!");
        
        //creates instance of Staircase and main execution of code...
        sc = new Staircase (Combinations (n,r,originalNumber, m), X, r,s, maxRValue);
        
    }
    
    //this will output all the unique combinations onto the screen...
    // It might be worthwhile and experimenting with similar changes to myself in the code...
    // And ensure there are enough execution cycles left in the code to see these....
    //unfortunately due to my code logic, I simply could not get unique subsets during the main program execution...
    // This will be something I might try again in the future, or seek assistance from someone more knowledgable than me..
    
    
    System.out.println("\n\n*************ALL UNIQUE ENTRIES*************");

    Iterator iterator = sc.st.iterator();
    
    while (iterator.hasNext())
    {
        System.out.println(iterator.next());
    }
    
    
    
}

public static long Combinations (int n, int r, int originalNumber, Map factorialResults)
{
    long result=0;
    int denominator1; //denominator split two parts since there are two factorial calculations
    int denominator2; //denominator split two parts since there are two factorial calculations
    int Numerator=n+r-1; // Numerator
    int zero=0;
    long zeroFactorial = 1;
    // if no sample or objects, there are no outcomes...
    if (originalNumber==0 && r==0)
    {
        System.out.println("n and r can not both be equal to zero");
        //System.exit(0);
        
        return 0;
        
    }
    //this situation would occur if n is 0 only and r is any positive number accept 0 (if statement above)
    //for instance (C^R (n,r)) = (0,3) 0+3-1 = 2 2<3

    if (originalNumber==0 && originalNumber+r-1<r)
    {
        System.out.println("n+r-1 must be > or = to r");
        //System.exit(0);
        return 0;
        
    }
    
    if (Numerator>=1)
    {
        result = ((n+r-1)* (Combinations (n-1, r,originalNumber, factorialResults)));
        // this completes factorial for numerator
        factorialResults.put(Numerator,result); //result stored in the Map
        //factorialResults.put(n-1,result); //result stored in the Map
        //System.out.println("getting result back out numerator: " + (Numerator) + " " + factorialResults.get(n+r-1));
        
        if (n==originalNumber) // this will occur once
        {
            denominator1 = r;
            denominator2 = originalNumber-1;
            factorialResults.put(zero,zeroFactorial); //0! is equal to 1
            
            if (factorialResults.containsKey(denominator1) && factorialResults.containsKey(denominator2))
            {
                long returnValue = result / ((long)factorialResults.get(denominator1) *(long)factorialResults.get(denominator2));
                return returnValue;
                
            }
            
        }
        return result;
        
    }
    return 1; // it will reach here only when condition not met (Numerator>=1)
    }
    
}

