2D Array to Rectangles - java

Is there a way to parse 2 dimensional array like this into a rectangle object (x,y, width, height)?. I need the array of all possible rectangles...
{0,0,0,0,0}
{0,0,0,0,0}
{0,1,1,0,0}
{0,1,1,0,0}
{0,0,0,0,0}
This would give 4 rectangles (we are looking at 0):
0,0,5,2
0,0,1,5
3,0,2,5
0,5,5,1
I have tried something like this, but it only gives the area of the biggest rectangle...
public static int[] findMaxRectangleArea(int[][] A, int m, int n) {
// m=rows & n=cols according to question
int corX =0, corY = 0;
int[] single = new int[n];
int largeX = 0, largest = 0;
for (int i = 0; i < m; i++) {
single = new int[n]; // one d array used to check line by line &
// it's size will be n
for (int k = i; k < m; k++) { // this is used for to run until i
// contains element
int a = 0;
int y = k - i + 1; // is used for row and col of the comming
// array
int shrt = 0, ii = 0, small = 0;
int mix = 0;
int findX = 0;
for (int j = 0; j < n; j++) {
single[j] = single[j] + A[k][j]; // postions element are
// added
if (single[j] == y) { // element position equals
shrt = (a == 0) ? j : shrt; // shortcut
a = a + 1;
if (a > findX) {
findX = a;
mix = shrt;
}
} else {
a = 0;
}
}
a = findX;
a = (a == y) ? a - 1 : a;
if (a * y > largeX * largest) { // here i am checking the values
// with xy
largeX = a;
largest = y;
ii = i;
small = mix;
}
}
}// end of loop
return largeX * largest;
}
this code is working with 1s, but that is not the point right now

Related

Is there a test case scenario in which my program will fail?

Problem : You have L, a list containing some digits (0 to 9). Write a function solution(L) which finds the largest number that can be made from some or all of these digits and is divisible by 3. If it is not possible to make such a number, return 0 as the solution. L will contain anywhere from 1 to 9 digits. The same digit may appear multiple times in the list, but each element in the list may only be used once.
Test Cases :
Input:
Solution.solution({3, 1, 4, 1})
Output: 4311
Input:
Solution.solution({3, 1, 4, 1, 5, 9})
Output: 94311
My Program :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
public class Solution {
static ArrayList<Integer> al = new ArrayList<Integer>();
static ArrayList<Integer> largest = new ArrayList<Integer>();
static int o = 1;
static int po = 0;
static void combinations(String[] digits, String[] data, int start, int end, int index, int r)
{
if (index == r)
{
String temp = "0";
for (int j = 0; j < r; j++)
{
temp = temp + data[j];
// System.out.print(data[j]);
}
Integer d = Integer.parseInt(temp);
al.add(d);
// System.out.println(al);
}
for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
{
data[index] = digits[i];
combinations(digits, data, i + 1, end, index + 1, r);
}
}
static void printCombinations(String[] sequence, int N)
{
String[] data = new String[N];
for (int r = 0; r < sequence.length; r++)
combinations(sequence, data, 0, N - 1, 0, r);
}
static String[] convert(int[] x)
{
String c[] = new String[x.length];
for(int i=0; i < x.length; i++)
{
Integer k = x[i];
if(k==0)
{
o = o * 10;
continue;
}
c[i] = k.toString();
}
// System.out.println(o);
c = Arrays.stream(c).filter(s -> (s != null && s.length() > 0)).toArray(String[]::new);
po = c.length;
// System.out.println("Come"+ Arrays.asList(c));
return c;
}
public static int solution(int[] l) {
if(l.length==0)
return 0;
if(IntStream.of(l).sum()%3==0)
{
String x = "";
Arrays.sort(l);
for (int i = l.length - 1; i >= 0; i--) {
x = x + l[i];
}
return Integer.parseInt(x);
}
printCombinations(convert(l),po);
al.sort(Comparator.reverseOrder());
al.remove(al.size()-1);
al.removeIf( num -> num%3!=0);
if(al.isEmpty())
return 0;
for(int i=0; i< al.size(); i++)
{
Integer n = al.get(i);
printMaxNum(n);
}
// System.out.println(al);
// System.out.println(largest);
return largest.get(0)*o;
}
static void printMaxNum(int num)
{
// hashed array to store count of digits
int count[] = new int[10];
// Converting given number to string
String str = Integer.toString(num);
// Updating the count array
for(int i=0; i < str.length(); i++)
count[str.charAt(i)-'0']++;
// result is to store the final number
int result = 0, multiplier = 1;
// Traversing the count array
// to calculate the maximum number
for (int i = 0; i <= 9; i++)
{
while (count[i] > 0)
{
result = result + (i * multiplier);
count[i]--;
multiplier = multiplier * 10;
}
}
// return the result
largest.add(result);
}
public static void main(String[] args) {
System.out.println(solution(new int[]{9,8,2,3}));
}
}
My Code passes both given test cases and 3 other hidden test cases except one. I tried all possible input combinations but couldn't get to the exact failure. The return type by default is given as int and therefore they would not pass values which give output that does not fit in int. Any other scenario where my code fails?

Shortest path for the knight (BFS)

Please help me understand what I am doing wrong with my code. I am trying to get the shortest path using BFS to solve the problem but it's either giving me -1 or 2. It should give me 6 as the answer. What am I doing wrong? This is the problem:
Given a chess board, find the shortest distance(minimum number of steps) taken by a knight to reach given destination from given source.
For example, N = 8 (8 x 8 board), Source = (7, 0) Destination = (0, 7)
Minimum number of steps required is 6
My code is below:
class Point {
int x, y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
class knightShortestPath {
int N = 8;
public static boolean visited[][];
public boolean isPositionValid(int x, int y){
if( x < 0 || y < 0 || x > this.N || y > this.N){
return false;
}
return true;
}
public void createChessBoard(int N) {
this.N = N;
visited = new boolean[this.N][this.N];
for (int i = 0; i < this.N; i++) {
for (int j = 0; j < this.N; j++) {
visited[i][j] = false;
}
}
}
public int BFS(Point source, Point destination) {
int row[] = {2, 2, -2, -2, 1, 1, -1, -1};
int col[] = {1, -1, 1, -1, 2, -2, 2, -2};
Queue<Point> queue = new LinkedList<>();
queue.offer(source);
visited[source.x][source.y] = true;
int minimumNumSteps = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Point pt = queue.poll();
if (pt.x == destination.x && pt.y == destination.y) {
return minimumNumSteps;
}
for (int j = 0; j < size; j++) {
Point next = new Point(pt.x + row[i], pt.y + col[j]);
if (isPositionValid(pt.x + row[i], pt.y + col[j]) && !visited[i][j]) {
visited[i][j] = true;
queue.offer(next);
}
}
}
minimumNumSteps++;
}
return minimumNumSteps;
}
public static void main(String[] args) {
knightShortestPath position = new knightShortestPath();
position.createChessBoard(8);
Point src = new Point(0,7);
Point dest = new Point(7,0);
System.out.println("The minimum number of steps are: " + position.BFS(src, dest)); //answer is 6
}
}
First thing: I have no idea how you can end up with a negative value. You never decrease minimumNumSteps after initializing it with 0. An overflow possibly? Seems weird to me ..
Besides that, I see two issues:
The two for loops are incorrect. You currently iterate over the queue.size(). What you want to do instead is iterating over all children of the current node.
Poll the current point outside of the for loops.
So:
while(!queue.isEmpty()) {
Point pt = queue.poll();
// check if it's target
// ...
for (int i = 0; i < row.length; i++) {
// ...
for (int j = 0; j < col.length; j++) {
// ...
}
}
}
Another note: When the queue is empty and you have not reached the goal, there is no solution. Currently, you are returning some value that may be interpreted falsely.

print 2 dimentional array center aligned

Hi I am trying to print a two dimensional array that is center aligned but the numbers point to the memory cell if im correct. How would I go about getting them to print the actual numbers, Ive tried creating a display method and that didnt work. Here is my code so far. I am also going to be finding the min, max and avg after I figure this out.
import java.util.Scanner;
public class Print2DArray {
public static void main(String[] args) {
Scanner print2d = new Scanner(System.in);
System.out.println("Please enter the number of rows: ");
int rows = print2d.nextInt();
System.out.println("Please enter the number of columns: ");
int columns = print2d.nextInt();
int array[][] = new int[rows][columns];
System.out.println("\nVictor - 002017044\n");
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
int value = (int) (Math.random() * 10000);
value = (int) (Math.round((value * 100)) / 100.0);
array[x][y] = value;
}
}
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
printArray(array);
}
System.out.println();
}
int max = 0;
int avg = 0;
int min = 0;
System.out.println("\nMaximum: " + max + "\nAverage: " + avg
+ "\nMinimum: " + min);
}
private static void printArray(int [][] array){
int width = 6;
int leftSP = (width - array.length)/2;
int rightSP = width - array.length - leftSP;
for (int i = 0; i < leftSP; i++) {
System.out.print(" ");
}
System.out.print(array);
for (int i =0; i < rightSP; i++) {
System.out.print(" ");
}
}
}
I'm not quite sure what you mean by center aligned in this context. Centering something requires you to know how much space you are allowed to print to and then evenly distributing what you are displaying to both sides of the width/2. For example, by default, in cmd.exe you are limited to 80 characters across, but this can be changed. However, I think the core of this answer is here:
Can I find the console width with Java?
Basically, you can't center it. The best you can hope for is to left align it (or attempt to center it based on some arbitrary pre-determined width).
Based on what you wrote though, and what I see in printArray, your other issue is that you don't know how to print out a value at an index of an array. Before I address that, I must address something you wrote
but the numbers point to the memory cell if im correct
This is actually incorrect. This is the default functionality of the toString method, per the java.lang.Object#toString method:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString%28%29
Your print method should probably look like:
private static void printArray(int [][] array){
if(array == null || array.length < 1 || array[0].length < 1)
throw new IllegalArgumentException("array must be non-null, and must have a size of at least \"new int[1][1]\"");
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array[0].length; j++)
System.out.print("[" + array[i][j] + "]");
System.out.println();
}
}
EDIT:
I saw a comment you made in which you specify what you mean by center aligned. Basically you will want to record the maximum length of any int you are placing into the array, like the following:
//global max value
public static int maxLength = 0;
...
//inside of Print2DArray.main(String [] args)
for (int x = 0; x < array.length; x++) {
for (int y = 0; y < array[x].length; y++) {
value = (int) (Math.round((value * 100)) / 100.0);
int numberOfDigits = String.valueOf(value).length();
if(numberOfDigits > Print2DArray.maxLength)
Print2DArray.maxLength = numberOfDigits;
array[x][y] = value;
}
}
Then you will want to adjust your printArray function's print from
System.out.print("[" + array[i][j] + "]");
to
System.out.printf("[%" + Print2DArray.maxLength + "d]", array[i][j]);
first fix bug
for (int y = 0; y < array[x].length; y++) {
printArray(array[x][y]);//chage printArray(array) to printArray(array[x][y])
}
second modify printlnArray
private static void printArray(int v){
System.out.format("%-8s",String.valueOf(v));
}
center-align
private static int[] widthes = {9,99,999,9999,99999};
private static int numberWidth(int v) {
for (int i = 0; i < widthes.length; i++) {
if(widthes[i] > v) return (i+1);
}
return -1;
}
private static void printArray(int v){
int width = 8;
int numberWidth = numberWidth(v);
int left = (width-numberWidth)/2;
int right = width - numberWidth - left;
for (int i = 0; i < left; i++) {
System.out.print(" ");
}
System.out.print(v);
for (int i = 0; i < right; i++) {
System.out.print(" ");
}
}
more reference
How to align String on console output

Java: Square Matrix Multiplication by means of recursion

I need to write a recursive method that multiplies 2 square matrices (size n-by-n).
It needs to run in theta(N^3) time but it's not Strassen's algorithm.
I've written a method but I am getting a stack overflow.
Matrix A is Matrix B is
1 2 1 0 3 2 3 0
2 3 2 0 2 1 2 0
1 2 1 0 3 2 3 0
The two matrices are both int[][]. here is the code I have written:
public int[][] ncubed(int [][]A, int [][]B){
int w = A.length;
int [][] C = new int[w][w];
if (w==1){
C[0][0] = A[0][0] * B[0][0];
}
else{
int [][]A1 = partition(1,A);
int [][]A2 = partition(2,A);
int [][]A3 = partition(3,A);
int [][]A4 = partition(4,A);
int [][]B1 = partition(1,B);
int [][]B2 = partition(2,B);
int [][]B3 = partition(3,B);
int [][]B4 = partition(4,B);
int [][]C1 = partition(1,C);
int [][]C2 = partition(2,C);
int [][]C3 = partition(3,C);
int [][]C4 = partition(4,C);
C1 = add(ncubed(A1,B1),ncubed(A2,B3));
C2 = add(ncubed(A1,B2),ncubed(A2,B4));
C3 = add(ncubed(A3,B1),ncubed(A4,B3));
C4 = add(ncubed(A3,B2),ncubed(A4,B4));
join(C1, C, 0 , 0);
join(C2, C, w/2 , 0);
join(C3, C, 0, w/2);
join(C4, C, w/2, w/2);
}
return C;
}
public int [][] partition(int quadrant, int[][] array){
int n = array.length;
int[][] Q = new int[array.length][array.length];
if(quadrant>4 || quadrant<1) return null;
switch(quadrant){
case(1):
for(int i = 0; i<(n/2); i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(2):
for(int i = n/2; i<n; i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(3):
for(int i = 0; i<(n/2); i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
case(4):
for(int i = (n/2); i<n; i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
}
return Q;
}
The methods add and join work fine because I've tested them so it's not in that part.
I just can't figure out my problem in the actual ncubed method(the matrix multiply method).
If anyone is able to help me understand something I'm doing incorrectly or show me another way to do this with the specifications stated at the top, that would be awesome. Thanks for any help.
The naive method will give you theta(n^3) time -- have you checked out something simpler?
Failing that, have you looked at these similar questions?

code does not work with arrays (multiple arrays in arraylist)

hi I'm having a little problem with arrays.
here's the code:
int frame_size = 410;
int frame_shift = 320;
ArrayList<double[]> frames = new ArrayList<double[]>();
for (int i = 0; i + frame_size < inbuf.length; i = i + frame_shift) {
double[] frame = new double[frame_size];
System.arraycopy(inbuf, i, frame, 0, frame_size);
frames.add(frame);
}
here I share a large array into several small, and add them to arraylist
I need to get more of ArrayList arrays and pass them to the function, and then accept the answer and assemble arrays processed one:
int[] Cover = new int[frames.size() * nParam];
for (int i = 0; i < frames.size(); i++) {
double[] finMc = Gos.getVek(frames.get(i));
for (int c = 0; c < finMc.length; c++) {
int mc = (int) finMc[c];
for (int m = 0; m < Cover.length; m++) {
Cover[m] = mc;
}
}
}
all this code does not work (
all elements of the array are zero Cover.
Сover[0] = 0
Cover[1] = 0
Cover[2] = 0
...
help solve the problem, please!)
thank you in advance)
Update
int frame_size = 410;
int frame_shift = 320;
ArrayList<double[]> frames = new ArrayList<double[]>();
for (int i = 0; i + frame_size < inbuf.length; i = i + frame_shift) {
double[] frame = new double[frame_size];
System.arraycopy(inbuf, i, frame, 0, frame_size);
frames.add(frame);
}
int[] Cover = new int[frames.size() * nParam];
for (int i = 0; i < frames.size(); i++) {
double[] finMc = Gos.getVek(frames.get(i));
for (int c = 0; c < finMc.length; c++) {
int mc = (int) finMc[c];
Cover[i * frames.size() + c] = (int) finMc[c];
}
}
Code^ not work(
UPDATE 2
double[] inbuf = new double[Size];
inbuf = toDoubleArray(Gos.data);
inbuf[2] = 10;
inbuf[4] = 14;
toDoubleArray
public static double[] toDoubleArray(byte[] byteArray) {
int times = Double.SIZE / Byte.SIZE;
double[] doubles = new double[byteArray.length / times];
for (int i = 0; i < doubles.length; i++) {
doubles[i] = ByteBuffer.wrap(byteArray, i * times, times)
.getDouble();
}
return doubles;
}
Code not work:
int frame_size = 410;
int frame_shift = 320;
ArrayList<double[]> frames = new ArrayList<double[]>();
for (int i = 0; i + frame_size < inbuf.length; i = i + frame_shift) {
double[] frame = new double[frame_size];
System.arraycopy(inbuf, i, frame, 0, frame_size);
frames.add(frame);
}
double[] Cover = new double[frames.size() * nParam];
for (int i = 0; i < frames.size(); i++) {
double[] finMc = Gos.getVek(frames.get(i));
for (int c = 0; c < finMc.length; c++) {
Cover[i * frames.size() + c] = finMc[c];
}
}
A couple of thoughts spring to mind immediately:
1)
for (int m = 0; m < Cover.length; m++) {
Cover[m] = mc;
}
This block starts m over at 0 every time through the loop. This means you're always writing over the same portion of the Cover array. So effectively, it's only the last frame's data that's stored. You probably meant
for(int m = i * frames.size(); m < (i+1)*frames.size(); i++) {
Cover[m] = mc;
}
But this raises a further issue -- you're writing the same value (mc) into the entire area allocated for a whole frame of data. You probably want to merge this loop with the previous loop so that this doesn't happen.
for (int c = 0; c < finMc.length; c++) {
Cover[i * frames.size() + c] = (int)finMc[c];
}
2) int mc = (int) finMc[c];
That line casts the value to an int which truncates the value stored at finMc[c]. If finMc[c] is between 0 and 1 this will yield 0 when the data is copied and casted. This is compounded by the previous issue which ensures that only the last frame's data ever gets copied. This is simply solved by removing the cast and declaring Cover as an array of doubles instead of ints.
So in sum, the code might work a bit better if it's written this way:
double[] Cover = new double[frames.size() * nParam];
for (int i = 0; i < frames.size(); i++) {
double[] finMc = Gos.getVek(frames.get(i));
for (int c = 0; c < finMc.length; c++) {
Cover[i * frames.size() + c] = finMc[c];
}
}

Categories