Appending Arrays in loop - java

I have a java code where X is a 2D array and a loop to add data to it. The code is as follows:
public static void main(String [] args0
{
int[] len = new int[3];
double[][] X = null;
double[][] vec = null;
for (int i = 0; i < 3; i++)
{
System.out.println("Enter the len" +(i+1)+":");
len[i] = in.nextInt();
if(i == 0)
{
vec = new double [1][len[i] + 1];
X = new double[1][vec[0].length];
for(int k = 0; k < vec[0].length - 1; k++)
{
Xi[0][k] = 0;
}
Xi[0][ve1[0].length-1] = 1;
}
else
{
vec = new double [1][len[i] + 1];
X = new double[1][vec[0].length];
for(int k = 0; k < vec[0].length - 1; k++)
{
X[0][k] = 0;
}
X[0][vec[0].length-1] = 1;
}
}
}
When I print X, I need it have appended the values added when i=0 and when i>0. But it prints only the value of what is supposedly the final iteration. How do I make it print the data of all iterations appended to the end of data added during each iteration? I understand that since I am creating a new double[][] in each iteration, the value of gets overwritten. But how do i fix it?

You have correctly identified that with X = new double[1][vec[0].length]; you are always overriding the result from previous iterations. In order to fix it, you need to move the initialization out of the for loop. Here is an example of how you can do that:
public static void main(String [] args) {
int[] len = new int[3];
double[][] X = new double[3][];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("Enter the len " +(i+1)+":");
len[i] = in.nextInt();
X[i] = new double[len[i]];
for (int j = 0; j < len[i] - 1; j++) {
X[i][j] = 0;
}
X[i][len[i] - 1] = 1;
}
in.close();
}
As you can see, the array X is initialized in the beginning with size 3, since it will always hold 3 one-dimensional arrays in your case. However, you can initialize the size dynamically as well. You don't need the vec variable, because you can always access the length that was just read and stored in len. In fact, you don't need the len array as well, since it stores information that is anyways contained in X:
public static void main(String [] args) {
double[][] X = new double[3][];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
System.out.println("Enter the len " + (i+1) + ":");
X[i] = new double[in.nextInt()];
for (int j = 0; j < X[i].length - 1; j++) {
X[i][j] = 0;
}
X[i][X[i].length - 1] = 1;
}
in.close();
}

Related

Merging 2 Array and Removing Duplicate inputs

im having a problem on how to remove duplicate value on an array,can anyone help me?
I have this code made to just merge 2 arrays and displaying the result but i dont know how to remove the duplicate inputs. (im sorry i just started learning java.)
public static void main(String... args) {
int[] x = new int[3];
int[] y = new int[3];
int[] xy = new int[6];/***new array to hold the integers of arrays x and y ****/
int temp, c = 0;
Scanner myInput = new Scanner(System.in);
/*** input of array x at the same time storing the integers to array xy ***/
System.out.println("enter 3 integers for array x:");
for (int a = 0; a < 3; a++) {
x[a] = myInput.nextInt();
xy[c] = x[a];
c++;
}
/*** input of array y at the same time storing the integers to array xy ***/
System.out.println("enter 3 integers for array y:");
for (int b = 0; b < 3; b++) {
y[b] = myInput.nextInt();
xy[c] = y[b];
c++;
}
/*sorting...*/
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 5 - i; j++) {
if (xy[j] > xy[j + 1]) {
temp = xy[j];
xy[j] = xy[j + 1];
xy[j + 1] = temp;
}
}
}
/*printing of array xy sorted*/
for (int w = 0; w < 6; w++)
System.out.print(xy[w] + " ");
}
Since you have sorted your merged array a simplified solution is to not remove the duplicate but instead filter them out when printing by comparing the current value in the loop to the previous
System.out.print(xy[0] + " ");
for (int w = 1; w < 6; w++) {
if (xy[w] != xy[w - 1]) {
System.out.print(xy[w] + " ");
}
}

Randomly place 1D string array into 2D char array

I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop.
userWords is 1D array of String while puzzleBoard is a 2D array of char.
I've tried
for(int i=0; i<userWords.length;i++) {
puzzleBoard[r++] = userWords[i].toCharArray();
}
but it's not placing it randomly like I want it to
So I tried
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
but it's printing only 3 char instead of the 3 strings of char into the char array.
I've also tried
puzzleBoard[r][c] = userWords[i].toCharArray();
instead of
puzzleBoard[r][c] = userWords[i].charAt(i);
But it display error "cannot convert from char[] to char"
Thank you
Full Code
public static void main(String[] args) {
String[] userWords = new String[3];
Methods.userInput(userWords); //ask user for input
Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
Methods.printPuzzle(puzzleBoard); //print out the puzzle
}//end main
public static void printPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print((i+1));
System.out.println();
}
}//end printPuzzle
public static void fillPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = '*';
}
}
}//end fillPuzzle
public static void userInput(String a[]) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < a.length;i++) {
System.out.println((i+1) + ". enter word:");
a[i] = input.next().toUpperCase();
}
}//end userInput
You can try this one:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
And you should add something that detects whether there is already a word at this position, otherwise you would overwrite it if the random numbers point to a location where is already written a word.
I think you should use 2 for-loops because you want to select first the string and next the characters in the string.
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}

Making a nested for loop into a single for loop

I had an assignment to create an array of random number from 10-100.
Then I need to sout all the numbers not listed in the array.
I did the assignment with a nested for loops, to cross reference the arrays, then I changed all the found numbers in the array into -1. Finally I printed out the elements in the array that were not -1.
My professor told me that is it possible for me to do this assignment with only one for loop and there is no need to do a nested for loop. and make the computer run 10,000 times instead of just 100.
Is that possible? If so how?
Thank you.
package assignment.pkg1;
import java.util.Random;
public class Assignment1 {
static Random ran = new Random();
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
InversingArray(arr);
}
public static void InversingArray(int[] randomArray) {
int[] fullArray = new int[100];
for (int i = 0; i < 100; i++) {
fullArray[i] = i;
}
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
System.out.println("These numbers are not in randomArray: ");
for (int i = 0; i < 100; i++) {
if (fullArray[i] != -1) {
System.out.println(fullArray[i]);
}
}
}
In your code you create an array to hold the possible values. If you think about it, the array index will always be equal to the number stored in the array.
fullArray[i] = i;
This is redundant.
What you are being asked to do is determine which numbers have been used: a boolean test. This means that you should have an array of boolean that is initially false (the default value of booleans in java) and is flipped to true when an equal integer is flipped to true.
Something like
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = (ran.nextInt(90)) + 10;
}
// ba starts with all false values
boolean ba[] == new boolean[90]; // note that the instructor said 10-100
for(int i=0; i<90; i++) {
ba[arr[i]] = true;
// lets assume arr[0] == 45
// ba[arr[0]] is the same as ba[45]
// ba[45] = true; will set that bucket of the boolean array to true
}
System.out.println("These numbers are not in randomArray: ");
for (int k = 0; k < 10; k++) {
System.out.println(k);
}
for (int j = 0; j < 90; j++) {
if (!ba[j]) { // shorthand for ba[j]==false
System.out.println(j+10); // The array starts at a base of 10
}
}
Be aware (probably the point of the exercise) that you are working with an array [0..90] that represents the numbers [10..100].
The nested loop currently looks like this:
for (int i = 0; i < 100; i++) {
for (int j = 1; j < 100; j++) {
if (randomArray[j] == fullArray[i]) {
fullArray[i] = -1;
}
}
}
But we know, that fullArray[i] is always the same as i.
So you can rewrite it to:
for (int j = 1; j < 100; j++) {
int i = randomArray[j];
fullArray[i] = -1;
}
Or even shorter:
for (int j = 1; j < 100; j++) {
fullArray[randomArray[j]] = -1;
}

Out of Bounds Error in 2D Array with Dice Program

So I am creating a program that rolls z die x times with y sides, and I keep getting an out of bounds error at the first line in the first for loop. However I'm not sure why this is, the loop counts from 0 to (z-1). I'm basically in the home stretch of this program and I need the help of the stackoverflow community.
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int x = console.readInt();
System.out.print("Enter the amount of sides: ");
int y = console.readInt();
System.out.print("Enter the amount of die: ");
int z = console.readInt();
int[][] dice = new int[x][z];
int row = 0;
for (int i = 0; i<z; ++i){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x)) {
i = 0;
++row;
}
}
row = 0;
int[] sum = new int[x];
for (int j = 0; j<z; ++j){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x)) {
j = 0;
++row;
}
}
int[] counter = new int[2*y];
int k = 0;
while (k<sum.length){
for (int l = 0;l<((2*y)-1);++l){
if (sum[k]==l) ++counter[l];
if (l==((2*y)-1)) {
++k;
}
}
}
for (int m = 0;m<sum.length;++m) System.out.println(sum[m]+"'s: "+counter[m]+"times, "+((((double)counter[m])/x)*100)+"%");
}
}
first loop:
for (int i = 0; i<z; i++){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x-1)) {
i = -1;
++row;
}
}
second loop:
for (int j = 0; j<z; j++){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x-1)) {
j = -1;
++row;
}
}
Third loop: runs forever. I'm not sure what this is trying to achieve, so I can't fix it for you...
There are x rows but you are using z as the row loop
int[][] dice = new int[x][z]; <-- x is the row count
int row = 0;
for (int i = 0; i < z; ++i){ <--- The outer loop is iterating the rows (x),
Here's how to iterate through a 2D array
int[][] dice = new int[x][z];
for (int i = 0; i < x; i++){
for (int j = 0; j < z; j++){
// do something with dice[i][j]
}
}

Java permutations 2

I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPermutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPermutation(int[] p)
{
int n = p.length-1;
int j = 0;
int m;
int f = 0;
System.out.print("(");
while (f < n) {
m = p[j];
if (m == 0) {
do
f++;
while (p[f] == 0 && f < n);
j = f;
if (f != n)
System.out.print(")(");
}
else {
System.out.print(" " + m);
p[j] = 0;
j = m - 1;
}
}
System.out.print(" )");
}
}
I'm not too crazy about
int n = p.length-1;
followed by
while (f < n) {
So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.
You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);
I don't think swapping each element with a random other element will give a uniform distribution of permutations. Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
remainingValues.add(i);
for(int i = 0; i < n; i++) {
int next = rand.nextInt(remainingValues.size());
result[i] = remainingValues.remove(next);
}
Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time. There are data-structures which could handle this task in n log n time but they are very non-trivial.
This does not answer the problem you have identified.
Rather i think it identifies a mistake with your generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
System.out.println("random nums generated are: ");
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
System.out.print(r + " ");
Run the proc several times.
Do you see what i see?
Jerry.

Categories

Resources