I was planning to generate a random number and export it as JSON using json-simple. I have the following code
public class Main implements JSONAware{
private final int data;
public Main(int data){
this.data = data;
}
public String toJSONString(){
StringBuffer sb = new StringBuffer();
sb.append("[");
sb.append(data);
sb.append("]");
sb.append(",");
return sb.toString();
}
public static void main(String[] args){
JSONArray da = new JSONArray();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
// da.add("%d",grid[row][col]);
da.add(grid[row][col]);
}
// System.out.println();
}
System.out.println(da);
}
This prints as following:
[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7,91,...]
but I was trying to print it as
[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7,91,...],
[68,48,40,44,47,85,8,43,17,78,35,7,77,26,80,34,19,47,17,0,59,5,79,...],
.
.
.
can anyone tell me how would I split the row from column?
As far as I understood your problem, You want 128 rows to be separate JsonArray i.e. 1 row = 1 JsonArray.
For that you could do :
public static void main(String[] args){
JSONArray jArray = new JSONArray();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
JSONArray da = new JSONArray();
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
da.add(grid[row][col]);
}
jArray.add(da);
}
System.out.println(jArray);
}
Just use Json api provided with javaee. And it will be easily accomplished. You will not need to create any jsonToString(...).
import javax.json.Json;
import javax.json.JsonObject;
...
public static void main(String ...args) {
JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
Random generator = new Random();
int[][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (int col = 0; col < 14; col++) {
grid[row][col] = generator.nextInt(100);
arrayBuilder.add(grid[row][col]);
}
jsonBuilder.add(Integer.toString(row), arrayBuilder.build());
}
JsonObject json = jsonBuilder.build();
System.out.println(json);
}
Well if you dont want to use javaee's json api, In your code :
JSONObject obj=new JSONObject();
Random generator = new Random();
int [][] grid;
grid = new int[128][14];
for (int row = 0; row < 128; row++){
JSONArray da = new JSONArray();
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
da.add(grid[row][col]);
}
obj.put(Integer.toString(row), da);
}
System.out.println(obj);
Related
I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;
I have this array here that takes strings values this is my Puzzle Board View,
Right now everything works but the array is hard coded and i need the strings to be generated randomly from 0-4.
I have tried to get a random char and put it is as a string but this didn't work. Any tips would be nice.
Random rand = new Random();
char c = (char)(rand.nextInt(5) + '0');
StringBuilder sb = new StringBuilder();
sb.append(c);
String[] debug_board_state = new String[7];
debug_board_state[0] = "0,3,0,0,3,0,2";
debug_board_state[1] = "1,0,2,0,0,1,2";
debug_board_state[2] = "0,2,0,0,0,0,0";
debug_board_state[3] = "0,0,3,0,3,0,4";
debug_board_state[4] = "2,0,0,0,0,1,0";
debug_board_state[5] = "0,1,0,0,1,0,2";
debug_board_state[6] = "2,0,3,0,0,2,0";
UPDATE.
Thanks to user Answer i was able to get the random matrix, although i ran into another problem, I need do more stuff to the matrix so i don't want to print it out. here is the code
static private final int WIDTH_EASY = 7;
protected void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
};
for (int i = 0; i < WIDTH_EASY; ++i) {
StringTokenizer tokenizer = new StringTokenizer (debug_board_state[i][i], ",");
int column = 0;
while(tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
getCurrentState().board_elements[i][column] = new BoardElement();
getCurrentState().board_elements[i][column].max_connecting_bridges = Integer.parseInt(token);
getCurrentState().board_elements[i][column].row = i;
getCurrentState().board_elements[i][column].col = column;
if (getCurrentState().board_elements[i][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[i][column].is_island = true;
}
++column;
}
}
}
The string Tokenizer works with 1d array but not with 2d, i need something that will do the same thing as StringTokenizer and apply it to the matrix. I am getting the following error
java.lang.NullPointerException: Attempt to read from field Island_and_Bridges.Hashi.BoardElement[][] Island_and_Bridges.Hashi.BoardState$State.board_elements on a null object reference
Although I think int[][] is a better idea, here is the String[][] solution. You can use String.valueOf(rand.nextInt(5)) to generate element in the matrix:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
String[][] matrix = new String[7][7];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Update:
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
Something like this?
Pseudo-code:
String[][] debug_board_state = new String[7][7];
for (int x = 0; x < debug_board_state.size(); x++) {
for (int y = 0; y < debug_board_state[x].size(); y++) {
debug_board_state[x][y] = new_random_character();
}
}
0-4 lies from 49 to 52 on the ASCII scale:
Random rand = new Random();
char c = (char)(rand.nextInt(4)+49);
StringBuilder sb = new StringBuilder();
sb.append(c+'0');
Maybe, you want something like this:
public void initBoard() {
Random random = new Random();
String[][] board = new String[7][7];
for (int i=0; i < board.size(); i++) {
for (int j=0; j < board[].size(); j++) {
board[i][j] = String.valueOf(random.nextInt() % 5);
}
}
}
It will initialize your board with random number of String.
I want to swap Columns and Rows in a 2D array.
My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.
Id like to know how I can save the Variable oldField independent
public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
// a Field
int[][] oldField = pField.clone();
int[][] newField = pField.clone();
for (int i = 0; i < newField.length; i++) {
for (int j = (newField.length - 1); j >= 0; j--) {
newField[i][(newField.length - 1) - j] = oldField[j][i];
}
}
return newField;
}
When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
this code solves your problem:
public class SwapRowsAndColumns {
public static void main(String[] args) {
int[][] someMatrix = new int[2][3];
someMatrix[0][0] = 1;
someMatrix[0][1] = 2;
someMatrix[0][2] = 3;
someMatrix[1][0] = 4;
someMatrix[1][1] = 5;
someMatrix[1][2] = 6;
printMatrix(someMatrix);
int[][] invertedMatrix = swapMatrix(someMatrix);
printMatrix(invertedMatrix);
}
private static int[][] swapMatrix(int[][] pField) {
int originalTotalRows = pField.length;
int originalTotalColumns = pField[0].length;
int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];
for(int i=0; i< originalTotalRows; i++){
for(int j=0; j < originalTotalColumns; j++){
newMatrix[j][i] = pField[i][j];
}
}
return newMatrix;
}
private static void printMatrix(int[][] matrix){
int totalRows = matrix.length;
int totalColumns = matrix[0].length;
for(int i=0; i< totalRows; i++){
for(int j=0; j< totalColumns; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
}
}
This is my codes where I am trying to add elements randomly.
Is there an way to add elements using while loops, for loops or for each loops in Java?
package arrays_into_2d_array;
import java.util.*;
public class Arrays2DArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Random random = new Random();
int [] arr1 = new int[50];
for(int i = 0; i < arr1.length; i++){
arr1[i] = 1+random.nextInt(5);
}
int [] arr2 = new int[100];
for(int i = 0; i < arr2.length; i++){
arr2[i] = 1+random.nextInt(5);
}
int [] arr3 = new int[200];
for(int i = 0; i < arr3.length; i++){
arr3[i] = 1+random.nextInt(5);
}
int [] arr4 = new int[400];
for(int i = 0; i < arr4.length; i++){
arr4[i] = 1+random.nextInt(5);
}
int [] arr5 = new int[800];
for(int i = 0; i < arr5.length; i++){
arr5[i] = 1+random.nextInt(5);
}
int [] arr6 = new int[1600];
for(int i = 0; i < arr6.length; i++){
arr6[i] = 1+random.nextInt(5);
}
int [] arr7 = new int[3200];
for(int i = 0; i < arr7.length; i++){
arr7[i] = 1+random.nextInt(5);
}
int [] arr8 = new int[6400];
for(int i = 0; i < arr8.length; i++){
arr8[i] = 1+random.nextInt(5);
}
int [] arr9 = new int[12800];
for(int i = 0; i < arr9.length; i++){
arr9[i] = 1+random.nextInt(5);
}
int [] arr10 = new int[25600];
for(int i = 0; i < arr10.length; i++){
arr10[i] = 1+random.nextInt(5);
}
int [][] arr2D = {arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10};
for(int i = 0; i < arr2D.length; i++){
System.out.println("Index = "+i+" of 2D array has = "+arr2D[i].length+" number of elements.");
}
}
}
Any help will be appreciated.
You are writing too many codes that are almost same, so you should use loop.
package arrays_into_2d_array;
import java.util.*;
public class Arrays2DArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Random random = new Random();
int [] sizes = {50, 100, 200, 400, 800, 1600, 3200, 6400, 12800, 25600};
int [][] arr2D = new int[sizes.length][];
for(int i = 0; i < arr2D.length; i++){
arr2D[i] = new int[sizes[i]];
for(int j = 0; j < arr2D[i].length; j++){
arr2D[i][j] = 1+random.nextInt(5);
}
}
for(int i = 0; i < arr2D.length; i++){
System.out.println("Index = "+i+" of 2D array has = "+arr2D[i].length+" number of elements.");
}
}
}
Of course. What you are looking for is a method.
You would declare a method which accepts a int[] and a Random instance and performs the loop:
public static void assignRandomValues(int[] array, Random random)
{
for (int i = 0; i < array.length; i++)
{
array[i] = 1 + random.nextInt(5);
}
}
Then you would turn your code into this:
int[] arr1 = new int[50];
assignRandomValues(arr1, random);
...and so on.
Not exactly a loop, but the java 8 version using the stream API is definetly short:
int[][] arr2D = IntStream.range(0, 10).map(i -> 50 << i) // stream of sizes
.mapToObj(size -> IntStream.generate(() -> random.nextInt(5) + 1).limit(size).toArray()) // stream of arrays with given sizes
.toArray(int[][]::new); // combine arrays
I want to get matrix[i][j] to my int[][] gettwodimensionalArray, I try so many way, but when I do the test, my gettwodimensionaArray still not store from matrix[i][j]. Please help me out, thank you.
Here is my code look like.
public int[][] gettwodimensionalArray(String file_name) {
File file = new File(file_name);
ArrayList<int[]> rows = new ArrayList<int[]>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] s = line.split("\\s+");
int[] row = new int[s.length];
for (int i = 0; i < s.length; i++) {
row[i] = Integer.parseInt(s[i]);
}
rows.add(row);
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int numbOfRow = rows.size();
// find number of columns by gettting the lenght of one of the rows row
int keepTrackSizeFirstRow;
for (int i = 0; i < numbOfRow; i++) {
if (i == 0) {
keepTrackSizeFirstRow = rows.get(0).length;
}
// compare current row i's array length, to keetracksizefirstrow
}
int[][] matrix = new int[numbOfRow][rows.get(0).length];
// System.out.println(matrix);
for (int i = 0; i < numbOfRow; i++) {
// i = row
for (int j = 0; j < rows.get(i).length; j++) {
// j = col
matrix[i][j] = rows.get(i)[j];
System.out.print(matrix[i][j]);
}
}
return matrix;
}
Not sure what you are trying to do. If you want each row of the input to fit in the array, you can declare the array with variable sizes, like this:
int[][] matrix = new int[numbOfRow][];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = new int[rows.get(i).length];
}
If instead you want all rows to have the same length, you should find the maximum length of the input like this:
int maxlength = 0;
for (int i = 0; i < rows.size(); i++) {
maxlength = (rows.get(i).length > maxlength) ? rows.get(i).length : maxlength;
}
int[][] matrix = new int[numbOfRow][maxlength];