Thursday, August 4, 2016

MolecularWeightComputer

 import java.util.LinkedHashMap;  
 import java.util.Map;  
 import java.util.Stack;  
 /**  
  * Created by mridul on 8/1/16.  
  */  
 public class MolecularWeightComputer {  
   private interface Name<T>{  
     T getName();  
     void setName(T t);  
   }  
   private enum Atom{  
     Oxygen("O",15.9994F),  
     Carbon("C",12.011F),  
     Nitrogen("N",14.00674F),  
     Sulfur("S",32.066F),  
     Hydrogen("H",1.00794F);  
     private String symbol;  
     private float atomicWeight;  
     Atom(String symbol, float atomicWeight){  
       this.symbol=symbol;  
       this.atomicWeight=atomicWeight;  
     }  
     String getSymbol(){  
       return symbol;  
     }  
     float getAtomicWeight(){  
       return atomicWeight;  
     }  
   }  
   private static class Molecule implements Name<String>{  
     private String name;  
     private final String formula;  
     private float molecularWeight;  
     private Map<String,Integer> composition=new LinkedHashMap<>();  
     private Molecule(String formula){  
       this.formula = formula;  
     }  
     static Molecule createMoleculeFromFormula(String formula){  
       return new Molecule(formula.toUpperCase());  
     }  
     private float getMolecularWeight(){  
       return molecularWeight;  
     }  
     public String getName(){  
       return name;  
     }  
     public void setName(String name){  
       this.name=name;  
     }  
     private void computeAtomicCount(){  
       Stack<Integer> digits =new Stack<>();  
       String key="";  
       for(int index = 0; index< formula.length(); index++){  
         Character token= formula.charAt(index);  
         if(Character.isAlphabetic(token)){  
           key=Character.toString(token);  
           digits.clear();  
         }else if(Character.isDigit(token)){  
           int value=Integer.parseInt(Character.toString(token));  
           if(!digits.isEmpty()){  
             value=(digits.pop()*10)+value;  
           }  
           digits.push(value);  
         }  
         if(composition.containsKey(key)){  
           composition.put(key,digits.peek());  
         }else {  
           composition.put(key, 0);  
         }  
       }  
       //replace zero entries with one  
       for(Map.Entry<String,Integer> entry: composition.entrySet()){  
         if(entry.getValue()==0){  
           entry.setValue(1);  
         }  
       }  
       //print map values  
       for(Map.Entry<String,Integer> entry: composition.entrySet()){  
         System.out.printf("%s:%d ",entry.getKey(),entry.getValue());  
       }  
       System.out.println("\n");  
     }  
     private void computeMolecularWeight(){  
       computeAtomicCount();  
       float molecularWeight=0.0F;  
       for(Map.Entry<String,Integer> entry: composition.entrySet()){  
         for(Atom atom:Atom.values()){  
           if(entry.getKey().equalsIgnoreCase(atom.getSymbol())){  
             molecularWeight+=entry.getValue()*atom.getAtomicWeight();  
           }  
         }  
       }  
       this.molecularWeight=molecularWeight;  
       System.out.printf("Molecular weight of is %.2f%n", molecularWeight);  
     }  
   }  
   public static void main(String... args) {  
     System.out.printf("Leucine Data: %n");  
     Molecule leucine = Molecule.createMoleculeFromFormula("C6H13NO2");  
     leucine.computeMolecularWeight();  
     System.out.printf("Lysine Data: %n");  
     Molecule lysine = Molecule.createMoleculeFromFormula("C6H14N2O2");  
     lysine.computeMolecularWeight();  
     System.out.printf("Molecular difference is %.2f%n", leucine.getMolecularWeight() - lysine.getMolecularWeight());  
   }  
 }  

Wednesday, July 13, 2016

Code to return rounded of value owing to issue with Set Scale in BigDecimal

private BigDecimal getRoundedFare(BigDecimal value){
BigDecimal fractionalValue=value.remainder(BigDecimal.ONE);
        BigDecimal integralValue=value.subtract(fractionalValue);
        BigDecimal roundedFare = (fractionalValue.doubleValue() >= 0.50) ?  integralValue.add(BigDecimal.ONE): integralValue;
        return  roundedFare;
    }

Wednesday, March 23, 2016

Webdriver Parser to retrieve information from an HTML report - direct access was not available to use listeners

import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.support.ui.*;  
 import java.util.*;  
 import java.util.concurrent.TimeUnit;  
 /**  
  * Created by Mridul on 1/14/2016.  
  */  
 public class ReportParser {  
   private WebDriver driver;  
   private WebDriverWait wait;  
   ReportParser(){  
     System.setProperty("webdriver.chrome.driver", "C:\\chromedriver\\chromedriver.exe");  
     this.driver = new ChromeDriver();  
     driver.manage().window().maximize();  
     wait=new WebDriverWait(driver,10);  
   }  
   public WebDriver getDriver(){  
     return driver;  
   }  
   public WebDriverWait getWaitDriver(){  
     return wait;  
   }  
   private void printMap(Map<String,List<String>> testMap){  
     System.out.println("Printing values in map!");  
     for(Map.Entry entry: testMap.entrySet()){  
       System.out.println("The Defect is :" + entry.getKey());  
       System.out.println("The associated tests are :");  
       for(String value : (List<String>)entry.getValue()){  
         System.out.println(value);  
       }  
       System.out.println("\n");  
     }  
     System.out.println("The no of tests are : " + testMap.size());  
   }  
   private Map<String,List<String>> storeTestsToMap(List<WebElement> elements, Map<String, List<String>> testMap){  
     for(WebElement element: elements){  
       //WebElement anchor=element.findElement(By.tagName("a"));  
       WebElement anchor=wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName("a")));  
       //retrieve key  
       String fullKey=anchor.getAttribute("title");  
       String key=(fullKey.contains("Exception"))? fullKey.substring(0,fullKey.indexOf("Exception")) : fullKey;  
       //System.out.println(key);  
       //retrieve value  
       String fullValue=anchor.getText();  
       String value=fullValue.substring(fullValue.indexOf("Shopping"), fullValue.length());  
       //System.out.println(value+"\n");  
       //store key value into map based on unique key  
       List<String> values;  
       if(testMap.containsKey(key)){  
         values=testMap.get(key);  
       }else {  
         values=new ArrayList<String>();  
       }  
       values.add(value);  
       testMap.put(key, values);  
     }  
     return testMap;  
   }  
   public static void main(String... args){  
     try {  
       int displaySize, totalCount, currentCount;  
       Map<String, List<String>> failureTestsMap=new WeakHashMap<String, List<String>>();  
       Map<String, List<String>> errorTestsMap=new WeakHashMap<String, List<String>>();  
       ReportParser reportParser;  
       WebDriver driver;  
       WebDriverWait wait;  
       reportParser = new ReportParser();  
       driver = reportParser.getDriver();  
       wait=reportParser.getWaitDriver();  
       driver.get("http://localhost:63342/ais-parent/ais-dotcom/target/site/thucydides/index.html");  
       driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);  
       do {  
         //WebElement testTable = driver.findElement(By.id("test-results-table"));  
         //List<WebElement> elems_failureTest = testTable.findElements(By.className("FAILURE-text"));  
         WebElement testTable = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test-results-table")));  
         //List<WebElement> elems_failureTest = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("FAILURE-text")));  
         List<WebElement> elems_failureTest = testTable.findElements(By.className("FAILURE-text"));  
         //System.out.println("Failure tests size : " + elems_failureTest.size());  
         failureTestsMap = reportParser.storeTestsToMap(elems_failureTest,failureTestsMap);  
         //reportParser.printMap(failureTestsMap);  
         List<WebElement> elems_errorTest = testTable.findElements(By.className("ERROR-text"));  
         //System.out.println("Error tests size : " + elems_errorTest.size());  
         errorTestsMap = reportParser.storeTestsToMap(elems_errorTest, errorTestsMap);  
         //reportParser.printMap(errorTestsMap);  
         //navigate to the drop down element  
         //Select sel_ResultSize = new Select(driver.findElement(By.name("test-results-table_length")));  
         Select sel_ResultSize = new Select(wait.until(ExpectedConditions.presenceOfElementLocated(By.name("test-results-table_length"))));  
         displaySize = Integer.parseInt(sel_ResultSize.getFirstSelectedOption().getText());  
         //System.out.println("Size : " + displaySize);  
         //retrieve the total tests  
         //String totalTests = driver.findElement(By.id("test-results-table_info")).getText();  
         String totalTests = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test-results-table_info"))).getText();  
         String count = totalTests.substring(totalTests.indexOf("to"), totalTests.indexOf("of"));  
         currentCount = Integer.parseInt(count.substring(count.length() - 3, count.length() - 1));  
         //System.out.println("currentCount : " + currentCount);  
         String finalCount = totalTests.substring(totalTests.indexOf("of"), totalTests.indexOf("entries"));  
         totalCount = Integer.parseInt(finalCount.substring(finalCount.length() - 3, finalCount.length() - 1));  
         //System.out.println("totalCount : " + totalCount);  
         //click on the next button  
         //WebElement elem_NextButton=driver.findElement(By.id("test-results-table_next"));  
         WebElement elem_NextButton=wait.until(ExpectedConditions.presenceOfElementLocated(By.id("test-results-table_next")));  
         elem_NextButton.click();  
       } while (currentCount < totalCount);  
       reportParser.printMap(failureTestsMap);  
       System.out.println("The no of failure tests are : " + failureTestsMap.size());  
       reportParser.printMap(errorTestsMap);  
       System.out.println("The no of error tests are : "+errorTestsMap.size());  
     }finally {  
       //driver.quit();  
     }  
   }  
 }  

Friday, March 4, 2016

Xml value - absolute xpath mapper. Maps multiple paths if present for each unique value as key

 package com.mridul.mapper;  
 import org.w3c.dom.Document;  
 import org.w3c.dom.Element;  
 import org.w3c.dom.NodeList;  
 import org.w3c.dom.Node;  
 import javax.xml.parsers.DocumentBuilder;  
 import javax.xml.parsers.DocumentBuilderFactory;  
 import java.io.ByteArrayInputStream;  
 import java.io.File;  
 import java.io.IOException;  
 import java.util.*;  
 /**  
  * Created by Mridul on 2/25/2016.  
  */  
 public class Mapper {  
   private List<StringBuilder> paths = new ArrayList<>();  
   private Node rootNode;  
   private static String FORWARD_SLASH = "/";  
   private static int ROOT_COUNTER = 0;  
   private boolean textFlag = false;  
   private static Map<String, List<String>> valuePathMap=new WeakHashMap<>();  
   public boolean isTextFlag() {  
     return textFlag;  
   }  
   public void setTextFlag(boolean textFlag) {  
     this.textFlag = textFlag;  
   }  
   public Node getRootNode() {  
     return rootNode;  
   }  
   public void setRootNode(Node rootNode) {  
     this.rootNode = rootNode;  
   }  
   public static void main(String... args) {  
     try {  
       //The order of these sequential steps matter  
       Mapper mapper = new Mapper();  
       StringBuilder xmlAsString = mapper.getFileAsStringBuilder("xml/catalog.xml");  
       //StringBuilder xmlAsString = mapper.getFileAsStringBuilder("xml/auction.xml");  
       //StringBuilder xmlAsString = mapper.getFileAsStringBuilder("xml/uwm.xml");  
       mapper.retrieveAndSetRootNode(xmlAsString);  
       mapper.recursivelyPrintAllNodes(FORWARD_SLASH);  
       mapper.printValuesInMap();  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
   }  
   private StringBuilder getFileAsStringBuilder(String fileName) {  
     StringBuilder result = new StringBuilder();  
     ClassLoader classLoader = getClass().getClassLoader();  
     File file = new File(classLoader.getResource(fileName).getFile());  
     try (Scanner scanner = new Scanner(file)) {  
       while (scanner.hasNextLine()) {  
         String line = scanner.nextLine();  
         result.append(line).append("\n");  
       }  
       scanner.close();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
     //System.out.println(result.toString());  
     return result;  
   }  
   private void retrieveAndSetRootNode(StringBuilder xml) throws Exception {  
     DocumentBuilderFactory factory =  
         DocumentBuilderFactory.newInstance();  
     DocumentBuilder builder = factory.newDocumentBuilder();  
     ByteArrayInputStream input = new ByteArrayInputStream(xml.toString().getBytes("UTF-8"));  
     Document document = builder.parse(input);  
     Element rootNode = document.getDocumentElement();  
     setRootNode(rootNode);  
   }  
   private void recursivelyPrintAllNodes(String path) {  
     Node rootNode = getRootNode();  
     String rootNodeName = rootNode.getNodeName();  
     if (ROOT_COUNTER == 0) {  
       path = path + rootNode.getNodeName();  
     }  
     ++ROOT_COUNTER;  
     String parentPath = path;  
     NodeList childNodes;  
     if (rootNode.hasChildNodes()) {  
       childNodes = rootNode.getChildNodes();  
       for (int index = 0; index < childNodes.getLength(); index++) {  
         Node currentNode = childNodes.item(index);  
         short nodeType = currentNode.getNodeType();  
         if (nodeType == Node.TEXT_NODE) {  
           String value = currentNode.getNodeValue().trim();  
           if (value.equals("")) {  
             continue;  
           } else {  
 /*            System.out.println("The current path is : " + path);  
             System.out.println("The text node value is : " + value);*/  
             storeValuePathIntoMap(value, path);  
             this.setTextFlag(true);  
           }  
         }  
         if (isTextFlag()) {  
           setTextFlag(false);  
           break;  
         }  
         if (nodeType == Node.ELEMENT_NODE) {  
           String currentNodeName = currentNode.getNodeName();  
           if (!(rootNodeName.equals(currentNodeName))) { //add path only in case of mismatch  
             path = parentPath + FORWARD_SLASH + currentNodeName;  
           }  
           setRootNode(currentNode); //setting root node to current node  
           recursivelyPrintAllNodes(path);//recursive call to iterate  
         }  
       }  
     }  
   }  
   private void storeValuePathIntoMap(String key, String value){  
     if(valuePathMap.containsKey(key)){  
       List<String> values=valuePathMap.get(key);  
       values.add(value);  
     }else{  
       valuePathMap.put(key,new ArrayList<>(Arrays.asList(value)));  
     }  
   }  
   private void printValuesInMap(){  
     for(Map.Entry<String, List<String>> entry: valuePathMap.entrySet()){  
       System.out.println("Key: " + entry.getKey());  
       System.out.println("Value: " + entry.getValue()+"\n");  
     }  
   }  
 }  

Monday, November 2, 2015

Code to generate test cases and add a uniform distribution of parameters

import java.util.*;  
 /**  
  * Created by Mridul on 9/25/2015.  
  */  
 public class DotcomSuiteGenerator {  
   /**  
    * method which recursively generates the probable testcases  
    * @param prefix  
    * @param lists  
    */  
   private static int counter;  
   private List<String> randomList=new ArrayList<>();  
   private List<String> copyOfRandomList=new ArrayList<>();  
 /*  public void generate(String prefix, String spacer, List<String>... lists) {  
     int len=lists.length;  
     if(len > 0) {  
       List<String> list = lists[0];  
       lists = Arrays.copyOfRange(lists, 1, len);  
       for (String value : list) {  
         String name = prefix + value + spacer;  
         generate(name,spacer,lists); //recursive call  
         if(lists.length==0) {  
           System.out.println(name.substring(0,name.length()-1));  
           ++counter;  
         }  
       }  
     }  
   }*/  
   public void generate(String prefix, String spacer, List<String>... lists) {  
     int len=lists.length;  
     if(len > 0) {  
       List<String> list = lists[0];  
       lists = Arrays.copyOfRange(lists, 1, len);  
       for (String value : list) {  
         String name = prefix + value + spacer;  
         generate(name,spacer,lists); //recursive call  
         if(lists.length==0) {  
           name = name + getRandomListValue();  
           System.out.println(name);  
           ++counter;  
         }  
       }  
     }  
   }  
   private String getRandomListValue(){  
     String result="";  
     int size=copyOfRandomList.size();  
     if(size==0)  
       copyOfRandomList=new ArrayList<>(randomList);  
     if( size >= 0) {  
       Collections.shuffle(copyOfRandomList);  
       result = copyOfRandomList.remove(0);  
     }  
     return result;  
   }  
   public void appendRandomVariables(List<String>... lists) {  
     //creating combo list containing all the data for booking  
     List<String> comboBookingParams=new ArrayList<>();  
     for(int index=0; index < lists.length; index++) {  
       comboBookingParams.addAll(lists[index]);  
     }  
     randomList=comboBookingParams;  
     copyOfRandomList=new ArrayList<>(randomList);  
     for(String value: copyOfRandomList){  
       System.out.println("value : "+value);  
     }  
     System.out.println(" copyOfRandomList.size() : "+copyOfRandomList.size());  
   }  
   public static void main(String... args){  
     //constants  
      //String prefix="Shopping_Calendar_Matrix_Pricing_"; //for shopping  
      String prefix="Booking_";  
      String spacer="_";  
     //parameters  
      List<String> tripTypeOW=Arrays.asList("OW");  
      List<String> tripType=Arrays.asList("RT","MC");  
      List<String> route=Arrays.asList("DOM","INTL");  
      List<String> paxTypeADT= Arrays.asList("ADT");  
      List<String> paxTypeSRC= Arrays.asList("SRC");  
      List<String> payTypeD=Arrays.asList("Dollars");  
      List<String> payTypeP=Arrays.asList("Points");  
      List<String> flightType=Arrays.asList("Dir","Conn");  
      List<String> fareType=Arrays.asList("BUS","ANY","WGA");  
      List<String> fareTypeRED=Arrays.asList("BUSRED","ANYRED","WGARED");  
      List<String> scenarioType=Arrays.asList("SameMonth","DifferentMonth");  
      List<String> discountType=Arrays.asList("AmtDiscount","PercDiscount");  
     //booking specific parameters  
     List<String> creditCards=Arrays.asList("Visa","Mastercard","Diner","Discover","UATP","Amex");  
     List<String> otherPayTypes=Arrays.asList("GIF","LUV");  
     List<String> comboPayType=Arrays.asList("Visa_GIF","Visa_LUV","Mastercard_GIF","Mastercard_LUV",  
                         "Diner_GIF","Diner_LUV","Discover_GIF","Discover_LUV",  
                         "UATP_GIF","UATP_LUV","Amex_GIF","Amex_LUV");  
     List<String> cash=Arrays.asList("Cash");  
     DotcomSuiteGenerator instance=new DotcomSuiteGenerator();  
     System.out.println("The combination of tests are: ");  
     /*  
     ALL VALID COMBINATIONS OF DATA ARE GIVEN BELOW FOR SHOPPING  
      */  
     //generates all Adult Dollars for OW  
 /*    instance.generate(prefix, spacer, tripTypeOW, route, paxTypeADT, payTypeD, flightType, fareType, scenarioType);  
     //generates all Adult Points for OW  
     instance.generate(prefix, spacer, tripTypeOW, route, paxTypeADT, payTypeP, flightType, fareTypeRED, scenarioType);  
     //generates all Adult Dollars for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeADT, payTypeD, flightType, flightType, fareType, scenarioType);  
     //generates all Adult Points for for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeADT, payTypeP, flightType, flightType, fareTypeRED, scenarioType);  
     //generates all Senior Dollars for OW  
     instance.generate(prefix, spacer, tripTypeOW, route, paxTypeSRC, payTypeD, flightType, fareType, scenarioType);  
     //generates all Senior Points for OW  
     instance.generate(prefix, spacer, tripTypeOW, route, paxTypeSRC, payTypeP, flightType, fareTypeRED, scenarioType);  
     //generates all Senior Dollars for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeSRC, payTypeD, flightType, flightType, fareType, scenarioType);  
     //generates all Senior Points for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeSRC, payTypeP, flightType, flightType, fareTypeRED, scenarioType);*/  
     //ALL PERCENTAGE AND AMOUNT DISCOUNT SCENARIOS- NOT IN EXCEL SHEET- FOR FUTURE USE  
 /*    //generates all Adult Dollars with Amount and Percentage Discount  
     instance.generate(prefix, spacer, tripType, route, paxTypeADT, payTypeD, flightType, fareType, scenarioType, discountType);  
     //generates all Adult Points with Percentage Discount  
     instance.generate(prefix, spacer, tripType, route, paxTypeADT, payTypeP, flightType, fareTypeRED, scenarioType, Arrays.asList("PercDiscount"));  
     //generates all Senior Dollars with Amount and Percentage Discount  
     instance.generate(prefix, spacer, tripType, route, paxTypeSRC, payTypeD, flightType, fareType, scenarioType, discountType);  
     //generates all Senior Points with Percentage Discount  
     instance.generate(prefix, spacer, tripType, route, paxTypeSRC, payTypeP, flightType, fareTypeRED, scenarioType, Arrays.asList("PercDiscount"));*/  
     //EXPERIMENTAL- FOR FUTURE TESTCASES WITH DIFFERENT FARE TYPES ON FLIGHT SEGMENTS OF RT AND MC TESTCASES  
 /*    //generates all RT and MC trips for ADT with Dollars with separate segments  
     instance.generate(prefix, spacer, Arrays.asList("RT","MC"), route, paxTypeADT, payTypeD, flightType, fareType, fareType, scenarioType);*/  
     //generate other combo types-one time run  
     //instance.generate("", spacer, creditCards, otherPayTypes);  
     /*  
       ALL VALID COMBINATIONS OF DATA ARE GIVEN BELOW FOR BOOKING  
      */  
     //SET ALL APPENDABLE LISTS HERE  
     instance.appendRandomVariables(creditCards, otherPayTypes, comboPayType, cash);  
     //generates all Adult Dollars for OW  
     instance.generate(prefix, spacer, tripTypeOW, route, paxTypeADT, payTypeD, flightType, fareType, scenarioType);  
     //generates all Adult Points for OW  
     instance.generate(prefix, spacer, tripTypeOW, route, paxTypeADT, payTypeP, flightType, fareTypeRED, scenarioType);  
     //generates all Adult Dollars for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeADT, payTypeD, flightType, flightType, fareType, scenarioType);  
     //generates all Adult Points for for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeADT, payTypeP, flightType, flightType, fareTypeRED, scenarioType);  
     //generates all Senior Dollars for OW  
     instance.generate(prefix, spacer, tripTypeOW, route, paxTypeSRC, payTypeD, flightType, fareType, scenarioType);  
     //generates all Senior Points for OW  
     instance.generate(prefix, spacer, tripTypeOW, route, paxTypeSRC, payTypeP, flightType, fareTypeRED, scenarioType);  
     //generates all Senior Dollars for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeSRC, payTypeD, flightType, flightType, fareType, scenarioType);  
     //generates all Senior Points for RT and MC  
     instance.generate(prefix, spacer, tripType, route, paxTypeSRC, payTypeP, flightType, flightType, fareTypeRED, scenarioType);  
     System.out.println("The total number of tests is : "+counter);  

Sunday, October 18, 2015

Cows and Bulls Game

 import java.util.*;  
 /**  
  * Created by Mridul on 10/17/15.  
  */  
 public class CowsAndBulls {  
   private final int[] secretNumber;  
   private int[] guessNumber;  
   private List<String> guesses;  
   private int size;  
   private static final int DEFAULT_SIZE=4;  
   private int getSize(){  
     if(size==0) {  
       return DEFAULT_SIZE;  
     }else{  
       return size;  
     }  
   }  
   private void setSize(int size){  
     this.size = size;  
   }  
   public int[] getSecretNumber(){  
     return secretNumber;  
   }  
   CowsAndBulls(){  
     secretNumber=populateSecretNumber();  
     guessNumber=new int [getSize()];  
     Arrays.fill(guessNumber,0);  
     guesses=new ArrayList<>();  
   }  
   private int[] populateSecretNumber(){  
     Random rand=new Random();  
     int size=getSize();  
     int[] number= new int[size];  
     for(int i=0;i<size;i++){  
       number[i]= rand.nextInt(9);  
     }  
     return number;  
   }  
   public void verifyGuess(String guess){  
     try {  
       int iguess = Integer.parseInt(guess);  
       int len = guess.length();  
       int remainder = 0;  
       while (len > 0) {  
         guessNumber[--len] = iguess % 10;  
         iguess = iguess / 10;  
       }  
       computeCowsAndBulls();  
     }catch (NumberFormatException nfe){  
       System.out.println("Please enter a valid number");  
     }  
   }  
   private void computeCowsAndBulls(){  
     int cows=0;  
     int bulls=0;  
     for(int i=0; i<guessNumber.length;i++){  
       for(int j=0;j<secretNumber.length;j++){  
         if(guessNumber[i]==secretNumber[j]){  
           //if indexes are same then bulls  
           if(i==j) {  
             ++bulls;  
           }else {  
             ++cows;  
           }  
         }  
       }  
     }  
     System.out.printf("%d bulls and %d cows\n", bulls, cows);  
   }  
   public static void main(String... args){  
     CowsAndBulls instance =new CowsAndBulls();  
     do {  
       System.out.println("Starting Cows and Bulls game!");  
       System.out.println("Please type EXIT to quit the game anytime!");  
       System.out.println("Please type REVEAL to show the 4 digit number anytime!");  
       System.out.println("Please start guessing the 4 digit number : ");  
       Scanner scanner = new Scanner(System.in);  
       String currentGuess = scanner.next();  
       if(currentGuess.equalsIgnoreCase("EXIT")){  
         System.out.println("Thanks for playing the game!");  
         System.exit(0);  
       }else if(currentGuess.equalsIgnoreCase("REVEAL")){  
         System.out.println("The Secret number is : "  
             + Arrays.toString(instance.getSecretNumber()));  
         System.out.println("Thanks for playing the game!");  
         System.exit(0);  
       }  
       else {  
         instance.verifyGuess(currentGuess);  
       }  
     }while(true);  
   }  
 }  

Friday, September 25, 2015

Code to generate a combination of strings recursively-Used to generate test cases from parameters

 import java.util.*;  
 /**  
  * Created by x217018 on 9/25/2015.  
  */  
 public class DotcomSuiteGenerator {  
   /**  
    * method which recursively generates the probable testcases  
    * @param prefix  
    * @param lists  
    */  
   public void generate(String prefix, String spacer, List<String>... lists) {  
     int len=lists.length;  
     if(len > 0) {  
       List<String> list = lists[0];  
       lists = Arrays.copyOfRange(lists, 1, lists.length);  
       for (String value : list) {  
         String name = prefix + value + spacer;  
         generate(name,spacer,lists); //recursive call  
         if(lists.length==0) {  
           System.out.println(name.substring(0,name.length()-1));  
         }  
       }  
     }  
   }  
   public static void main(String... args){  
     //constants  
      String prefix="Shopping_Calendar_Matrix_Pricing_";  
      String spacer="_";  
     //parameters  
      List<String> tripType=Arrays.asList("OW","RT","MC");  
      List<String> route=Arrays.asList("DOM","INTL");  
      List<String> paxTypeADT= Arrays.asList("ADT");  
      List<String> paxTypeSRC= Arrays.asList("SRC");  
      List<String> payType=Arrays.asList("Dollars","Points");  
      List<String> flightType=Arrays.asList("Dir","Conn");  
      List<String> fareTypeADT=Arrays.asList("BUS","ANY","WGA");  
      List<String> fareTypeSRC=Arrays.asList("BUSRED","ANYRED","WGARED");  
      List<String> scenarioType=Arrays.asList("SameMonth","DifferentMonth");  
      List<String> discountType=Arrays.asList("AmtDiscount","PercDiscount");  
     DotcomSuiteGenerator instance=new DotcomSuiteGenerator();  
     System.out.println("The combination of tests are: ");  
     //generates all Adult testcases  
     instance.generate(prefix, spacer, tripType, route, paxTypeADT, payType, flightType, fareTypeADT, scenarioType);  
     //generates all Senior testcases  
     instance.generate(prefix, spacer, tripType, route,paxTypeSRC,payType,flightType,fareTypeSRC,scenarioType);  
     //generates all Adult testcases with Dollars with both Amount and Percentage Discount  
     //instance.generate(prefix, spacer, tripType, route,paxTypeADT,Arrays.asList("Dollars"),flightType,fareTypeADT,scenarioType, discountType);  
     //generates all Seniors testcases with Points with both Percentage Discount  
     //instance.generate(prefix, spacer, tripType, route,paxTypeADT,Arrays.asList("Points"),flightType,fareTypeADT,scenarioType,Arrays.asList("PercDiscount"));  
   }  
 }  
 //Sample data  
 /*  
 The combination of tests are:  
 Shopping_Calendar_Matrix_Pricing_OW_DOM_ADT_Dollars_Dir_BUS_SameMonth  
 Shopping_Calendar_Matrix_Pricing_OW_DOM_ADT_Dollars_Dir_BUS_DifferentMonth  
 Shopping_Calendar_Matrix_Pricing_OW_DOM_ADT_Dollars_Dir_ANY_SameMonth  
 Shopping_Calendar_Matrix_Pricing_OW_DOM_ADT_Dollars_Dir_ANY_DifferentMonth  
 Shopping_Calendar_Matrix_Pricing_OW_DOM_ADT_Dollars_Dir_WGA_SameMonth  
 Shopping_Calendar_Matrix_Pricing_OW_DOM_ADT_Dollars_Dir_WGA_DifferentMonth  
  */