Sorted Matrix Search - java

I keep receiving an ArrayIndexOutOfBounds on the line directly after the for loop. I would also wondering how I could continue to loop the matrix to iterate the row or column until the target is reached.
In the given matrix, I want to start in the bottom left hand corner. If the target value is less than the selected number then the row moves up. If the target value is greater than the selected number then column moves one to the right.
public static void optimizedSearch(int matrix[][], int array_size, int target) {
int row = 0;
int col = array_size-1;
boolean found = false;
int comparison_counter = 0;
int end = array_size * 2;
//while (!found) {
for (int i = 0; i < 100 && !found; i++) {
if (matrix[row][col] < target ) {
row++;
comparison_counter++;
} else if (matrix[row][col] > target) {
col--;
comparison_counter++;
} else if (matrix[row][col] == target) {
found = true;
} else if ((i == end) && (found == false)) {
found=false;
}
}// end for loop
if (found == true) {
System.out.println(target + " found in " + comparison_counter + " number of comparisons using optimized search");
} else
System.out.println(target + " not found in " + comparison_counter + " number of comparisons using optimized search");
} //end optimizedSearch

Related

Bug in beginner Binary search

It shows the output when the Search value(SV) is present in the array. But not if it is not there. It keeps asking for input and keeps looping.
This is my first time attempting to make a code for binary search
import java.util.Scanner;
public class Binary_search {
public static void main() {
Scanner input = new Scanner(System.in);
int start = 0;
int end = arr.length;
//I used flag to end the loop
int Flag = 0;
int mid = 0;
int SV = input.nextInt();
//here I enter values in the array
for (int x = 0; x <= 4; x++) {
arr[x] = input.nextInt();
}
//here I start a loop for the search
while (Flag == 0) {
mid = (start + end) / 2;
if (mid == SV) {
System.out.println("Number Found" + arr[mid]);
Flag = Flag + 1;
} else if (mid > SV) {
end = mid - 1;
} else if (mid < SV) {
start = mid + 1;
}
//this was the second possibility if the number was not present
else if (start == end) {
Flag = Flag + 1;
System.out.println("Number not found");
}
}
}
}
If the SV is present in the array it will show what position it is in, "Number Found" + arr[mid]. But if it is not there it is supposed to output, "Number not found", however, this does not happen and it keeps asking for input.
You can create simple way like this.
Please compare and check where you need to correct.
public class Test {
public static void main(String[] args) {
int arr[] = { 10, 20, 30, 40, 50 };
int key = 3;
binarySearchExample(arr, key);
}
public static void binarySearchExample(int arr[], int key) {
int first = 0;
int last = arr.length - 1;
int mid = (first + last) / 2;
while (first <= last) {
if (arr[mid] < key) {
first = mid + 1;
} else if (arr[mid] == key) {
System.out.println("Element is found at index: " + mid);
break;
} else {
last = mid - 1;
}
mid = (first + last) / 2;
}
if (first > last) {
System.out.println("Element is not found!");
}
}
}
You can create a class like this to input the numbers from the user and store it in an array and search another inputted number in the array with binary search and display its location.
import java.util.*;
class BinarySearch
{
public static void main()
{
int i, num, item, array[], first, last, middle;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = sc.nextInt();
//array gets created by inputted space
array = new int[num];
System.out.println("Enter " + num + " integers");
for (i = 0; i < num; i++)
array[i] = sc.nextInt();
System.out.println("Enter the number to be searched:");
item = sc.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;
//search starts
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
//number found in
System.out.println(item + " is found at location " + (middle + 1));
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
//number not found in array
System.out.println(item + " is not found.\n");
}
}

start searching in a 2 dimensional array from a sertent element java

I am trying to write a code that searches through a 2 dimensional array and tries to find the closest element to "x" that is empty, if "x" has any data in. The elements' coordinates are given from another method. For example "x" is (3,2). If there's no empty element then the code must continue searching in the whole array.
public void find(int row, int column) {
for (int i = row - 1; i < row + 2; i++) {
for (int k = column - 1; k < column + 2; k++) {
if (this.arr[i][k].equals(" ")) {
System.out.println(i + "," + k + " is empty.");
return;
}
}
}
}
I am looking foreword for any helpful suggestions on how to code this method.
Thank you.
Under assumptions
this is matrix (each row has equal num of columns)
method arguments are valid: 0 <= row < numOfRows and 0 <= column < numOfColumns
this code will do search of 2 dimensional array around specified element in the way you've described.
Note that this is not clock direction round search around specified element, but search from top left corner to bottom right corner (from top to bottom and from left to right)
public void find(int row, int column) {
int distance = 1;
int numOfRows = arr.length;
int numOfColumns = 0;
if (arr.length > 0) {
numOfColumns = arr[0].length;
}
int maxDistance = Math.max(numOfRows, numOfColumns);
for (distance = 1; distance < maxDistance; distance ++) {
for (int i = Math.max(row - distance, 0); i <= Math.min(row + distance, numOfRows - 1); i++) {
if (Math.abs(i - row) == distance) {
// Check row
for (int k = Math.max(column - distance, 0); k <= Math.min(column + distance, numOfColumns - 1); k++) {
if (arr[i][k] == null || arr[i][k].trim().isEmpty()) {
System.out.println((i+1) + "," + (k+1) + " is empty.");
return;
} else {
System.out.println((i+1) + "," + (k+1) + " is not empty.");
}
}
} else {
// Check only edge elements
int k = column - distance;
if (k >= 0) {
if (arr[i][k] == null || arr[i][k].trim().isEmpty()) {
System.out.println((i+1) + "," + (k+1) + " is empty.");
return;
} else {
System.out.println((i+1) + "," + (k+1) + " is not empty.");
}
}
k = column + distance;
if (k < numOfColumns) {
if (arr[i][k] == null || arr[i][k].trim().isEmpty()) {
System.out.println((i+1) + "," + (k+1) + " is empty.");
return;
} else {
System.out.println((i+1) + "," + (k+1) + " is not empty.");
}
}
}
}
}
System.out.println("No empty elements");
}

How do I generate a magic square using only a 1 dimensional array?

I am assigned to prompt a user to give the order of a magic square (a magic square of order 3 would be a 3x3 matrix) and then generate a magic square of that order without using a 2 dimensional array.
Here's what I know and understand:
The Array will have order squared elements.
When you print out the table, the location of number in the array is [order × row + col]
The index of the array's location on the table is (index/order, index % order)
Here's what I am given but don't understand how to implement properly:
row = order − 1, col = order/2 and i = 1
Repeat the following until i = order^2 + 1:
(a) magic[index] = i
(b) increment row and col by 1. that is, row = (row + 1) mod order and col = (col + 1) % order
(c) If magic[index] != 0
i. row = (row + order − 2) % order
ii. col = (col + order − 1) % order
(d) increment i by 1
This is my code so far:
package magicsquarecreator;
import java.io.IOException;
import java.util.Scanner;
public class MagicSquareDemo
{
public static void main(String[] args)
{
Scanner keyIn = new Scanner(System.in);
String option;
do
{
System.out.println();
System.out.println(" MAGIC SQUARE APPLICATION ");
System.out.println("==================================================");
System.out.println("Generate a Magic Square........................[1]");
System.out.println("Test for a Magic Square........................[2]");
System.out.println("Quit the Program...............................[0]");
System.out.println();
System.out.print("Select an option -> ");
option = keyIn.next();
System.out.println();
switch(option)
{
case "1":
try
{
System.out.println("Enter the dimension of the magic square -> ");
int order = keyIn.nextInt();
if (order < 1)
{
System.out.println("The order must be positive and odd");
}
else if (order % 2 == 0)
{
System.out.println("The program can only generate a magic square"
+ "\nwhose dimension is positive odd number.");
}
else if (order % 2 != 0)
{
int i=1, j=1;
int row = order - 1;
int col = order/2;
int[] magic = new int[order*order];
for (i=1; i<=order; i++)
{
magic[i] = i;
row = (row + 1) % order;
col = (col + 1) % order;
if (magic[i] != 0)
{
row = (row + order − 2) % order;
col = (col + order − 1) % order;
}
}
}
}
catch(IOException e)
{
System.out.println(e);
}
break;
case "2":
try
{
}
catch(IOException e)
{
System.out.println(e);
}
break;
case "0":
break;
default: System.out.println("Invalid choice...please select a valid menu option.");
}
}
while (option.compareTo("0") != 0);
}
}
Right now I am just worried about getting and understanding case 1. The Try Catch statements for file output, but I can do that on my own time. The biggest problem currently is understanding how to create this loop.
to be honest, i also didnt really understand the taks, as it was written from u. if i do it as i understand it there, it does not work.
but i looked ub how it should work and finally i got it.
here is the part for the else if (order % 2 != 0) condition as a methode (i tested it, it is working right now):
public static void magicSqare(int order){
System.out.println(order);
int row = order - 1;
int col = order /2;
int [] magic = new int [order*order];
int index;
index = (row)*order + col;
magic[index]= 1;
for (int i = 2; i <= order*order; i++) {
if (magic[((row +1) % order)*order + ((col +1) % order)] == 0) {
row = (row +1) % order;
col = (col +1) % order;
}
else {
row = (row + order -1) % order;
//col = (col + order -1) % order;
}
index = (row)*order + col;
magic[index]= i;
}
//System.out.println(Arrays.toString(magic));
}

Recursive method that searches an array doesn't work

So I have this recursive method that searches a 4x4 "board" for a word (think boggle except it only looks above, below, left, and right of the current letter). It gets passed an index (the current letter it is searching for from a given word), and the row and column to search around. The first if statement takes care of the first letter, and always works. The next else if statement doesn't work, and I'm not sure why. Any help is appreciated as to why. secondArray is used in another part of the program when it is displayed.
private boolean verifyWord(int index, int row, int column) {
System.out.println(index + " " + row + " " +column);
if (index == 0) {
for (int i = 0; i < letterArray.length; i++) {
for (int i2 = 0; i2 < letterArray[0].length; i2++) {
if (letterArray[i][i2] == wordToFind.charAt(index)) {
secondArray[i][i2] = true;
verifyWord(index+1, i, i2);
}
}
}
} else if (index > 0 && index < wordToFind.length()) {
// check above row
if (row+1 < row) {
if (letterArray[row+1][column] == wordToFind.charAt(index)) {
secondArray[row+1][column] = true;
verifyWord(index+1, row+1, column);
}
}
//check below row
if (row-1 >= 0) {
if (letterArray[row-1][column] == wordToFind.charAt(index)) {
secondArray[row-1][column] = true;
verifyWord(index+1, row-1, column);
}
}
//check left column
if (column-1 >= 0) {
if (letterArray[row][column-1] == wordToFind.charAt(index)) {
secondArray[row][column-1] = true;
verifyWord(index+1, row, column-1);
}
}
//check right column
if (column+1 < letterArray[0].length) {
if (letterArray[row][column+1] == wordToFind.charAt(index)) {
secondArray[row][column+1] = true;
verifyWord(index+1, row, column+1);
}
}
} else {
boolCheck = true;
}
return boolCheck;
}
The first condition if(row+1 < row) in your else if(index > 0 && index < wordToFind.length()) would never be evaluated to true (x+1 is always bigger than x).
You probably want it to be if(row+1 < letterArray.length)

java grid boundary

The problem is to find the shortest path on a grid from a start point to a finish point. the grid is a 2 dimensional array filled with 0's and 1's. 1's are the path. I have a method that checks the neighbors of a given coordinate to see if its a path. The problem im having is with the boundaries of the grid. The right and bottom boundary can just be checked using the arrays length and the length of a column. But how would i check to make sure that i dont try to check a point thats to the left of the grid or above the grid?
This is my method
public static void neighbors(coordinate current, int[][] grid, Queue q)
{
int row = current.getRow();
int col = current.getCol();
if(grid[row-1][col] == 1)
{
if(grid[row][col] == -1)
{
grid[row-1][col] = grid[row][col] + 2;
}
else
{
grid[row-1][col] = grid[row][col] + 1;
}
coordinate x = new coordinate(row-1,col);
q.enqueue(x);
}
else if(grid[row+1][col] == 1)
{
if(grid[row][col] == -1)
{
grid[row+1][col] = grid[row][col] + 2;
}
else
{
grid[row+1][col] = grid[row][col] + 1;
}
coordinate x = new coordinate(row+1,col);
q.enqueue(x);
}
else if(grid[row][col-1] == 1)
{
if(grid[row][col] == -1)
{
grid[row][col-1] = grid[row][col] + 2;
}
else
{
grid[row][col-1] = grid[row][col] + 1;
}
coordinate x = new coordinate(row, col - 1);
q.enqueue(x);
}
else if(grid[row][col+1] == 1)
{
if(grid[row][col+1] == -1)
{
grid[row][col+1] = grid[row][col] + 1;
}
else
{
grid[row][col+1] = grid[row][col] + 1;
}
coordinate x = new coordinate(row, col + 1);
q.enqueue(x);
}
else
{
}
q.dequeue();
}
I assume that the leftmost and topmost indexes are 0 in your arrays, so just make sure that index-1 >= 0 before indexing into the appropriate array.

Categories

Resources