Saving 2d object array indicies to 1d arrays - java

I want to search through a 2d object array and separate the objects based on an object class field, test 1 and test 2 respectively. I then want to write the 2d array's object's indices to two 1d arrays as x,y. I would like to have two pairs of two 1d arrays for each object, so that I can calculate the distance between the test 1 and test 2 object.
My problem/Question
When I run a loop on one of the 1d arrays to print their values to check them, they are filled with a bunch of zeros and they shouldn't be. I included comments in the code to help clarify.
public class gameboard2 {
public static void main(String[] args) {
Character2 objectArray[][] = new Character2[8][8];
int test1X1[] = new int[100];
int test1Y1[] = new int[100];
int test2X2[] = new int[100];
int test2Y2[] = new int[100];
int junkX1Array[] = new int[100];
int junkY1Array[] = new int[100];
for (int row = 0; row < objectArray.length; row++){
for(int col = 0; col < objectArray.length; col++){
if (row <= 1 && col <= 7){
objectArray[row][col] = new Character2();
objectArray[row][col].setType("Test1");
objectArray[row][col].setIdTest1(row,col);
objectArray[row][col].objectFlag = true;
}
else if ((row == 6 || row == 7) && (col <= 7)){
objectArray[row][col]= new Character2();
objectArray[row][col].setType("Test2");
objectArray[row][col].setIdTest2(row,col);
objectArray[row][col].objectFlag = true;
}
else {
objectArray[row][col]= new Character2();
objectArray[row][col].setType("Test3");
}
}
}
for (int x = 0; x < objectArray.length; x++){
for (int y = 0; y < objectArray.length; y++ ){
if (objectArray[x][y].getType().compareTo("Test1") == 0){
test1X1[x] = x;
test1Y1[y] = y;
}
if (objectArray[x][y].getType().compareTo("Test2") == 0){
test2X2[x] = x;
test2Y2[y] = y;
System.out.println(test2X2[x]);
//Arrays are filled with 2d array object indices and printed as they are filled. These values appear correct. However when you print from the array (see below) its filled with a bunch of zeros.
}
else
junkX1Array[x] = x;
junkY1Array[y] = y;
}
}
System.out.print("Now the newly created array will be printed");
// Array is printed. Values differ.
for (int b = 0; b < test2X2.length; b++)
{
System.out.println(test2X2[b]);
}
}
}
//
This is the object class.
public class Character2 {
private String id;
private String type;
boolean objectFlag = false;
public void setType(String AssignType) {
type = AssignType;
}
public String getType(){
return type;
}
public String getId(){
return id;
}
public void setIdTest1(int row, int col){
id = ("Test1" + " row: " + row + " col: " + col);
}
public void setIdTest2(int row, int col){
id = ("Test2" + " row: " + row + " col: " + col);
}
}

I think the problem here is that you are using a same index(x, y) for test1x1, test1Y1, test2X2, test2Y2 arrays. try using different index name for those arrays. because I think they are 4 different arrays.
for example :
int i=0;j=0;k=0;l=0;
for (int x = 0; x < objectArray.length; x++){
for (int y = 0; y < objectArray.length; y++ ){
if (objectArray[x][y].getType().compareTo("test1") == 0){
test2X2[i] = x;
test2Y2[j] = y;
i++;j++;
}
if (objectArray[x][y].getType().compareTo("test2") == 0){
test1X1[k] = x;
test1Y1[l] = y;
k++;l++;
}}}

Ok. Mast.mangesh was correct, he just didn't have the full context. You are indexing into your test arrays with x and y but you aren't adding values to your test arrays at every x and y. They should have their own index that is incremented only when you add something to the test array itself, which brings me to my next suggestion. Why are you using arrays here? Why not use something more robust, like ArrayList? You would have avoided that all along...
public static void test(){
Character2 objectArray[][] = new Character2[8][8];
ArrayList<Integer> x1 = new ArrayList<>();
ArrayList<Integer> y1 = new ArrayList<>();
ArrayList<Integer> x2 = new ArrayList<>();
ArrayList<Integer> y2 = new ArrayList<>();
ArrayList<Integer> junkx = new ArrayList<>();
ArrayList<Integer> junky = new ArrayList<>();
for (int row = 0; row < objectArray.length; row++){
for(int col = 0; col < objectArray.length; col++){
if (row <= 1 && col <= 7){
objectArray[row][col] = new Character2();
objectArray[row][col].setType("Test1");
objectArray[row][col].setIdTest1(row,col);
objectArray[row][col].objectFlag = true;
}
else if ((row == 6 || row == 7) && (col <= 7)){
objectArray[row][col]= new Character2();
objectArray[row][col].setType("Test2");
objectArray[row][col].setIdTest2(row,col);
objectArray[row][col].objectFlag = true;
}
else {
objectArray[row][col]= new Character2();
objectArray[row][col].setType("Test3");
}
}
}
for(Character2[] c2: objectArray){
for(Character2 c: c2){
System.out.print(" " + c.getType() );
}
System.out.println();
}
for (int x = 0; x < objectArray.length; x++){
for (int y = 0; y < objectArray.length; y++ ){
if (objectArray[x][y].getType().compareTo("Test1") == 0){
x1.add(x);
y1.add(y);
}
if (objectArray[x][y].getType().compareTo("Test2") == 0){
x2.add(x);
y2.add(y);
}
else{
junkx.add(x);
junky.add(y);
}
}
}
System.out.print("Now the newly created array will be printed");
for(int i : y2){
System.out.println(i);
}
}

Related

How to print the index number of an element in two dimensional arrays in java?

So this is the code, i displayed a multiple of 5 and then shuffled it.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class TwoDimensionalArrays {
public static void main(String[] args) {
This part is the display of multiple of 5 numbers up to 500.
int [][]table = new int[10][10];
int x = 5;
for(int i = 0; i < table.length; i++){
for(int j=0; j < table[i].length; j++){
table[i][j]= x;
x+=5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
This part is the shuffled arrays using Math.random.
System.out.println("\nShuffled Arrays: \n");
int index1 = 0;
for(int a = 0; a < table.length; a++) {
for(int b = 0; b < table[a].length; b++) {
int il = (int)(Math.random()*table.length);
int jl = (int)(Math.random()*table[a].length);
int temp = table[a][b];
table[a][b] = table[il][jl];
table[il][jl] = temp;
System.out.print(table[a][b] + "\t");
}
System.out.println();
}
}
}
How can i print the index number of an element, for example, 40, from the shuffled arrays?
Please check the below answer. Here I added seperate for loops to print the shuffled array. Because in your current implementation after printing table[a][b] value, that value can be gain replaced by the randomly generated indexes. So Best way is print the shuffled array after completely shuffled it. Used Map<String, Integer> to keep the indexes with values. Please check the below code:
public static void main(String[] args) {
int[][] table = new int[10][10];
int x = 5;
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = x;
x += 5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
System.out.println("\nShuffled Arrays: \n");
Map<String, Integer> map = new HashMap<>(); //Hash map to keep indexes
//Shuffle the array
for (int a = 0; a < table.length; a++) {
for (int b = 0; b < table[a].length; b++) {
int il = (int) (Math.random() * table.length);
int jl = (int) (Math.random() * table[a].length);
int temp = table[a][b];
table[a][b] = table[il][jl];
table[il][jl] = temp;
}
}
//Print shuffled array
for (int a = 0; a < table.length; a++) {
for (int b = 0; b < table[a].length; b++) {
int value = table[a][b];
System.out.print(value + "\t");
//Insert indexes to hash map as key value pairs
String key = a + ", " + b;
if (value == 40 || value == 320 || value == 450) {
map.put(key, value);
}
}
System.out.println();
}
//Printing indexes
System.out.println("\nIndexes: \n");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getValue() + " [" + entry.getKey() + "]");
}
}
So the idea here is to check if value on random index is present in existing array(before shuffled), if yes then add the random entry into a map with value as newly assigned index in shuffled array, so this way once your shuffled array is ready, you have the completed map with all the details of each value and its index in shuffled array
public static void main(String [] args) {
int [][]table = new int[10][10];
Map<Integer,String> map = new HashMap<>();
int x = 5;
for(int i = 0; i < table.length; i++){
for(int j=0; j < table[i].length; j++){
table[i][j]= x;
x+=5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
System.out.println("\nShuffled Arrays: \n");
int index1 = 0;
for(int a = 0; a < table.length; a++) {
for(int b = 0; b < table[a].length; b++) {
int il = (int)(Math.random()*table.length);
int jl = (int)(Math.random()*table[a].length);
int temp = table[a][b];
if(exists(table[il][jl], table)) {
map.put(table[il][jl], "["+a + "][" + b + "]");
}
table[a][b] = table[il][jl];
table[il][jl] = temp;
System.out.print(table[a][b] + "\t");
}
System.out.println();
}
System.out.println(map);
}
public static boolean exists(int value, int[][] tmp) {
List<int[]> list = Arrays.asList(tmp);
for(int[] arr: list){
if(Arrays.stream(arr).anyMatch(i -> i == value)) {
return true;
}
}
return false;
}
Hope this will help..!!

There are no updates among different iterations of the code (Conway's Game of Life)

This program is attempting to recreate Conway's Game of Life.
The rules that this code is trying to apply:
Empty cells with 3 neighbors come to life
Live cells with <2 or >3 neighbors die
All births / deaths occur simultaneously
The issue is the my code outputs no change among the different iterations, even though there is obviously supposed to be.
Any help or ideas with some of the logic being used in the portion that updates the cells would be greatly appreciated.
I have tried printing out different variables and cells that are filled, but everything (in that regard) seems to be working properly.
Apologizes for not being more in-depth, I am honestly unsure what the error with the code is. Thanks for help in advance.
import java.util.*;
import java.io.*;
public class Game_Of_Life {
public static void main(String[] args) throws IOException {
final int runs = 5;
int organisms;
String[][] real = new String[20][20];
String[][] test = new String[20][20];
Scanner reader = new Scanner(new File("life100.txt"));
for(int i = 0; i < real.length; i++) {
for(int g = 0; g < real.length; g++) {
real[i][g] = test[i][g] = " ";
}
}
while(reader.hasNext()) {
real[reader.nextInt()-1][reader.nextInt()-1] = "*";
test[reader.nextInt()-1][reader.nextInt()-1] = "*";
}
reader.close();
for(int j=0; j<runs; j++) {
for(int i = 0; i < real.length; i++) {
for(int g = 0; g < real.length; g++) {
int neigh = neighbors(real, i, g);
if(test[i][g].equals("*")) {
if(neigh<2 || neigh>3) {
real[i][g] = " ";
}
}
else {
if(neigh == 3) {
real[i][g] = "*";
}
}
}
}
for(int i = 0; i < real.length; i++) {
for(int g = 0; g < real.length; g++) {
real[i][g] = test[i][g];
}
}
System.out.println(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n");
for(int i = 0; i < real.length; i++) {
System.out.print((i+1) + " ");
for(int g = 0; g < real.length; g++) {
System.out.print(" " + test[i][g] + " ");
}
System.out.println();
}
}
}
public static boolean able(int row, int col, int N) {
if (row >= 0 && col >= 0 && row < N && col < N) {
return true;
}
else {
return false;
}
}
public static int neighbors(String[][] ray, int row, int col) {
int neighbor=0;
int[] rows = {row-1, row-1, row-1, row, row, row+1, row+1, row+1};
int[] cols = {col-1, col, col+1, col-1, col+1, col-1, col, col+1};
for(int i=0; i<8; i++) {
if(able(rows[i], cols[i], 20) && ray[rows[i]][cols[i]].equals("*")) {
neighbor++;
}
}
return neighbor;
}
}
Actual Results: Cells do not become alive or dead after the five iterations I have it running.
Seems to me like all of your checks should be against the "test" array, so change to:
int neigh = neighbors(test, i, g);
Then, once all checks have been made and changes to "real" are done, copy everything from "real" back to "test".
So change:
real[i][g] = test[i][g];
To:
test[i][g] = real[i][g];

How can I read numbers from a .txt file and put them into a 2-D array?

This is for a school project. I need to read numbers from a .txt file and put them into an array. After they're in an array, I need to pass it into a different class to do the math and compare the numbers. The only problem is, I can't get the code to read the .txt file or make it into an array.
I need to use
if (sq.isMagicSquare())
to pass the array to class Square, but it gives the error:
required: int[][]
found: no arguments
reason: actual and formal lists differ in length
public class MagicSquareTester
{
public static void main() throws IOException
{
Square sq = null;
System.out.println("Enter the name of your data file (magicData.txt):");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.nextLine(); // input data file name from keyboard
Scanner inFile = new Scanner(new File (fileName));
int sqSize = inFile.nextInt(); // read the size
while (sqSize != -1)
{
sq = new Square(sqSize, inFile);
if (sq.isMagicSquare()) //will return true or false
System.out.println("\tWe have a Magic Square!");
else
System.out.println("\tThis is NOT a Magic Square.");
System.out.println(sq);
System.out.println();
sqSize = inFile.nextInt();
}
System.out.println("Of the " + sq.getTotalTested() + " squares tested " + sq.getMagicCount() + " were magic square(s)" );
}
}
public class Square
{
Scanner scan = new Scanner(System.in); //has been imported correctly, btw
int tested = 0, areMagic = 0, sqSize;
boolean magic;
int[][] Square;
public Square(int sqSize, Scanner inFile)
{
Square = new int [sqSize] [sqSize];
}
public void readSquare(Scanner inFile)
{
for(int row = 0; row < sqSize; row++)
for(int col = 0; col < sqSize; col++)
{
Square[row][col] = inFile.nextInt();
tested++;
}
}
public boolean isMagicSquare(int[][] array)
{
Sums testMagic = new Sums();
int rows = testMagic.sumRows(array);
int cols = testMagic.sumCol(array);
int diagonals = testMagic.sumDiagonal(array);
if((rows == cols) && (cols == diagonals) && (diagonals == rows))
{
magic = true;
areMagic++;
}
else
magic = false;
return magic;
}
public int getMagicCount()
{
return areMagic;
}
public int getTotalTested()
{
return tested;
}
}
public class Sums
{
int sum = 0, lastSum = 0, counter1, counter2, counter3;
boolean magic = true;
public int sumRows(int [][] array)
{
for (int row = 0; row < array.length; row++)
{
sum = 0;
for (int col = 0; col < array.length; col++)
{
sum += array[row][col];
System.out.print(sum + " ");
if (lastSum == sum)
{
lastSum = sum;
counter1++;
}
else if (lastSum != sum)
{
magic = false;
System.out.println("This is not a magic square");
row = array.length;
col = array.length;
}
}
}
return counter1;
}
public int sumCol(int [][] array)
{
for (int col = 0; col < array.length; col++)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
sum += array[row][col];
System.out.print(sum + " ");
if (lastSum == sum)
{
lastSum = sum;
counter2++;
}
else if (lastSum != sum)
{
magic = false;
System.out.println("This is not a magic square");
row = array.length;
col = array.length;
}
}
}
return counter2;
}
public int sumDiagonal(int [][] array)
{
int diagonal1 = 0, diagonal2 = 0;
for (int col = 0; col < array.length; col++)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
if(row == col)
{
sum += array[row][col];
System.out.print(sum + " ");
diagonal1 = sum;
}
}
}
for (int col = 0; col < array.length; col--)
{
sum = 0;
for (int row = 0; row < array.length; row++)
{
if((row + col) == array.length - 1)
{
sum += array[row][col];
System.out.print(sum + " ");
diagonal2 = sum;
}
}
}
if(diagonal1 == diagonal2)
{
magic = true;
counter2 = counter3;
}
else
counter3 = 0;
return counter3;
}
}
Also, apologies if my code looks weirdly formatted. I've never posted here before and I'm doing my best.
I suggest you use java.io.file and separate the squaring and parsing operations from the file reading operations.
Possibly like follows:
public class MathSquareTester {
public static void main (String[] args) throws IOException {
List<Integer> squaredNums = new ArrayList<Integer>();
FileInputStream in = new FileInputStream(file_name);
BufferedReader reader = new BufferedReader(new FileReader(in));
String line = reader.readLine();
while (line != null) {
//Assuming each line represents a separate integer
squaredNums.add((int)Math.pow(Integer.parseInt(line)), 2);
line = reader.readLine();
}
int[] numsArray = new int[squaredNums.size];
squaredNums.toArray(numsArray);
//All of your numbers are now stored in numsArray
}
}

Add Matrices in Java

I need to write a short program on how to add two matrices.. The first matrix should look like this:
1 2 3 4 5 6 7 8 9 10
11 12 13.......19 20
21................30
31................40
41................50
etc..
91...............100
But I don't really come to a solution how to increment the first array.. :S
Here is what I got so far:
package uebung05;
public class MatrixAddition
{
public static void main(String[] argv)
{
int firstArray[][] = new int[10][10];
int secondArray[][] = new int[10][10];
int ergArray[][] = new int[10][10];
System.out.println("Matrix 1\n----------------------------");
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
// Increment Array here???
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nMatrix 2\n----------------------------");
// Dekrementieren der zweiten Matrix
for(int row = 0; row < secondArray.length; row++)
{
for(int column = 0; column < secondArray[row].length; column++)
{
// Array mit Werten befüllen
secondArray[row][column] = column + 1;
System.out.print(secondArray[row][column] + " ");
}
System.out.println();
}
System.out.println("\nAddition beider Matrizen\n----------------------------");
// Addition firstArray & secondArray
for(int row = 0; row < ergArray.length; row++)
{
for(int column = 0; column < ergArray[row].length; column++)
{
// Addition
ergArray[row][column] = firstArray[row][column] +
secondArray[row][column];
System.out.print(ergArray[row][column] + " ");
}
System.out.println();
}
}
}
Method to add the first and second matrices together:
public static int[][] matrixAdd(int[][] A, int[][] B)
{
// Check if matrices have contents
if ((A.length < 0) || (A[0].length < 0)) return B;
if ((B.length < 0) || (B[0].length < 0)) return A;
// create new matrix to store added values in
int[][] C = new int[A.length][A[0].length];
for (int i = 0; i < A.length; i++)
{
for (int j = 0; j < A[i].length; j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
But I don't really come to a solution how to increment the first array.
// Inkrementieren der ersten Matrix
for(int row = 0; row < firstArray.length; row++)
{
for(int column = 0; column < firstArray[row].length; column++)
{
firstArray[row][column] = 1+ row*10 + column;
System.out.print(firstArray[row][column] + " ");
}
System.out.println();
}
Sum two matrices in the new one and return:
public int[][] addMatrixes(int[][] src1, int[][] src2){
int[][] dst = new int[src1.length][src1[0].length];
for(int i=0;i<src1.length;i++){
for(int j=0;j<src1[0].length;j++){
dst[i][j] = src1[i][j] + src2[i][j];
}
}
return dst;
}
Not very generic, but you can define your first matrix with only one easy loop :
int dim = 10;
int size = dim*dim;
int firstArray[][] = new int[dim][dim];
int row, column;
for (int index = 0; index < size; index++ ){
row = index/dim;
column = index%dim;
firstArray[row][column]=row*10+column+1;
System.out.print(String.valueOf(firstArray[row][column])+"\t");
if (column == 9){ System.out.println("");}
}

array index out of bounds exception , is this meant to happen?

im attempting to test a program in java and i am getting an array index out of bounds exception that i dont believe should be thrown. have a look at this code and tell me if im missing something? eclipse is telling me the error is being thrown in the location where i have added a comment to show it
class maze{
private int cols; // number of columns in maze
private int rows; // number of rows in maze
private String name;
private weightedGraph<Integer> graph;
private dijkstra solution;
public char[][] mazeStore;
public maze(String filename){
try{
FileReader r = new FileReader(filename);
Scanner s = new Scanner(r);
this.rows = s.nextInt();
this.cols = s.nextInt();
this.name = filename;
this.mazeStore = new char[(2*rows)+1][(2*cols)+1];
String line = s.nextLine();
for(int k = 0; k < ((2*rows)+1); k++){
char[] temp = line.toCharArray();
for(int i = 0; i < temp.length; i++){
mazeStore[k][i] = temp[i];
line = s.nextLine();
}
}
graph = new weightedGraph<Integer>(rows*cols);
for(int y = 1; y < 2*rows; y++){
for(int x = 1; x < 2*cols; x++){
if((x % 2 == 1) && (y % 2 == 0)){
if(mazeStore[x][y] != '-'){ // <<<<<<<<<<<<<<THIS IS WHERE THE ERROR IS THROWN
int label = (x - 1) + (x / 2);
graph.addEdge(label, label+cols, 1);
graph.addEdge(label+cols, label, 1);
}
}
if((x % 2 == 0) && (y % 2 == 1)){
if(mazeStore[x][y] != '|'){
int label = ((x - 1) + (x / 2)) + (y / 2);
graph.addEdge(label, label+1, 1);
graph.addEdge(label+1, label, 1);
}
}
}
}
this.solution = new dijkstra(graph, 0);
}
catch(FileNotFoundException e){
System.err.println("FileNotFoundException: " + e.getMessage());
}
You initialized array
new char[(2*rows)+1][(2*cols)+1]
but iterating it
for(int y = 1; y < 2*rows; y++){//y row iterator
for(int x = 1; x < 2*cols; x++){//x col iterator
so it should be
mazeStore[y][x] not mazeStore[x][y]
you have youre varaibles out of order. youre outter most loop is based on rows but youre using it in the array you initialized to be the size of columns

Categories

Resources