How do I randomly add letter in this 2D array? - java

What code would i need to get a letter to randomly generate inside this code?
public class Array {
public static void main(String[] args) {
// Create 2-dimensional array.
int[][] values = new int[5][5];
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {
// Loop and display sub-arrays.
int[] sub = values[i];
for (int x = 0; x < sub.length; x++) {
System.out.print(sub[x] + " ");
}
System.out.println();
}
}
}

String s = "abcdefghijklmnopqrstuvwxyz";
//loop through rows
for(int x = 0; x< values[0].length;x++)
{
//loops through columns
for(int y = 0; y< values.length;y++)
{
int x = (int)(Math.random()*26); // random int between 0-25
String letter = ""+s.charAt(x); //concatenates
values[x][y] = letter; // declares.
}
}
here is How you would get a letter to randomly generate inside the code.

Related

How do I convert a String into a 2D array

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;

Finding the max of a column of a 2d array and save it into a 1d array

okay so I have a 10x10 2d Array and I found out how to calculate the minimum and maximum value of the column. I want to save the minimum values into on 1d array and the maximum values into a separate 1d array. I found out how to do this, but my 1d arrays just print out a bunch of 0s that equal the value so like 16 0s instead of just the number.
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class F {
public static void main (String args []) throws Exception
{
File a = new File("C:\\users\\James\\desktop\\A10Array.txt");
Scanner scan = new Scanner(a);
int[][] arr = new int [10][10];
for (int i=0;i<10;i++)
for (int j=0;j<10;j++)
arr[i][j] = scan.nextInt();
for (int i=0;i<10;i++)
{
for (int j=0;j<10;j++)
{
System.out.print(arr[i][j] +"\t");
}
System.out.println();
} System.out.println();
for (int i = 0; i < 10; i++) {
int minInCol = arr[0][i];
int maxInCol = arr[0][i];
double sum = 0;
for (int j = 0; j < 10; j++) {
sum+=arr[j][i];
if (minInCol > arr[j][i]) {
minInCol = arr[j][i];
}
if (maxInCol < arr[j][i]) {
maxInCol = arr[j][i];
}
}
int[]min = new int [minInCol];
int[]max = new int [maxInCol];
System.out.print(Arrays.toString(max));
}
scan.close();
}
}
int[]min = new int [minInCol];
int[]max = new int [maxInCol];
System.out.print(Arrays.toString(max));
You just create the arrays with the length is the min and max value, but you don't init the array. So by default the out put for empty array is 0

2D array populating not working

I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.

Making an array with random values

I am trying to fill an array with random int values from 0 to 6. To control my code i am printing out the random values I generate. I try to exclude duplicates in the nested if-statement inside the for-loop, but when I run the code I get my seven values, but some of them are still duplicated. Can someone please help me?
Here is my code:
import java.util.Random;
public class TesterArrayer
{
public static void main(String[] args)
{
int size = 7;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int x =0; x < size; x++)
{
int randomValue = randomNumber.nextInt(6);
if (randomValue != randomArray[x])
{
randomArray[x] = randomValue;
}
}//End for-loop
for (int y = 0; y < size; y++)
{
System.out.println(randomArray[y]);
}
}
}
public static void main(String[] args) {
int size = 7;
boolean add = true;
int counter = 0;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int j = 0; j < size; j++)
{
randomArray[j] = -1;
}
while (counter < size) {
add = true;
int randomValue = randomNumber.nextInt(7);
for (int x = 0; x < size; x++) {
if (randomValue == randomArray[x]) {
add = false;
}
}// End for-loop
if(add)
{
randomArray[counter] = randomValue;
counter++;
}
}
for (int y = 0; y < size; y++) {
System.out.println(randomArray[y]);
}
}
Try something like this. You don't want to add the number unless it's not already in the list. Also for your random you need 7 instead of 6 if you want 0-6.
This code will fill your array with 0-6 not repeating any numbers.
If you only want the numbers 0..length-1 in random order you can do something like this:
int length = 7;
List<Integer> list = new ArrayList<>(length);
for(int i=0; i<length; i++){
list.add(Integer.valueOf(i));
}
//list is now in order, need to randomly shuffle it
Collections.shuffle(list);
//now list is shuffled, convert to array
int array[] = new int[length];
for(int i=0; i<length; i++){
array[i] = list.get(i);
}
Change minLimit, maxLimit and noOfItems to get random Numbers
public class RandomIntegers
{
public static final Random random = new Random();
public static final int maxLimit = 6;
public static final int minLimit = 0;
public static final int noOfItems = 7;
public static void main( String[] args )
{
Set<Integer> uniqueRandomIntegerSet = new HashSet< Integer >();
while(uniqueRandomIntegerSet.size() < noOfItems)
uniqueRandomIntegerSet.add( random.nextInt( maxLimit - minLimit + 1 ) + minLimit );
Integer[] randomUniqueIntegers = uniqueRandomIntegerSet.toArray( new Integer[0] );
}
}
As you should use a more optimal data structure for this approach, as mentioned in the other answer and comments, you can still accomplish this with an array of course. As you have defined the problem you would need to change int randomValue = randomNumber.nextInt(6); to int randomValue = randomNumber.nextInt(7); or else this will loop infinitely as there is no possible way to have no duplicates in a size 7 array with only 6 values.
You can do something like this to modify your code for it to work:
boolean flag = false;
for(int x = 0; x < size; x++)
{
int randomValue = randomNumber.nextInt(7);
for (int i = 0; i < x; i++)
{
if (randomValue == randomArray[i])
{
//randomArray[x] = randomValue;
flag = true;
x--;
}
}
if (!flag)
randomArray[x] = randomValue;
flag = false;
}//End for-loop
This code is simply flagging when it sees a duplicate value in the array already and will skip this value and decrement the x value so that it will create another random value for this spot in the array.
byte[] source = new byte[1024];
Random rand = new Random();
rand.nextBytes(source);

Convert String into 2D int array

I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}

Categories

Resources