Filling Array List with random data - java

I have the following variables and ArrayList:
int rowLength, columnLength;
ArrayList<String[]> data = new ArrayList<String[]>();
I need to fill this array list with random data. The data must be string (recommended int that has been converted to String). The main goal is to fill multidimensional array list with random data.
I've tried to do that but I had too many troubles. I'm new in Java, so sometime I need help with basic things as well.

Try using nextInt() from Random. This will create a random int which you can wrap in Integer.toString(int i). Then add it to a String[] then add it to the ArrayList.
For example:
Random r = new Random();
for (int i = 0; i < columnLength; i++) {
String[] s = new String[rowLength];
for (int i = 0; i < s.length; i++) {
s[i] = Integer.toString(r.nextInt());
{
data.add(s);
}

Use nested for loops like below:
int rowLength = 10, columnLength = 5; //Initialize sizes
ArrayList<String[]> data = new ArrayList<String[]>();
for (int row = 0; row<rowLength; row++) {
String[] stringsColumn = new String[columnLength];
for (int col = 0; col <columnLength; col++) {
stringsColumn[col]=Integer.toString(col);
}
data.add(stringsColumn);
}
Output loop
//Note that this output loop will interchange the columns for rows but it works fine for demonstration
for (String[] col:data){
for (String s:col){
System.out.print("\t"+s);
}
System.out.println();
}
Output
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4

You can try something like this:
public String generateRandomString(int len) {
String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
And this:
public Integer generateRandomInteger(int range) {
Random rnd = new Random();
Integer val = rnd.nextInt(range);
return val;
}
Having these 2 functions you can add random data to your ArrayList:
data.add(generateRandomString(10));
data.add(generateRandomInteger(200));

There is many, many, many ways to do this. From what I see from your snippet is that you do expect some static range of this "multi dimenesional" "Array":isch thingy.
int rowLength, columnLength;
would then imply two dimensions, is that the case or are you expecting more dimensions, is the dimension(s) dynamic? If two is the limit I guess String[][] would do, else some more dynamic construct of Map or List should work.

Related

Is it possible to convert a string of integer values to fit into a 3 x 3 array?

I have a string:
1 2 3 4 5 6 7 8 9
and an empty 3 x 3 array:
int[][] grid = new int[3][3];
I want the string to be stored in the grid such that:
{{1,2,3},{4,5,6},{7,8,9}}
Is there any way of doing this without having to import packages except for java.lang.*?
Given your input is an array like int[9]
You may loop through it:
int x = 0, y = 0;
for(int i = 0; i < srcArray.length; i++) {
if (x > dstArray[y].length) {
x = 0;
y++;
}
if (y > dstArray.length) {
break;
}
dstArray[y][x] = srcArray[i];
}
Given your Input is a String, you can srcString.split(„ „) it and parse each item of the result String[] array by Integer.parseInt() to the Input Array described above

2D array in Java with incremental column number that increase in each row

How Can I create a Java 2 Dimensional array whose output will be like:
0
0 0
0 0 0
0 0 0 0
I know how to declare a 2 dimensional array.But don't know how to implement that. Sp need some help here. Thanks
Java is considered "row major", meaning that it does rows first. So if you know the number of rows you can do something like:
int[][] myArr = new int [4][];
for(int i = 0; i < myArr.length; i++){
myArr[i]= new int[i+1];
}
System.out.println(Arrays.deepToString(myArr));
Here no of zeros you want to put in each row is equals to the sequence no of that row eg 1st row has 1 0,2nd has 2 and so on. It can be done as follows:
int[][] arr = new int[5][];
for (int i = 0; i < arr.length; i++)
{
arr[i]=new int[i+1];
for (int j = 0; j <= i; j++)
arr[i][j] = 0; //or whatever you want to store
}

Merging 2 arrays into 1 in Java

Okay so i have this following exercise i need to merge 2 arrays together into 1 array.
The new array has to containt elements of each array e.g: newArray index 0 = array1Element from 0 index, newArray index 1 = array2Element from index 0 and so on..
If one of those arrays has no more elements, continue putting elements from the longer array... so far i have come to this..which is of not right or isn't giving the right solution..can you please give me a proper solution and explain everything that was done in the code..
public static void main(String[] args) {
int[] array1 = {1,1,1,1,1,1};
int[] array2 = {2,2,2,2,2,2,2,2,2,2};
arrayMan(array1,array2);
}
public static int[] arrayMan(int[] firstArray,int[] secondArray) {
int[] newArray = new int[firstArray.length + secondArray.length];
int array1Pos;
int array2Pos;
System.arraycopy(firstArray,0,newArray,0,firstArray.length);
for (int i = 0; i < newArray.length -1 ; i++) {
for (int j = 0; j < secondArray.length ; j++) {
if(newArray[i] == newArray[i+1]) {
array1Pos = newArray[i+1];
array2Pos = secondArray[j];
newArray[i] = array1Pos;
newArray[i + 1] = array2Pos;
}
}
}
for (int i = 0; i < newArray.length ; i++) {
System.out.println(newArray[i]);
}
return newArray;
}
The expected output should be {1,2,1,2,1,2,1,2,1,2,1,2,2,2,2}
I won't write the code for you but I'll try to point you in the right direction.
I think you would find it helpful to first do this on paper, writing out the state after each number is added to the destination array.
For example:
Start:
sourceArray1 = [1,1,1,1,1,1]
sourceArray2 = [2,2,2,2,2,2,2,2,2,2]
targetArray = []
targetIndex = 0 <- where to put the next item
source1Index = 0 <- where to get the next item from sourceArray1
source2Index = 0 <- where to get the next item from sourceArray2
Step (take from sourceArray1)
targetArray = [1]
targetIndex = 1
source1Index = 1
source2Index = 0
Step (take from sourceArray2)
targetArray = [1,2]
targetIndex = 2
source1Index = 1
source2Index = 1
Step (take from sourceArray1)
targetArray = [1,2,1]
targetIndex = 3
source1Index = 2
source2Index = 1
Keep doing this until targetArray is filled. At some point you won't be able to increment source1Index and will have to draw exclusively from sourceArray2.
Once you understand how to do this on paper you'll find the code much easier to write (and you'll see there's no need for System.arrayCopy).

How to convert a one-dimensional array to two-dimensional array in Java

I would like to read a file which is in the form of a matrix, so i tried reading a file put it in String arraylist and then converted to integer array. Now I need a 2D integer array. Can anyone help? Is there any better way to do this.
public class readMat {
private static ArrayList<String> list = new ArrayList<String>();
public static void main (String[] args)
{
// read file and put in arraylist
try
{
Scanner s = new Scanner(new File("link_info_test.txt"));
while (s.hasNext())
{
list.add(s.next());
}
}
catch (Exception e)
{
e.printStackTrace();
}
String[] stockArr = new String[list.size()];
stockArr = list.toArray(stockArr);
int[] sum= Convert(stockArr);
}
// convert string arraylist to integer 1 dimensional array private static int[] Convert(String[] stockArr)
{
if (list != null)
{
int intarray[] = new int[stockArr.length];
for (int i = 0; i < stockArr.length; i++)
{
intarray[i] = Integer.parseInt(stockArr[i]);
}
return intarray;
}
return null;
}
}
Let's say you have temperature data for each day of the week for 10 weeks (that is 70 pieces of data). You want to convert it to a 2d array with rows representing weeks and columns representing days. Here you go:
int temp[70] = {45, 43, 54, ........}
int twoD[30][7]
for(int i=0; i < 70; i++) {
twoD[i / 7][i % 7] = temp[i]
}
That's it.
After the line
int[] sum= Convert(stockArr);
you have your entire file in a 1D array of integers. At this point, you have to determine the width and height of the 2D array.
Let's say you want the 2D array to have 3 rows and 4 columns as an example. Do this:
int[][] int_table = new int[3][4];
for(int j = 0; j < 3; j++)
{
for(int i = 0; i < 4; i++)
{
int_table[j][i] = sum[j * 4 + i];
}
}
The equation I'm using within sum's index is a conversion function that goes from 1D to 2D coordinates. Starting at both j and i being equal to 0, sum[j * 4 + i] = sum[0 * 4 + 0] = sum[0]. The variable i would increment by one at the next step, and we would have sum[0 * 4 + 1] = sum[1]. At the end of the row, i would reset to 0 and j would increment by 1. At that point, we would have sum[1 * 4 + 0] = sum[4], or sum's fifth element. This makes sense if you consider the first four elements as those of the first row. now that we're on a new row, we can fill it with the next four. The "four" that I've been mentioning is the width of the row that we defined earlier while declaring the 2D array.
Keep in mind that the 2D array's width and height can't multiply together to be larger than the total number of integers in the 1D array. You'll get an IndexOutOfBoundsException if you try to read beyond that size.
Assuming that each entry of your String array consists of some integers, separated by some delimiter (comma, dot, hyphen, etc), then you can use the String.split() method. For instance, if your delimiter is a comma, then you would do something like this:
String Integer1;
String Integer2;
String[] TotalString;
TotalString = stockArr[i].Split(",");
Integer1 = TotalString[0];
Integer2 = TotalString[1];
Then just parse the Strings into integers and put them into your array.
If i understood, your question correctly you want to convert 1D array to 2D array ... You can use following method
public static int[][] convertArrayTo2DArray(final int[] _1darray) {
int[][] _2dArray = null;
int size = _1darray.length / 2;
if (_1darray.length % 2 == 0) {
_2dArray = new int[2][size];
} else {
_2dArray = new int[3][size];
}
int index = 0;
outter: for (int i = 0; i < _2dArray.length; i++) {
for (int j = 0; j < _2dArray[i].length; j++) {
if (index == _1darray.length) {
break outter;
}
_2dArray[i][j] = _1darray[index];
index++;
}
}
return _2dArray;
}

Arrays in array, 100 rows, dynamic columns

I'm trying to get this:
arrays[1][0] = 5
arrays[2][0] = 7
arrays[2][1] = 2
arrays[3][0] = 6
arrays[3][1] = 9
arrays[3][2] = 11
So I want arrays[1][] to have one element of random data, arrays[2][] to have 2 elements of random data and so on until I have 100 arrays. So my last array would be arrays[100][] with 100 elements of random data.
This is the code I have now but I get a NullPointerException when arrays[i][j] = generator.nextInt(max) is executed:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
Your
Comparable[][] arrays = new Comparable[100][];
line only creates the outermost array. You need to create the arrays that go in it, e.g. something like this:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
arrays[i] = new Comparable[/* relevant length here*/]; // <====
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
It's unclear to me why you start i at 1 or where the randomness should be (I'm guessing at /* relevant length here */), but hopefully that points you the right way.

Categories