Selenium WebDriver: Finding the row of a table containing two input values - java

I'm working on function that takes two values in a table then verifies the row that contains the two values to verify if a third value exist in that row.
The code below finds the row where the two values are. However, it will not break out of the for loop if rowNo and rowNo2 are equal. I've tried using .equals() but that gives me an error. Any tips?
try {
// Get the row number of passed row Data
WebElement table = oWebDriver.getWebElement(tableObject);
List<WebElement> rows = table.findElements(By.tagName("tr"));
List<WebElement> cols = table.findElements(By.tagName("td"));
int colSize = (cols.size()) / (rows.size());
int rowNo = 0;
int rowNo2 = 0;
int colNo = 0;
for (int i = 0; i < cols.size(); i++) {
WebElement cellData = cols.get(i);
if (cellData.getText().contains(rowData)||cellData.getText().contains(rowData.toUpperCase())) {
int l = i / colSize;
rowNo = l + 1;
for (int k = 0; k < cols.size(); k++) {
WebElement cellData2 = cols.get(k);
if (cellData2.getText().contains(rowData2)||cellData2.getText().contains(rowData2.toUpperCase())) {
int n = k / colSize;
rowNo2 = n + 1;
}
System.out.println("row No2 = " + rowNo2);
System.out.println("row No1 = " + rowNo);
if (rowNo == rowNo2) {
break;
}
}
}
}

Related

How to solve two dimensional growth grid problem?

I was doing an assessment for job interview. One of the 3 problems that I had to solve in an hour was finding the maximal value in a grid where you traverse it and add 1 to the elements based on the coordinates given. I spent a little to much time on the second problem and only ended up with about 20 minutes for this one. I didn't finish it in time so it's bugging me.
I just want to make sure that the solution to the problem as I remember it is optimized.
The input is a String array of two int values and the dimension of the grid.
To illustrate, if the coordinates given are (3,2) (2,2) (1,3) then
[1][1][0]
[1][1][0]
[1][1][0]
[1][1][0]
[2][2][0]
[2][2][0]
[1][1][0]
[2][2][0]
[3][3][1]
and so on...
I believe the required result was the maximal value that is not in (1,1) and the number of times it exists in the grid.
This is the the solution I came up with. Is there any way to optimize it?
public static List<Integer> twoDimensions(String[] coordinates, int n) {
List<Integer> maxAndCount = new ArrayList<Integer>();
int[][] grid = new int[n][n];
int arrLength = coordinates.length;
int max = Integer.MIN_VALUE;
int count = 1;
for (int i = 0; i < arrLength; i++) {
String[] coors = coordinates[i].split(" ");
int row = Integer.parseInt(coors[0]);
int column = Integer.parseInt(coors[1]);
for (int j = 0; j < row; j++) {
for (int k = 0; k < column; k++) {
grid[j][k] += 1;
System.out.println("grid (" + j + "," + k + "): " + grid[j][k]);
if (!(j == 0 & k == 0) && grid[j][k] > max) {
max = grid[j][k];
count = 1;
} else if (grid[j][k] == max) {
count++;
}
}
}
}
maxAndCount.add(max);
maxAndCount.add(count);
return maxAndCount;
}
public static void main(String[] args) {
String[] coors = { "1 3", "2 4", "4 1", "3 2" };
System.out.println("The Max and count Are:" + twoDimensions(coors, 4).toString());
}
Other solution for exercise is. (erikdhv#gmail.com)
public static long countMax(List<String> upRight) {
// Write your code here
int xl = 1;
int yl = 1;
xl = Integer.parseInt(upRight.get(1).split(" ")[0]);
yl = Integer.parseInt(upRight.get(1).split(" ")[1]);
for (int i=0; i<upRight.size(); i++){
if (xl > Integer.parseInt(upRight.get((int) i).split(" ")[0]) ) xl = Integer.parseInt(upRight.get((int) i).split(" ")[0]);
if (yl > Integer.parseInt(upRight.get((int) i).split(" ")[1])) yl = Integer.parseInt(upRight.get((int) i).split(" ")[1]);
}
return (yl * xl);
}
This fails a few test cases I can think of, the value of XL should be on Index 0 not 1
Answer of erik fails for few test cases, just change int to long for xl and yl and boom... all test cases passed.
public static long twoDimensions(List<String> list, int n) {
long res = 0;
int rowCount =0,colCount=0;
for(int i=0;i<n;i++)
{
int row = list.get(i).charAt(0) - 48;
int col = list.get(i).charAt(2) - 48;
if(row > rowCount)
rowCount = row;
if(col >colCount)
colCount = col;
}
int tempArr[][] = new int[rowCount+1][colCount+1];
for(int i = 0;i<n;i++)
{
int row = list.get(i).charAt(0) - 48;
int col = list.get(i).charAt(2) - 48;
for(int j=row;j>=1;j--)
{
int m = j;
for(int k=1;k<=col;k++)
{
tempArr[m][k]= tempArr[m][k]+1;
if(tempArr[m][k]>res)
res = tempArr[m][k];
}
}
System.out.println("for row: "+row+" col: "+col);
for(int j = 0;j<=rowCount;j++)
{
for(int k=0;k<=colCount;k++)
{
System.out.print(""+tempArr[j][k]);
}
System.out.println("");
}
System.out.println("");
}
return res;
}

How to continue to loop and create new cell based on arraylist

I have a string arraylist name as code like this:
[a,b,c,d]
and another string arraylist that contain data like this name as DWS:
[a11,a22,a33,a44,a55,a66,a77,b11,b22,b33,b44,b55,b66,b77,c11,c22,c33,c44,c55,c66,c77,d11,d22,d33,d44,d55,d66,d77]
What I want to do is I want to write to the DWS arraylist into excel file like this:
I have tried this way:
FileInputStream file1 = new FileInputStream(new File(namefile));
XSSFWorkbook wb1 = new XSSFWorkbook(file1);
XSSFSheet sheet1 = wb1.getSheetAt(0);
int limit = 7;
for (int m = 0; m < code.size(); m++) {
for (int x = 0; x < DWS.size(); x++) {
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(x));
}
}
}
but the result that I get is:
Any idea how to overcome this problem?
UPDATE
I change my code like this as suggested:
int limit = 7;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
for (int m = 0; m < code.size(); m++) {
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(i));
}
}
and the result is like this:
It only loop the first 7 data. I need it to continue for the rest of the arraylist. like the first image.
UPDATE
let me explain again the flow of my code
1) It will loop the DWS arraylist into the first cell which is cell no 5 and loop until the last row which row no 7,
2) then , after it reach row no 7, it then supposedly create a new cell which in line Cell cell = row2.createCell(m * 3 + 4);and then again, continue looping from the DWS arraylist data.
3) this steps will continue until it reach the last arraylist data of DWS
is that possible to do that?
UPDATE 2.0
I change to this:
int cellValueIndex = 0;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
for (int m = 0; m < code.size(); m++) {
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
}
}
but I got error like this:
java.lang.IndexOutOfBoundsException
UPDATE 3.0
I change to this but the result is still wrong
int cellValueIndex = 0;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
for (int m = 0; m < code.size(); m++) {
Cell cell = row2.createCell(m * 3 + 4);
cell.setCellValue(DWS.get(cellValueIndex));
}
cellValueIndex = cellValueIndex + 1;
}
UPDATE 4.0
I have change to this:
int cellValueIndex = 0;
int counter = 0;
for (int i = 0; i < limit; i++) {
Row row2 = sheet1.getRow(i + 2);
Cell cell = row2.createCell(4);
cell.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
int x = row2.getRowNum();
if (x == limit) {
for (int m = 1; m < code.size(); m++) {
Cell cell1 = row2.createCell(m * 3 + 4);
cell1.setCellValue(DWS.get(cellValueIndex + 1));
cellValueIndex++;
}
}
}
The result is like this:
But when I try to set the i=0;, like this:
int cellValueIndex = 0;
for (int i = 0; i < total1; i++) {
Row row2 = sheet1.getRow(i + 2);
Cell cell = row2.createCell(4);
cell.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
int x = row2.getRowNum();
if (x == total1) {
i = 0;
for (int m = 1; m < shiftcode.size(); m++) {
Cell cell1 = row2.createCell(m * 3 + 4);
cell1.setCellValue(DWS.get(cellValueIndex));
cellValueIndex++;
i++;
}
}
}
I got error like this:
java.lang.IndexOutOfBoundsException
There are 3 for loops going on here! However as I see, you are creating cells in the third loop, where the value of the x is the last representational value from the DWS. If DWS is just a source of the cell values then you should have a separate index for that rather than keeping a loop for that.
In this case, though you don't realize from the end result, it is creating DWS.size times tables and it's cells! You don't realize it from the result because what you see is the last executed table which contains the value d77 only. And you are putting ONLY one value to all the cells because in the last loop DWS.get(x) is always constant, you don't have to do that.
You have to put different values to each and every cell.
Solution:
You need just 2 loops.
int cellValueIndex = 0;
for (int m = 0; m < limit; m++) {
// create a row here
for (int n = 0; n < code.length; n++) {
// take the value from DWS like DWS.get(cellValueIndex) and
// keep incrementing cellValueIndex by one always
}
}
If you use apache csv printer you can print rows easily. I wrote a solution for you that work:
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class DataGenerator {
private static final String[] HEADERS = {"a", "b", "c", "d"};
private static final String[] DATA = {"a11", "a22", "a33", "a44", "a55", "a66", "a77", "b11", "b22", "b33", "b44", "b55", "b66", "b77", "c11", "c22", "c33", "c44", "c55", "c66", "c77", "d11", "d22", "d33", "d44", "d55", "d66", "d77"};
private static CSVPrinter csvPrinter;
private static final CSVFormat getFileCsvFormat = CSVFormat.newFormat(';')
.withHeader(HEADERS)
.withRecordSeparator('\n');
private static final int rowSize = DATA.length / HEADERS.length; // 7
#BeforeAll
private static void setupCsv() throws IOException {
final long date = new Date().getTime();
final String fileTestData = "src/test/resources/csv/testdata.csv";
final FileWriter getDataWriter = new FileWriter(fileTestData);
csvPrinter = new CSVPrinter(getDataWriter, getFileCsvFormat);
System.out.println("Files created:" + fileTestData);
}
#Test
void printCsv() throws IOException {
final int dataLength = DATA.length;
final List<String[]> columns = getColumns(DATA);
final String[][] rows = transformToRows(columns);
for (int i = 0; i < rows.length; i++) {
printRow(rows[i]);
}
csvPrinter.flush();
}
private void printRow(final String[] row) {
try {
csvPrinter.printRecord(row);
} catch (final IOException e) {
e.printStackTrace();
}
}
private List<String[]> getColumns(final String[] data) {
final List<String[]> partitions = new ArrayList<>();
final int dataLength = data.length;
for (int i = 0; i < dataLength; i += rowSize) {
partitions.add(Arrays.copyOfRange(DATA, i, Math.min(i + rowSize, dataLength)));
}
return partitions;
}
/**
* a1 a2
* b1 b2
* - transform to: -
* a1 b1
* a2 b2
*/
private String[][] transformToRows(final List<String[]> columns) {
final String[][] dataMatrix = new String[rowSize][HEADERS.length];
for (int i = 0; i < columns.size(); i++) {
for (int j = 0; j < rowSize; j++) {
//{{a1, a2}, {b1, b2}}
dataMatrix[j][i] = columns.get(i)[j];
}
}
return dataMatrix;
}
I think your main problem however was how to transform your data from a column structure to a row structure, which you can print left to right. The input data is split into columns easily, but most csv/excel/... printers work by row. You can use the transformToRows method from my example to do this.

Need to get the Least Frequent element of a 2D array

int curr = 0;
int cnt;
String element = values[0][0];
int numberRepeats = 0;//cnt-counter,what's the element ,how many times it's repeated
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {//those two for's are for the current element
cnt = 0;//counter is nullified
for (int j2 = i; j2 < values.length; j2++) {
for (int k = 0; k < values[j2].length; k++) {//and those two are the compared element
if (values[i][j] == values[j2][k]) {//if the current element is the same as the compared element,increase counter
cnt++;
}
}
if (cnt >numberRepeats) {//after the compared element is done comparing and the number of repeats of the current element is more then the lastly checked element
element = values[i][j];//we get the element ,and how many times it's repeated
numberRepeats = cnt;
}
}
}
}
System.out.println();
System.out.println("The most popular item is: "+element+". Number sold:"+numberRepeats);`
This is what I currently get:
houseShampoo meatPork dairyCream wheatBread wheatCrackers
houseShampoo houseShampoo houseDetergent meatPork dairyYogurt
meatLamb dairyMilk dairyCream meatPork houseShampoo
wheatCookies meatLamb dairyYogurt wheatCereal wheatBread
meatLamb dairyMilk wheatCookies wheatCrackers wheatPasta
The most popular item is: houseShampoo. Number sold:4
This is what I want to get:
The least popular item is: wheatPasta. Number sold:1
But I don't know how to change the condition in the if statement to give out the least frequent element instead of most popular
Since you want to find the minimum number of repeats, start of your initial value with the maximum value:
int numberRepeats = Integer.MAX_VALUE;
and when an item is found with a smaller number of repeats, replace it:
if (cnt < numberRepeats) {
element = values[i][j];
numberRepeats = cnt;
}
This should do the trick.
Hi I choosed different approach using Map I hope it helps :)
int dimension = 3;
int sold = 0;
String product = "";
Map<String,Integer> productsSoldAndCount = new HashMap<>();
String[][] elements = new String[3][3];
elements[0] = new String[]{"houseShampoo","meatpork","dairyCream"};
elements[1] = new String[]{"houseShampoo","bread","cookies"};
elements[2] = new String[]{"meatpork","meatpork","meatpork"};
for(var tmpArray : elements){
for(var tmpString : tmpArray){
if(!productsSoldAndCount.containsKey(tmpString)){
productsSoldAndCount.put(tmpString,1);
}else{
productsSoldAndCount.put(tmpString,productsSoldAndCount.get(tmpString) + 1);
}
}
}
for(var resultPair : productsSoldAndCount.entrySet()){
if(resultPair.getValue() > sold){
sold = resultPair.getValue();
product = resultPair.getKey();
}
}
System.out.println("The most popular item is: " + product + " Sold: " + sold);

What is wrong with my matrix multiplication method?

I'm writing a matrix multiplication method using java. My class is Table which is a 2D array. This is the constructor of Table:
public Table(int n, int m, int val)
{
assert(n > 0 && m > 0);
elements = new int[n][m];
for(int row = 0; row < elements.length; row++)
{
for(int col = 0; col < elements[row].length; col++)
{
elements[row][col] = val;
}
}
}
And this is the method I'm talking about:
public static Table product(Table a, Table b)
{
assert(a.numCols() == b.numRows()) : "different dimensions!" + null;
Table c = new Table(a.numRows(), b.numCols(),0);
int res = 0;
for(int row = 0; row < a.numRows(); row++)
{
for(int col = 0; col < b.numCols(); col++)
{
for(int k = 0; k < a.numCols(); k ++)
{
res = res + a.get(row, k) * b.get(k, col);
c.set(row, col, res);
}
}
}
System.out.println(c.toString());
return c;
}
The method product should return a new Table which is the result of the multiplication of a and b. I think it's pretty clear what it should do. The problem is that it only computes c[0][0] correctly; So c.get(0,0) is computed correctly, but the results after that are not. Do you see what I'm doing wrong? I appreciate your help.
First thing that looks odd is:
int res = 0;
it should be reset in other place too. Hope that helps :)
...
for(int col = 0; col < b.numCols(); col++)
{
res = 0;
for(int k = 0; k < a.numCols(); k ++)
....
res is only set to zero all the way outside the whole set of loops. Its value doesn't make a lot of sense in your multiplication core routine. Re-check your loop logic.
Reset res in the first loop (might need some re-ordering of the loops, havn't checked and matrices is to long ago) or just change
res = res + a.get(row, k) * b.get(k, col);
to
res = c.get(row, col) + a.get(row, k) * b.get(k, col);
int res = 0; should be between the second and the third for-loops.

Excel is missing some values while writing

I am new to Apache-poi and using 3.8 version of poi. While writing value in the Excel,i check for the column names if they matched, i will write some value in that column and finish it, and again i will start writing on header. The problem is if write three column values only last column values are add or saved and first two values are not saved in the column. Can anyone tell what went wrong.
(sorry, in case any mistake)
Code:
int i = 0;
Row row = sheet.createRow(i);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_ORANGE.index);
String validate_header = null;
while (iterator.hasNext()) {
if (eiterator.hasNext()) {
validate_header = eiterator.next();
}
Cell cell = row.createCell(i);
String col_heading = iterator.next();
cell.setCellValue(col_heading);
if(col_heading.equalsIgnoreCase("Assigned Date"))
{
Add_value(i, col_heading, row, sheet);
row=sheet.getRow(0);
cell=row.getCell(i);
}
else if(col_heading.startsWith("Review"))
{
int count=-1;
int n=Col_values.get("Defect Summary").size();
for (int j = 0; j < n; j++) {
row = sheet.createRow(count);
cell = row.createCell(i);
String s="External QC Defect ";
cell.setCellValue(s);
count++;
}
row=sheet.getRow(0);
cell=row.getCell(i);
}
sheet.autoSizeColumn(i);
i++;
}
private static Sheet Add_value(int k,String name,Row row, Sheet sheet) {
System.out.println("Inside the add method");
if(name.equalsIgnoreCase("Assigned Date")||name.equalsIgnoreCase("Reported Date") )
{
vector = Col_values.get("TargetDate");
int count = 1;
System.out.println("IF Size of the vector " + vector.size());
for (int j = 0; j < vector.size(); j++) {
row = sheet.createRow(count);
cell = row.createCell(k);
String s = (String) vector.get(j);
System.out.println(s);
cell.setCellValue(s);
count++;
}
}
else
{
vector = Col_values.get("Defect Summary");
int count = 1;
System.out.println("ELSE Size of the vector " + vector.size());
for (int j = 0; j < vector.size(); j++) {
row = sheet.createRow(count);
cell = row.createCell(k);
String s = (String) vector.get(j);
System.out.println(s);
cell.setCellValue(s);
count++;
}
}
return sheet;
}
'
Can u tell what went Wrong?
It seems that Add_value starts creating rows from top. Therefore on the second call the old rows are removed.
Replace
row = sheet.createRow(count);
with
row = k == 0 ? sheet.createRow(count) : sheet.getRow(count);

Categories