Copy coordinates of one 2D array to another array - java

I have a 2D array freeSpace[][] that represents x, y coordinates. If the space is "not free" then I have it marked as 77, other 1.
I want to put all the elements marked as 77 into it's own array, with those particular array coordinates. I think it should be simple, but I just can't get the syntax correct.
Here is my code:
for (int v = 0; v < info.getScene().getHeight(); v++) {
for (int h = 0; h < info.getScene().getWidth(); h++) {
//System.out.print(freeSpace[h][v] != 77 ? "." : "#");
if (freeSpace[h][v] == 77) {
blockedCoordinates = new int[][]{{h, v}};
}
}
System.out.println();
}
I have already declared the blockedCoordinates[][] array.
Most of my attempts have lead to an empty array.

You are doing some error while copying your data, here is why:
// assuming following definition
int[][] blockedCoordinate = new int[][]{};
for (int v = 0; v < info.getScene().getHeight(); v++) {
for (int h = 0; h < info.getScene().getWidth(); h++) {
//System.out.print(freeSpace[h][v] != 77 ? "." : "#");
if (freeSpace[h][v] == 77) {
// Make a copy
int[][] copyBlockedCoordinate = blockedCoordinates;
// extend the array length by 1
blockedCoordinates = new int[copyBlockedCoordinate.length + 1][2];
for (int i = 0; i < copyBlockedCoordinate.length; i++) {
for (int j = 0; j < copyBlockedCoordinate[i].length; j++) {
blockedCoordiante[i][j] = copyBlockedCoordinate[i][j];
}
}
// add new array at new or last index position in blockedCoordinate array
blockedCoordinate[copyBlockedCoordinate.length] = {h, v};
}
}
// Make sure you write what you want to the console here to debug :)
System.out.println();
}

Related

Printing with two for loops

I'm trying to print out X and Y coordinates from two separate arrays using two for loops. Each point is either decremented or incremented. The grid space is 500x500. I should basically end up with the output displaying a line of asterisks going either up or down. The arrays are populated correctly, and the X and Y coords are decremented or incremented correctly. I can't get it to work....
The populate board method fills the b1 array with the point's x member and the b2 array with the point's y member.
populateBoard(b1,b2,point);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(i == b2[i] && j == b1[j])
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
What is my logic error in the above code? Yet when I use this it works (only for one point obviously).
if(i == b2[0] && j == b1[0])
The logic in your above code is the assumption that in the i/j-th iteration of your double loop you'll be encountering a point whose x/y value happens to be exactly equal to i/j.
The working solution is as follows
private static void populateBoard(int[] xs, int[] ys, int w, int h)
{
Set<Point> points = new HashSet<>();
for(int i=0;i<xs.length;i++)
{
int x = xs[i];
int y = ys[i];
points.add(new Point(x,y));
}
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
Point p = new Point(j,i);
if(points.contains(p))
System.out.print("■");
else
System.out.print(".");
}
System.out.print("\n");
}
}
When I run this code against a trivial example:
int[] xs = {1,4,1,4,1,2,3,4};
int[] ys = {1,1,3,3,4,4,4,4};
populateBoard(xs, ys, 6, 6);
it produces the following (correct) output:
......
.■..■.
......
.■..■.
.■■■■.
......
Try this.
boolean[][] temp = new boolean[matrix.length][matrix.length];
for (int i = 0; i < b1.length; ++i)
temp[b2[i]][b1[i]] = true;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++)
System.out.print(temp[i][j] ? "*" : " ");
System.out.println();
}

how to get specific column in 2D array using java

when searched value exist in array, I choose the column and save them.
for example
1 2 3 4 5 6
A B C D E F
G H I J K L
I want to make a column including x==1||x==4
below column will be result of what i want
1 4
A D
G J
below code is my 2D array code. I make 1D array from csv file and 2D array. when searched value exist, I choose the column and save them.
String str = readCSV(new File("D:/sample_folder/sample1.csv"));
String[] strArr = parse(str); // It comes out in a row in an String array.
int varNumber = 45;
int rowNumber = strArr.length/varNumber;
String[][] Array2D = new String[varNumber][rowNumber];
for(int j=0;j<varNumber;j++)
{
for(int i=0; i<rowNumber;i++)
{
String k = strArr[i*varNumber+j];
Array2D[j][i]= k;
}
} //make 2D array
You can through rows of 2D array and pick the column you want.
for(int j=0;j<rowNumber;j++)
{
// index starts from 0
yourArray[j][0] = array2D[j][0];
yourArray[j][1] = array2D[j][3];
}
Or more dynamically you could write:
int[] columnsYouWant = {0, 3};
for(int j=0;j<rowNumber;j++)
{
for(int c=0;c<columnsYouWant.length;c++)
{
yourArray[j][c] = array2D[j][columnsYouWant[c]];
}
}
If you want to use if (x == 1 || x == 4) :
for(int j=0;j<rowNumber;j++)
{
column = 0;
for(int c=0;c<columnNumber;c++)
{
x = c + 1;
if (x == 1 || x == 4)
yourArray[j][column++] = array2D[j][c];
}
}
I might get it wrong. It also seems you may want to have columns starting with 1 or 4. In that case, if your first row has numbers and rest are alphabetical. You should find the column starting with either 1 or 4.
for(int j=0;j<colNumber;j++)
{
x = array2d[0][j];
if ( x == 1 || x == 4 ) {
// add you j to an array
}
}
In the case you will know which columns you want, and you can use the second piece of code in my answer to create 2D array with columns you want.
Try this simulation, I populate this in your 2DArray:
1 2 3 4 5 6
A B C D E F
G H I J K L
after that, I made a code to print only the columns 1 and 4.
public static void main(String[] args) {
String[][] twoDArray = populateArray();
int x = 0;
for (int i = 0; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[0].length; j++) {
x = j + 1;
if(x == 1 || x == 4) {
System.out.print(twoDArray[i][j]);
}
}
System.out.println();
}
}
public static String[][] populateArray() {
String[][] twoDArray = new String[3][6];
for (int i = 0; i < twoDArray[0].length; i++) {
twoDArray[0][i] = (i + 1) + "";
}
char alphaChar = 'A';
for (int i = 1; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[0].length; j++) {
twoDArray[i][j] = String.valueOf(alphaChar);
alphaChar++;
}
}
return twoDArray;
}
the output of the code is:
14
AD
GJ
if you comment the if(x == 1 || x == 4) { that I used, it will print like this:
123456
ABCDEF
GHIJKL

I need to make permutations with an array using the ArrayList Class. I can't figure out what's wrong

so im taking an ap comp sci class in school, and in the class we're learning about the basics of java. For this assignment we have to make permutations by taking numbers from one one-dimensional array, and putting in another, then deleting that number so it can't be picked again. The numbers in the array can't repeat. We have to use the ArrayList Class too. And I can't figure out what's wrong!
This is the method that creates the permutations:
public static ArrayList<Integer> createPerm()
{
ArrayList<Integer> list = new ArrayList<Integer>(10);
Integer x = 1, remove = 0;
for (Integer i = 0; i < 10; i++)
{
list.add(x);
x++;
}
ArrayList<Integer> perm = new ArrayList<Integer>(10);
for(Integer i = 0; i < 10; i++)
{
Integer r = (int)(Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++)
{
if (list.get(j) == r)
{
remove = j + 1;
list.remove(remove);
perm.add(r);
}
}
}
return perm;
}
I think that you (and I also:)) got a lttle bit confused because you are using Integer-objects as index and as list elements.
That is no problem with the List.get method, because there is only one get method which is expecting an int and Java converts the Integer to int.
The problem is in your usage of list.remove(). There are two methods, one expects an object and one an int.
So if you pass an Integer object, the remove(Object) method is called. But you pass the index, not the r-matching object, so the remove method fails sometimes, because it is random if the element is in your list if remove was called before. And if the method not fails, you have removed the element with the value of your index(+1), not the one who matches r.
for(Integer i = 0; i < 10; i++)
{
Integer r = (int)(Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++)
{
if (list.get(j) == r)
{
remove = j + 1;
list.remove(remove);//the main error is here you found 4
//on index 2 and removes 3 (because of +1)
perm.add(r);
}
}
}
The next thing is, that random can deliver the same number more than once,
so you should not loop only 10 times. Loop until the list is empty.
I have corrected the code as below, the original lines are commented before the correction.
//for (Integer i = 0; i < 10; i++) {
while (!list.isEmpty()) {
Integer r = (int) (Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++) {
//if (list.get(j) == r) {
if (list.get(j).equals(r)) {
//remove = j + 1;
remove = list.get(j);
list.remove(remove);
perm.add(r);
}
}
}
And here I put the code somewhat more clearly, so that it is easier to read
public static ArrayList<Integer> createPerm() {
ArrayList<Integer> list = new ArrayList<Integer>(10);
for (int i = 0; i < 10; i++) {
list.add(i+1);
}
ArrayList<Integer> perm = new ArrayList<Integer>(10);
while (!list.isEmpty()) {
int r = (int) (Math.random() * 10) + 1;
for (int j = 0; j < list.size(); j++) {
if (list.get(j).intValue() == r) {
perm.add(list.remove(j));
}
}
}
return perm;
}

Place String into 2 dimensional array

To put a String into a single array is easy but I want to put a string into a 2d char[][];
I'm stuck here, can some one help me please ... Thank u, ans sorry for my bad English!
String woord = "GPDNATSFASELNIERTPOTSRARIRRCOOFPUAUOGONOTORENOTUAMRHRILGTPOFRSCENOIEKLMETANTRSRUNIAARSETEITNAKAVERNTEJLIBFTNVOTWEEDEKLASC";
char[][] bord = new char[11][11];
char[] letters = woord.toCharArray();
int teller = 0;
//Board into a single array
for (int i = 0; i < woord.length(); i++) {
letters[i] = woord.charAt(i);
teller++;
System.out.print(letters[i]);
if (teller % 11 == 0) {
System.out.println();
}
}
//Board into a 2d Array
for (int r = 0; r < bord.length; r++) {
bord[r][0]=letters[r]; //<=== first 11 letters, next?
System.out.print(bord[r][0]);
for (int c = 0; c < bord[0].length; c++) {
//??
}
}
You can use usual trick applied for multi-dimensional arrays while traversing it. r*11 + a value (according to loops) will give us the next character of string. Below code,
//Board into a 2d Array
for (int r = 0; r < bord.length; r++) {
for(int a = 0; a < 11; a++)
bord[r][a] = letters[r*11 + a];
System.out.println(bord[r]);
}
will give the output:
GPDNATSFASE
LNIERTPOTSR
ARIRRCOOFPU
AUOGONOTORE
NOTUAMRHRIL
GTPOFRSCENO
IEKLMETANTR
SRUNIAARSET
EITNAKAVERN
TEJLIBFTNVO
TWEEDEKLASC

JAVA - How to find duplicate values in rows and columns in a 2D Array?

I have a 2D Array and I would like to find an easier way to manipulate my code so that it will find if there is a duplicate in the column and easier way then what I have below:
for (int i=0; i < array.length; i++) {
for (int j=0; j < array.length; j++) {
for (int k=1; k < array.length; k++){
if (array[j+k][i] == array[j][i]) {
if (array[j][i] != 0) {
return true;
}
}
}
}
}
return false;
EDIT: KINDLY POINTED OUT THE ABOVE ^^ WON'T WORK EITHER AS IT WILL THROW AN OUT OF BOUNDS EXCEPTION
This way has too many loops and I am sure there must be an easier way to find duplicates rather than going through this massive looping process.
This is for a square 2D array, ie. an array with rows = columns.
If so, how can this new way work - and how can I manipulate it to work to find duplicate values in the rows as well.
Thanks for the help.
you can use HashSet to store all already encountered elements. should be something like this:
static boolean noDupes(int[][] array) {
for (int i=0; i < array.length; i++) {
HashSet<Integer> set = new HashSet<Integer>();
for (int j=0; j < array.length; j++) {
if (set.contains(array[j][i])) return false;
set.add(array[j][i]);
}
}
return true;
}
this solution is O(length^2) = O(n) where n is the matrix total size. I think it is ideal in terms of big O, because you need to check all elements.
int[][] array = new int[3][5];
for (int i = 0; i < array.length; i++) // array initialization
for (int j = 0; j < array[i].length; j++ )
array[i][j] = i*j;
Map<Integer, Set<Point>> map = new HashMap<Integer, Set<Point>>();
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
if (map.containsKey(array[i][j]))
map.get(array[i][j]).add(new Point(i, j));
else
{
Set<Point> set = new HashSet<Point>();
set.add(new Point(i, j));
map.put(array[i][j], set);
}
for (Map.Entry<Integer, Set<Point>> entry : map.entrySet())
if (entry.getValue().size() > 1)
{
System.out.println("value = " + entry.getKey());
for (Point p : entry.getValue())
System.out.println("coordinates = " + p);
System.out.println();
}
The output is as expected:
value = 0
coordinates = java.awt.Point[x=0,y=3]
coordinates = java.awt.Point[x=0,y=0]
coordinates = java.awt.Point[x=2,y=0]
coordinates = java.awt.Point[x=0,y=4]
coordinates = java.awt.Point[x=0,y=2]
coordinates = java.awt.Point[x=1,y=0]
coordinates = java.awt.Point[x=0,y=1]
value = 2
coordinates = java.awt.Point[x=1,y=2]
coordinates = java.awt.Point[x=2,y=1]
value = 4
coordinates = java.awt.Point[x=2,y=2]
coordinates = java.awt.Point[x=1,y=4]
Finding the Duplicate Elements in a given Matrix - JAVA
static void findDuplicates(String[][] matrix) {
HashSet<String> uniqInp = new HashSet<String>();
HashSet<String> allDup = new HashSet<String>();
System.out.println("***** DUPLICATE ELEMENTS *****");
for(int row=0;row<matrix.length;row++)
{
for(int col=0;col<matrix[0].length;col++)
{
if(uniqInp.add(matrix[row][col]))
//If not duplicate it will add
continue;
else {
// If Duplicate element found, it will come here
if(allDup.add(matrix[row][col]))
System.out.print(matrix[row][col]+" ");
}
}
}
}

Categories

Resources