java word search diagonally - java

so I've been working on this for hours but i cant seem to figure out how the heck to search through a 2D charr array diagonally. Some context for this, I have figured out how to do the search both vertically and horizontally. Also, I am expected to find words from all 4 directions diagonally (top left -> bottom right/ bottom right -> top left/top right -> bottom left/top right -> bottom left)
Here's what I got so far
public void searchDiagonal() {
char [][] grid = //is a [15][15] array
char[] sample = {'W','O','R','D'}
int startR = 0;
int startC = 0;
int endR = 0;
int endC = 0;
boolean wordFound = false;
int row = 0;
for(int i = grid.length - 1; i >= 0; i--)
{
if(i == grid.length - 1) {
//check the middle diagonal
for(int j = grid.length - 1; j >= 0; j--) {
int index = 0;
if(sample[index] == grid[j][j])
{
startR = j;
startC = j;
if(index == sample.length - 1) {
//word has been found
endR = j;
endC = j;
wordFound = true;
System.out.println("Word found at [" + startR + "][" + startC + "] & ["
+ endR + "][" + endC + "]");
break;
}
index++;
}
if(wordFound)
break;
}
}
}
for(int i = grid.length - 1; i >= 0; i--) {
for(int j = grid.length - 1; j >= 0; j--) {
}
//now i will handle up/down and row will handle left/right [row][i]
if(i == 13) {
row = 14;
}
int index = 0;
if(sample[index] == grid[row][i])
{
if(index == 0) {
startR = row;
startC = i;
}
//first char matches
if(sample.length - 1 == index) {
endR = row;
endxC = i;
wordFound = true;
SSystem.out.println("Word found at [" + startR + "][" + startC + "] & ["
+ endR + "][" + endC + "]");
break;
}
index++;
}
row--;
}
}
Thank you in advanced!

To find out 4 diagonal words i would try following
Find TopLeftBottomRight word
reverse it
Find TopRightBottomLeft word
reverse it
find the sample word in above word lists.
Working code for find all 4 diagonal words
public class Main {
public static void main(String[] args) {
char[][] testData = {{'a', 'b', 'c', 'd'}, {'e', 'c', 'b', 'e'}, {'h', 'g', 'a', 'm'}, {'w', 'x', 'z', 't'}};
char[] sample = {'c', 'a', 't'};
boolean result = findInDiagonalWords(diagonalWords(testData),sample);
System.out.println(result);
}
private static List<String> diagonalWords(char[][] testData) {
String first = topLeftBottomRight(testData);
StringBuilder sb = new StringBuilder();
sb.append(first);
String second = sb.reverse().toString();
String third = bottomLeftTopRight(testData);
StringBuilder sb1 = new StringBuilder();
sb1.append(third);
String fourth = sb1.reverse().toString();
return Arrays.asList(first, second, third, fourth);
}
private static String topLeftBottomRight(char[][] testData) {
String topLeftBottomRight = "";
for (int i = 0; i < testData.length; i++) {
for (int j = 0; j <= i; j++) {
if (i == j) {
topLeftBottomRight = topLeftBottomRight + testData[i][j];
}
}
}
return topLeftBottomRight;
}
private static String bottomLeftTopRight(char[][] testData) {
String bottomLeftTopRight = "";
for (int i = testData.length; i > 0; i--) {
for (int j = 0; j < testData.length; j++) {
if ((testData.length - i) == j) {
bottomLeftTopRight = bottomLeftTopRight + testData[i - 1][j];
break;
}
}
}
return bottomLeftTopRight;
}
private static boolean findInDiagonalWords(List<String> diagonalWords, char[] sample) {
// return true if sample lies in diagonal words
//return false;
}
}

Related

How can I test credit numbers with hyphens (" -" ) to get it as INVALID . When I tried 4003-6000-0000-0014 i am getting errors

I cant get credit card numbers containing hymens as INVALID such as 4003-6000-0000-0014 must give me INVALID but its giving me errors of string.
public class prog {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in) ;
System.out.println("How many credit card you want to check?");
int numOfCredit = userInput.nextInt() ;
int creditnumbers[] = new int[numOfCredit] ;
for (int i = 0 ; i<numOfCredit ; i++)
{
System.out.println("Enter credit card number "+(i+1)+": ") ;
String creditNumber = userInput.next() ;
validateCreditCardNumber(creditNumber);
}
}
private static void validateCreditCardNumber(String str) { // function to check credit numbers
int[] ints = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
for (int i = ints.length - 2; i >= 0; i = i - 2) {
int j = ints[i];
j = j * 2;
if (j > 9) {
j = j % 10 + 1;
}
ints[i] = j;
}
int sum = 0;
for (int i = 0; i < ints.length; i++)
{
sum += ints[i];
}
if (sum % 10 == 0)
{
System.out.println("VALID");
}
else
{
System.out.println("INVALID");
}
}
}
I get these errors after running with hymens :
Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:642)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at testing/testing.prog.validateCreditCardNumber(prog.java:33)
at testing/testing.prog.main(prog.java:22)
you can replace in your string "-" with "" (blank) and then apply this function:
String card = "4003-6000-0000-0014";
Boolean t = check(card.replace("-",""));
public static boolean check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}

How to fix "Index 5 out of bounds for length 5" error in Java

I am working on solution for the CCC 2018 Robo Thieves Problem, it a simplified version of the original problem. My problem is that it will give me this "Index 5 out of bounds for length 5" when I executed my code and I'm not sure why it is happening. Half of my program executes and then this error occurs.
import java.util.*;
public class RoboThieves {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> rowPos = new ArrayList<Integer>();
ArrayList<Integer> colPos = new ArrayList<Integer>();
int sRow = -1; // robot pos
int sCol = -1;
int dotCounter = 0;
int stepCounter = 0;
int rowSize = sc.nextInt();
int colSize = sc.nextInt();
char[][] factoryGrid = new char[rowSize][colSize];
for (int i = 0; i < rowSize; i++) {
String rowChars = sc.next().toUpperCase();
for (int j = 0; j < colSize; j++) {
factoryGrid[i][j] = rowChars.charAt(j);
}
}
// check to see if the grid was inputted properly (with square brackets)
/*
* for (char [] row: factoryGrid) { System.out.println(Arrays.toString(row)); }
*/
// check to see if the grid was inputted properly (as inputted)
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
System.out.print(factoryGrid[i][j]);
}
System.out.println();
}
// locate dots and store their row and col in arraylists
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (factoryGrid[i][j] == '.') {
rowPos.add(i);
colPos.add(j);
dotCounter++;
}
}
}
// print dot location to check
for (int i = 0; i < rowPos.size(); i++) {
System.out.println("Dot Position = " + "(" + rowPos.get(i) + "," + colPos.get(i) + ")");
}
// locate robot position
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (factoryGrid[i][j] == 'S')
sRow = i;
sCol = j;
}
}
// print camera location to check
System.out.println("Camera Position = " + "(" + sRow + "," + sCol + ")");
//System.out.println(dotCounter); // test to see if counter works
char above = getAbove(factoryGrid, sRow, sCol);
char right = getRight(factoryGrid, sRow, sCol);
char below = getBelow(factoryGrid, sRow, sCol);
char left = getLeft(factoryGrid, sRow, sCol);
if (above == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
sRow = sRow - 1;
// sCol = sCol;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (right == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
// sRow = sRow;
sCol = sCol + 1;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (below == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
sRow = sRow + 1;
// sCol = sCol;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else if (left == '.') {
boolean canMove = check360(factoryGrid, sRow, sCol);
// check if camera is around dot
if (canMove == true) {
// set robot position to dot position and old position to W
// sRow = sRow;
sCol = sCol - 1;
factoryGrid[sRow][sCol] = 'W';
dotCounter--;
stepCounter++;
} else {
// this is if there is a camera in the 360 radius of the open space
System.out.println("You cannot move to the space beside because there is a camera in your sightline!");
}
} else {
System.out.println(
"The robot cannot move to any spaces try inputting a factory layout that can produce an answer.");
} // end if above dot (yes)
System.out.println(stepCounter);
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
System.out.print(factoryGrid[i][j]);
}
System.out.println();
}
} // end main method
public static char getLeft(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow][(cCol - 1)];
}
public static char getAbove(char[][] factGrid, int cRow, int cCol) {
return factGrid[(cRow - 1)][(cCol)];
}
public static char getBelow(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow + 1][cCol];
}
public static char getRight(char[][] factGrid, int cRow, int cCol) {
return factGrid[cRow][(cCol + 1)];
}
public static boolean check360(char[][] factGrid, int cRow, int cCol) {
boolean canMove = true;
char left = getLeft(factGrid, cRow, cCol);
char above = getAbove(factGrid, cRow, cCol);
char right = getRight(factGrid, cRow, cCol);
char below = getBelow(factGrid, cRow, cCol);
if (left == 'C' || above == 'C' || right == 'C' || below == 'C') {
canMove = false;
}
return canMove;
}
} // end main program
Upon first look, I expect that the issue may lie in your getLeft(), getAbove(), getRight(), and getBelow() methods.
In these methods, you give it a value for cRow and cCol and add or subtract 1. However, you need to make sure that the index you are querying does not exceed the size of the double array factGrid, or go below 0.
For example, in your getRight() method, you might try:
public static char getRight(char[][] factGrid, int cRow, int cCol) {
if(factGrid[0].length > (cCol + 1)) {
return factGrid[cRow][(cCol + 1)];
} else {
return '';
}
}

Converting a 2d String array to a 2d double array

I am making a project in which I need to put a certain precision(0.00 or 0.000) on values in a 2d array. The 2d array is a String and i want to convert it to double. But when I try, I get a NullPointerException, I don't know why.
Afterwards I want to again convert it to a String array.
print-method code:
public void printSheet() {
int start = 'a';
char letter = (char) start;
//kolomnamen
for (int i = 0; i < COLUMNS + 1; i++) {
if (i == 0) {
System.out.print(" ");
} else if (WIDTH != 0) {
String s = "";
for (int j = 0; j < WIDTH / 2; j++) {
s += "-";
}
s += (char) (letter + i - 1);
for (int j = 0; j < WIDTH / 2; j++) {
s += "-";
}
System.out.print(s + "\t");
}
}
System.out.println("\n");
for (int i = 0; i < sheet.length; i++) {
System.out.print(1 + i + "." + " ");
for (int j = 0; j < sheet[i].length; j++) {
double[][] voorlopig = null;
voorlopig[i][j] = Double.parseDouble(sheet[i][j]); //<-- problem
double d = voorlopig[i][j];
// String s = " " + sheet[i][j];
System.out.println(voorlopig);
double thaprez = (precision / precision) + (Math.pow(precision, 10)) - 1;
d = Math.floor(d * thaprez + .5) / thaprez;
String s = " " + voorlopig[i][j];
if (sheet[i][j] == null) {
System.out.print(s + "\t\t");
} else if (sheet[i][j].length() < 10) {
System.out.print(s + "\t");
} else {
System.out.print(s);
}
}
System.out.println("\n");
}
}
Thanks in advance.
Try to initialize your array double[][] voorlopig maybe like this:
double[][] voorlopig = new double[sheet.length][sheet.length];
You get NullPointerException because the array voorlopig was double[][] voorlopig = null;
double[][] voorlopig = null;
voorlopig[i][j] = Double.parseDouble(sheet[i][j]);
voorlopig is set to null, you'll get a NullPointerException.Initialize voorlopig before using it.

Making a hollow diamond with a word in it

What I need is a little modification to my code so that every part of my hollow diamond prints a letter of the word "HURRICANE"
My code is:
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(a)); //needs change
} else {
System.out.print(' ');
}
}
System.out.println();
}
The output comes out as:
H
H H
H H
H H
H H
H H
H H
H H
H
I need to modify my "charAt" statement a little so it comes out to be:
H
U U
R R
R R
I I
C C
A A
N N
E
How should I make my print statement?
It's worth noting that the example provided only works for Strings the same length as "HURRICANE". A superior solution would work for all strings.
Partial solution for you to complete, since I guess it's your coursework and I don't want you to copy / paste / fail exams :P
public static void main(String[] args) {
String st1 = "HURRICANE";
char[] st1CharArray = st1.toCharArray();
int maxSpaces = st1CharArray.length / 2 + 1;
for (int i = 0; i <= st1CharArray.length / 2; i++) {
if (i == 0) {
System.out.println(getSpacesString(maxSpaces) + st1CharArray[i]);
} else {
System.out.println(getSpacesString(maxSpaces - i)
+ st1CharArray[i] + getSpacesString(i * 2 - 1)
+ st1CharArray[i]);
}
}
// Loop from st1CharArray.length / 2 + 1 and get the second half done.
}
private static String getSpacesString(int numberOfSpaces) {
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < numberOfSpaces; i++) {
strBuilder.append(" ");
}
return strBuilder.toString();
}
//: Playground - noun: a place where people can play
import UIKit
var name : String = "HURRICANE"
var dimensions : Int = name.count - 1
var k : Int = 0
for rows in 0...dimensions{
for columns in 0...dimensions{
k = abs( (dimensions/2) - rows )
if columns == k || columns == dimensions - k{
print(Array(name)[rows], terminator: "")
}
else{
print(" ", terminator: "" )
}
}
print("")
}
String st1 = "HURRICANE";
int a = 0;
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(5 - i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= 9; j++) {
if (j == i || (10 - i) == j) {
System.out.print(st1.charAt(3 + i));
} else {
System.out.print(' ');
}
}
System.out.println();
}
Let's assume that a word has an odd number of characters, otherwise we get a crooked diamond.
Try it online!
public static void main(String[] args) {
String str = "abrahadabra";
int n = str.length() / 2;
for (int i = -n, ch = 0; i <= n && ch < str.length(); i++, ch++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print(str.charAt(ch));
else
System.out.print(" ");
System.out.println();
}
}
Output:
a
b b
r r
a a
h h
a a
d d
a a
b b
r r
a

Trying to search a grid of characters in java for a specific word. How can I search from right to left after searching from left to right?

I have the following code to search a grid of characters below from left to right to find a word. This works perfectly.
// Left to Right
public static String findLeftToRight (char[][]board, String word) {
char[] letters = word.toCharArray();
for (int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++) {
boolean found = true;
for (int k = 0; k < letters.length; k++) {
if ((j+k >= board[i].length) || (letters[k] != board[i][j+k])) {
found = false;
break;
}
}
if (found) {
return "String " + word + " found in row=" + i + " col=" +j;
}
}
}
return "String " + word + " not found";
} // end findLeftToRight
However, I cannot figure out how to search from right to left. Below is my attempt at searching from right to left, but it does not work. Can someone tell me what I'm doing wrong?
// Right to Left
public static String findRightToLeft (char[][]board, String word) {
char[] letters = word.toCharArray();
for (int i = board.length-1; i > -1; i--){
for (int j = board[i].length-1; j > -1; j--) {
boolean found = true;
for (int k = 0; k < letters.length; k++) {
if ((j+k <= board[i].length) || (letters[k] != board[i][j+k])) {
found = false;
break;
}
}
if (found) {
return "String " + word + " found in row=" + i + " col=" +j;
}
}
}
return "String " + word + " not found";
} // end findLeftToRight
if ((j+k <= board[i].length) || (letters[k] != board[i][j+k])) {
also needs to be reversed:
if ((j - k < 0) || (letters[k] != board[i][j-k])) {

Categories