/*
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 NcR    combinations 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..

//ISSUES:
// THIS HAS BEEN CREATED USING n = 3 and r =3
// IT HAS NO ISSUES WITH THESE SET.
// THE FIRST PART WILL BE TO TRY AND ACCOMODATE FOR A LARGER   n=4  and r=4
// HENCE I HAVE INCLUDED ONE COMMENTED SWITCH STATEMENT ALSO
// I CAN THEN TRY TO SEE WHAT HAPPENS IF R is reduced
// UNLIKE OTHER PROBLEMS LIKE GENERATING AND CHAINING A RANDOM NUMBER INTO BIGGER ONE, 
// THERE IS A BIT MORE TECHNICAL PROCESSING TO TRUNCATE THE SET ENTRY AND PERFORM CONVERSIONS FOR CURRENCIES...
// IT IS ALSO OPEN TO INTRODUCING TRANSACTION FEES IN THE SWITCH STATEMENT
// HOWEVER THIS IS NOT PART OF THE PROBLEM

// I HAVE NOW ADJUSTED SO THAT IT DOES NOT SHOW CONVERSIONS IF THE SET HAS ALREADY BEEN PROCESSED.

// NEED TO REMEMBER   SAMPLE IS R     AND OBJECTS IS N....
// R IS SMALLER THAN N

// Tried following... its largely successful... not sure how to get any closer....
//r=2  n=3     PASS
//r=4  n=4     PASS
//r=2  n=4     PASS
//r=3  n=4     PASS
//r=2  n=2     FAILS (it processes n currencies)
//r=3  n=3     FAILS (it processes n currencies)
//r=1  n=2     PASS  (THE CODE BREAKS SINCE ONLY ONE CURRENCY, NEED TO PROMPT END USER)
//r=1  n=1     FAILS  (it processes n currencies)



import java.math.*;
import java.util.*;
import java.math.RoundingMode;  
import java.text.DecimalFormat;  

class conversions
{
    public conversions (String currency, Double amount)
    {
        
    }
}


class exchangeCombinations
{
    DecimalFormat format = new DecimalFormat("##. 00");
    
    String currencyExchange="";
    double exchange;
    double amount=50.0;
    double currency;
    String temp1;
    int k;
    String fullConversionsReverse;
    String exchangeArbitrageFlipped;
    String outcome="";
    Double ArbitrageChecker;
    String fullConversions;
    String exchangeArbitrage;
    String newCurrency;
    String initialAmount;
    long combinations;
    int count;
    String temp;
    StringJoiner sj = new StringJoiner("=>");
    Set <String> s = new HashSet <>();   // this will store the  combinations
    
    int startPos;
    int endPos;
    
    //List <String> lst = new ArrayList<>(Arrays.asList("$","£","€"));  // this is list of numbers. In future, it will be chosen to use other data
    List <String> lst = new ArrayList<>(Arrays.asList("$","£","€","¥"));  // this is list of numbers. In future, it will be chosen to use other data
    
    
    List <String> copy = new ArrayList<>(lst);  //keeps a copy    // this list keeps a copy since during program execution the top list is modified
    
    StringBuilder sb;
    int currentSetSize;
    boolean exitCondition;
    int n;
    int r;
    
    
    public String currencyExchange(String exchangeCurrencies, String numberArray)
    {
         
      /*   
         switch (exchangeCurrencies)
    {
        case "$=>£":
            exchange=0.83;
            currency = amount*exchange;
            break;
        case "$=>€":
            exchange=0.92;
            currency = amount*exchange;
            break;
        case "£=>$":
            exchange=1.30;
            currency = amount*exchange;
            break;
        case "£=>€":
            exchange=1.20;
            currency = amount*exchange;
            break;
        case "€=>$":
            exchange=1.09;
            currency = amount*exchange;
            break;
        case "€=>£":
            exchange=0.83;
            currency = amount*exchange;
            break;
    }
    */
    
    
    switch (exchangeCurrencies)
    {
        case "¥=>£":
            exchange=0.0051;
            currency = amount*exchange;
            break;
        
        case "¥=>$":
            exchange=0.0067;
            currency = amount*exchange;
            break;
            
        case "¥=>€":
            exchange=0.0061;
            currency = amount*exchange;
            break;
        
        case "$=>£":
            exchange=0.83;
            currency = amount*exchange;
            break;
        case "$=>€":
            exchange=0.92;
            currency = amount*exchange;
            break;
        case "$=>¥":
            exchange=149.97;
            currency = amount*exchange;
            break;
        
        case "£=>$":
            exchange=1.30;
            currency = amount*exchange;
            break;
        case "£=>€":
            exchange=1.20;
            currency = amount*exchange;
            break;
            
         case "£=>¥":
            exchange=195.30;
            currency = amount*exchange;
            break;
            
        case "€=>$":
            exchange=1.09;
            currency = amount*exchange;
            break;
        case "€=>£":
            exchange=0.83;
            currency = amount*exchange;
            break;
         case "€=>¥":
            exchange=162.65;
            currency = amount*exchange;
            break;
    }
    
    amount=currency;
    temp1=numberArray;
    return numberArray+format.format(currency);
    
   //System.out.println("This is your new currency: " +numberArray+ currency);
   
    }
    
    enum currencies
    {
        Dollar("$"),
        Pound("£"),
        Euro("$");
        
        final String currency;
        
        currencies (String currency)
        {
            this.currency=currency;
            
        }
    }
    
    
    public exchangeCombinations(long combinations, int n, int r)
    {
        this.combinations=combinations;
        int randomNumber;    // random  number generated
        String numberArray="";     // value at index of randomNumber in the set
        String conversion;
        this.n=n;
        this.r=r;
        
        int totalCurrenciesAvailable;
        totalCurrenciesAvailable=lst.size();
        int differenceObjectsAndTotalCurrenciesAvailable;
       
        
        Random rand = new Random();  // generates random number
        
        System.out.println("Combinations: " + combinations +"\n");   //number combinations without replacement
        
        do
        {
            System.out.println("\n");
            
            lst = new ArrayList<>(copy);     // each time it starts again, it has to get the original ArrayList back
            
            temp="";   // this is used concatenation of value before it is stored in the set....
            
            sj=new StringJoiner("=>");
            
            do
            {
            // this is crucial part since if the do while loop evaluates as !lst.empty(),  this will be suitable if 
            // the sample(r) is the same value as n (objects).  Since list consists of n objects.
            // But if the end user decides to choose combinations of 2 (r) objects out of 3 (n) sample, the while loop
            // needs adjustment.
            // alternative boolean statements are required.
            
            // currently statement in end of do while is:  
            //  !lst.isEmpty()  -    this is valid for full list
            //  lst.size() >=(n-r)   is required if r is less than n
            
            
            exitCondition = !lst.isEmpty();   
            // this is default evaluation, irrespective of r and n. It will get overriden if r is smaller
            
            //initially exitCondition is true (list.isEmpty() = false...   NOT (false) evaluates as true
            // then   exitCondition is false (list.isEmpty()=true.......  NOT (true) evaluates as false  
            
            
            // FOR SOME REASON, NOT SURE I HAE TO INCLUDE THIS TO BREAK OUT OF THE DO WHILE LOOP
            //HOWEVER IT FIXED ISSUE WHICH WAS MAIN OUTCOME.....
            //IT CAN BE SEEN THAT EXITCONDITION ALWAYS EVALATED AS TRUE (SHOWING LIST NOT EMPTY`)
            // This is detrimental if the list is empty since there can be no selection
            // SO I have just broken out of the do while loop with exit condition above.....
            
            System.out.println("current value boolean:  " + exitCondition);
            if (lst.size()==0)
            {
                System.out.println("must get here: ");
                break;
            }
                
                //System.out.println("Size of list: " + lst.size());         //size list
                
                randomNumber = rand.nextInt(lst.size());                  //random number between  0 - (size list-1)
                //System.out.println("random number: " + (randomNumber));
                
                
                temp=numberArray;
                // this is needed so that the correct  currency1=>currency2 symbol  can be 
                // examined in switch statement.
                
                numberArray = lst.get(randomNumber);   //gets number from the list
                
                conversion = temp + "=>" + numberArray;
                
                
                if (temp!="")  // if currencies are not the same, it will start exchange rates
                {
                    System.out.println("***************");
                    
                    System.out.println("Current amount: " + temp + format.format(amount));
                    
                    System.out.println("This is your new currency: " + conversion + "   =>  " +  currencyExchange(conversion,numberArray));
                    
                    String reverseConversion = conversion.charAt(3) + "=>" + conversion.charAt(0);
                    //System.out.println("This is reverse76: " + reverseConversion);
                    //System.out.println("temp: " + temp);
                    System.out.println("This is conversion back to original to check arbitrage: " + reverseConversion + "   =>" + currencyExchange(reverseConversion,temp));
                
                }
                
                //System.out.println("This is currency in list: " + numberArray);    //corresponding value in list
                
                sj.add(numberArray);
                //temp =  temp + Integer.toString(numberArray);    // concatenating the values
                
                lst.remove(randomNumber);     // this is important step.. it removes value at this index from list... enforce combination without replacment
                System.out.println("WHAT IS LIST SIZE RIGHT NOWWWWW: " + lst.size());
            
                //******************************************
                
                if (n>r)   // if end user has selected a smaller sample from n objects    
            {
                System.out.println("$£$£$FDSFSDF HERE ! HERE");
                System.out.println(lst.size());
                
                // if n is taken to be smaller also than the currencies available in stock exchange (lst)
                // then the lst size also needs to be shrunk to accomodate this...
                if (n<totalCurrenciesAvailable)
                {
                    System.out.println("THIS SHOULD NOT PRINT!!!!!");
                    
                    differenceObjectsAndTotalCurrenciesAvailable = totalCurrenciesAvailable-n;
             
             System.out.println(lst.size());
             System.out.println(differenceObjectsAndTotalCurrenciesAvailable);
             System.out.println(n);
             System.out.println(r);
                
            if ((lst.size()-differenceObjectsAndTotalCurrenciesAvailable>(n-r)))   // this would be true at initial execution
            {
                System.out.println("EVER GET HERE!!!!!");
                
                // No need to change the exit point
                //instead best to break out since its processed r elements from n objects
                exitCondition =  true;
                //break;
                 
            }
            else
            {
                System.out.println("Ending first do while loop");
                //
                //exitCondition =  false;
                break;
            }
            }
            
            
            if (lst.size()>n-r)   // this would be true at initial execution
            {
                
                // No need to change the exit point
                //instead best to break out since its processed r elements from n objects
                exitCondition =  true;
                //break;
                 
            }
            else
            {
                System.out.println("Ending first do while loop");
                //
                //exitCondition =  false;
                break;
            }
            
            
            }
            //*******************************************************
                
                
                //System.out.println("value of i: " + i + "\n");
                
            } while (exitCondition);            // it will keep processing while this is true....   while list is not empty
            
            currentSetSize= s.size();
            System.out.println("************This is current set size: " + currentSetSize);
            
            
            s.add(sj.toString());    // adding the value to the set.
            
            
            //it performs this check since if the set has not grown, there is no point
            // in doing arbitration check since it is a repeat sequence already in the set
            System.out.println("************This is new set size: " + s.size());
            
            
            //so a condition is created as below to ensure it does not perform method call again:
            
            
            System.out.println("set size: " + s.size() +"\n");   //once this has incremented, the set has grown...
            System.out.println("This is saved in the set: " + sj.toString() +"\n");
            
            
            // Arbitrage check here
            
            fullConversions = sj.toString();
            
            System.out.println("******Arbitrage full check - full combination of currencies:   " + fullConversions);
            
            if (s.size()==currentSetSize)
            {
                System.out.println("NOT REQUIRED");
            }
            else
            {
                arbitrageCheckerTwoCurrencies();
                arbitrageCheckerFullCombination();
            }
        
        count++;   // this is indication of a cycle.. It is aiming to be close to combinations...
        
        } while (s.size()<combinations);    // this is 1 less due to 0 indexing of the set. 
        
        System.out.println("\nNumber cycles: " + count);
        
        System.out.println("Original list: " + copy.toString());  //original list outputted to the screen
        //System.out.println("highest is: " + checkMaximum());     // function call to check for maximum
        
    }
          
    public void arbitrageCheckerTwoCurrencies()
    {
            //System.out.println("Number times conversion to check is: " + (copy.size()+1));
            
            k=4;
            startPos=0;
            endPos = startPos+4;
            
            exchangeArbitrage = fullConversions.substring(0,endPos);
            
            amount=50;   // this will be the starting point. It makes no difference of the amount.
            // unless there is consideration for transaction fees.
            
            initialAmount =  exchangeArbitrage.charAt(0) + format.format(amount);
            
            System.out.println("Current amount (AMOUNT SHOULD RETURN HERE IF NO ARBITRAGE): " + initialAmount); 
             
            for (int i=0; i<copy.size()-1; i++)   // if three currencies, it will have to process conversion twice in forward direction
            {  
                
            newCurrency = Character.toString(exchangeArbitrage.charAt(3));
               
            //System.out.println("segment: " + exchangeArbitrage);    
                
                System.out.println("This is your new currency: " + exchangeArbitrage + "   =>  " +  currencyExchange(exchangeArbitrage, newCurrency));
            
            
                
            startPos=endPos-1;
            endPos=startPos+4;
            
            if (endPos>fullConversions.toString().length())      // it is checking against fullconversions 
            {
                break;
                
            }
                  
            exchangeArbitrage = fullConversions.substring(startPos, endPos);
            
            }
        
    }
    
    
    // THIS IS NOW FULLY FUNCTIONAL!!!!
    
    public void arbitrageCheckerFullCombination()
    {
        // This now has to go back to original state
            // issue is creating the substring in reverse and directions of => will be flipped
            //easiest starting point is just reversing the string with StringBuilder
            
            
            sb = new StringBuilder(fullConversions);   // this is correct
            fullConversionsReverse = sb.reverse().toString();   // this is correct
            System.out.println("Reverse conversion****: " + fullConversionsReverse);   // this is correct
            
            k=4;
            startPos=0;
            endPos = startPos+3;
            
            //mistake is here!!!!!!!!!!  / it is using reversestring so => is  >=
            exchangeArbitrage = fullConversionsReverse.charAt(startPos) + "=>" + fullConversionsReverse.charAt(endPos)    ;  // this will take 4 chars such as  £=>$  
            // this is correct... its the first part
            
            for (int i=0; i<copy.size()-1; i++)   // if three currencies, it will have to process conversion twice in forward direction
            {  
                
            newCurrency = Character.toString(exchangeArbitrage.charAt(3));  // this is correct this is symbol only
            exchangeArbitrageFlipped = exchangeArbitrage.charAt(0) + "=>" +  newCurrency;  
            // this is correct   this will give first char => next currency in line
            
            //System.out.println("segment'678 : " + fullConversionsReverse.charAt(0)+"=>"+fullConversionsReverse.charAt(3));    
            // System.out.println("segment'678 : " + exchangeArbitrageFlipped);
             
            outcome =  currencyExchange(exchangeArbitrageFlipped, newCurrency);    // this is correct conversion....
            //inline with above
            
            //this is correct
            System.out.println("This is your new currency in reverse: " + exchangeArbitrage + "   =>  " + outcome );
            
        
            startPos=endPos;
            endPos = startPos+3;
            System.out.println("start pos: " + startPos);
            System.out.println("end pos: " + endPos);
            
            if (endPos>fullConversionsReverse.length())  // this is to ensure no outbound exception.....
            {
                break;
            }
            
            System.out.println(fullConversionsReverse.charAt(startPos));
            exchangeArbitrage = fullConversionsReverse.charAt(startPos) + "=>" + fullConversionsReverse.charAt(endPos);

            //startPos=startPos+3;   // this is correct
            //endPosition=startPos+k;        // this is correct 1 extra char due to exclusion...
            //exchangeArbitrage = fullConversions.substring(startPos, endPos);   // this is correct
            //it can only fail if it comes out of loop for startpos to reset... but this does not happen...
            
            //System.out.println("Crash point next conversion: " + exchangeArbitrage);
            
            
            //System.out.println("Revised string!!!!!: " + exchangeArbitrage);
            }
            
            ArbitrageChecker = Double.parseDouble(outcome.substring(1)) - Double.parseDouble(initialAmount.substring(1));
            
            if (ArbitrageChecker >0)
            {
                System.out.println("- - - Arbitrage: - - - " + outcome.charAt(0) + format.format(ArbitrageChecker) + "  (" + initialAmount + " - " + outcome+")");
            }
            else
            {
                System.out.println("- - - NO Arbitrage: - - - ");
            }
    }
    
    }

public class Combination
{
    public static void main(String[] args) {
        System.out.println("Welcome to Online IDE!! Happy Coding :)");
        
        int originalNumber=2;
        int n=originalNumber;
        int r =1;
        Map <Integer, Long> m = new HashMap<>();
        System.out.println("***COMBINATIONS***  (WITHOUT REPLACEMENT)");
        System.out.println("C(n,r) = n! / (r!(n−r)!)");
        System.out.println("C(" + n+","+r+") = " + n+"!" + " / " + "("+r+"!"+"("+n+"-"+r+")!)");
        
        exchangeCombinations ec = new exchangeCombinations(Combinations (n,r,originalNumber, m), n,r);
        
    }
    
    public static long Combinations (int n,  int r, int originalNumber, Map factorialResults)
    {
        
        // n are objects
        // r is sample
       
       /*
       ***CALCULATION***
        P(n,r) =   n! /  (r!(n−r)!)
        
        */
        
        long result=0;
        int denominator1;
        int denominator2;
        
        if (n>=1)
        {
            // EXAMPLE
            
            // P (5,6)   =   6* 5* 4 * 3 * 2 * 1   /   6! (6-5)!     =    720 / (5! * 1!) =  120 / 5*4*3*2*1  * 1  = 720 / 120 = 6
        
        result = (n* (Combinations (n-1, r,originalNumber, factorialResults)));   // this completes factorial for numerator
        
        factorialResults.put(n,result);   //result stored in the Map
        //System.out.println("getting result back out: " + factorialResults.get(n));
        
        
        if (n==originalNumber)   // this will occur once
        {
            
            denominator1 = originalNumber-r;        // originalNumber required since n has reduced as part of the recursive calls
           
            denominator2 = r;                       // r sample size has not changed
           
            
        // this is using the Java Memoization technique to ensure the factorial outcome is not calculated again, to save program cycles.
        // since the returns are done in reverse order.... n = 1 is processed first and n=6 last... Hence in practice
        // there will be entry in Map for all factorials, ready for the denominator..
        
        
            if (factorialResults.containsKey(denominator1) && factorialResults.containsKey(denominator2))
            
            {
                //System.out.println("here");
                //System.out.println("This is exact value of factorial  " + (denominator1) + " : " +  factorialResults.get(denominator1));
                //System.out.println("This is exact value of factorial  " + (denominator2) + " : " +  factorialResults.get(denominator2));
               
                return result / ((long) factorialResults.get(denominator1) * (long)factorialResults.get(denominator2));
            }
           
        }
           
            return result;
            
        }
          return 1;    // it should not reach here  
        }
        
    }
