I am trying to make a 2D array that i can dynamically update. Lets say i have a 2D array with 10 rows and 3 columns. I want to add an int value to a specific row, thereby adding an extra column to that row (and only that row) so that it alone would have 4 columns. Here's what i have so far.
public class DynamicArray {
private int[][] array;
private int size;
public DynamicArray(int initialSize) {
array = new int[10][initialSize];
size = 0;
}
public int get(int j) {
return array[0][j];
}
public int getSize() {
return size;
}
public void put(int N) {
if (size < array[0].length)
array[0][size] = N;
else // need to create a bigger array
{
int[][] temp = new int[10][2 * size];
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
temp[i][j] = array[i][j];
temp[0][size] = N;
array = temp;
}
size = size + 1;
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(3);
da.put(2);
da.put(1);
da.put(3);
da.put(1);
da.put(4);
da.put(5);
for (int i = 0; i < da.getSize(); i++) {
for (int j = 0; j < 9; j++) {
System.out.print((da.get(i) + "\t"));
}
System.out.println("\n");
}
}
}
The problem is that with this code the program adds the new value to each row instead of only the one specified (in this case row 0).
How could I fix this?
Additionally, how could i make the program do the opposite as well -> remove a value from an individual row and shorten that row?
In case you just want to add the new element to the new array[0].
public void put(int N) {
if (size < array[0].length)
array[0][size] = N;
else { // need to create a bigger array
int[] temp = new int[2 * size]; // Temporary create a new array with double size
// fill the empty array with array[0] existing elements
for (int i = 0; i < size; i++) {
temp[i] = array[0][i];
}
// Change the array[0] to point to the new array
array[0] = temp;
// Add the new element to the new array
array[0][size] = N;
}
size = size + 1;
}
In case you want to put to a specific row number and you should get that as an argument in the put method.
public void put(int N, int rowNum);
You should also change the size element to be a array which will track the size of each row.
int[] size = new int[10];
Accordingly change the size of the row only when that specific row that reached its limit.
Check the code below
public class DynamicArray {
private int[][] array;
private int[] size;
public DynamicArray(int initialSize) {
array = new int[10][initialSize];
size = new int[10];
}
public int get(int rowNum, int colNum) {
return array[rowNum][colNum];
}
public int getSize(int rowNum) {
return size[rowNum];
}
public void put(int N, int rowNum) {
if (size[rowNum] < array[0].length)
array[rowNum][size[rowNum]] = N;
else { // need to create a bigger array
int[] temp = new int[2 * size[rowNum]];
for (int i = 0; i < size[rowNum]; i++) {
temp[i] = array[rowNum][i];
}
array[0] = temp;
array[0][size[rowNum]] = N;
}
size[rowNum] = size[rowNum] + 1;
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(3);
da.put(2, 0);
da.put(1, 0);
da.put(3, 0);
da.put(1, 0);
da.put(4, 0);
da.put(5, 1);
da.put(2, 4);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < da.getSize(i); j++) {
System.out.print((da.get(i, j) + "\t"));
}
System.out.println("\n");
}
}
}
Related
I have two lists of elements and numbers but how can I put them into arrays if I don't know the exact array size? new int[elements.size()][I'm not sure about this size].
For example:
List of elements = [2,5]
List of numbers = [99,100], [1,9,8,10,70]
public static int[][] arrays(List<Integer> numbers, List<Integer> elements){
int count = 0;
int x = 0;
int y = 0;
int[][] list = new int[elements.size()][];
for (Integer e : elements) {
for (int i = count; i < count+e; i++) {
list[x][y] = numbers.get(i);
y++;
}
x++;
y = 0;
count += e;
}
return list;
}
The correct input for your method would be a list of lists, with each list in the parent list potentially having a different length:
public static int[][] arrays(List<List<Integer>> numbers) {
int[][] array = new int[numbers.size()][];
for (int i=0; i < numbers.size(); ++i) {
array[i] = new int[numbers.get(i).size()];
for (int j=0; j < numbers.get(i).size(); ++j) {
array[i][j] = numbers.get(i).get(j);
}
}
return array;
}
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("");
}
}
}
public class Arrays {
private static int[] vals = {1,3,2,5};
public void addBefore(int input, int before){
int[] temp = new int[vals.length*2];
//int[] temp2 = new int [vals.length * 2];
int position = 0;
boolean check = false;
for(int i = 0; i<vals.length; i++){
check = false;
if(vals[i] == (before)){
check = true;
temp[i] = input;
position = i;
break;
}
temp[i] = vals[i];
}
vals[position] = input;
int previous = input;
int current = 0;
for(int i=position;i<vals.length;i++){
current = vals[i];
vals[i] = previous;
previous = current;
}
}
public static void main(String[] args){
Arrays a = new Arrays();
a.addBefore(1, 2);
for(int i = 0; i<vals.length; i++){
System.out.println(vals[i]);
}
}
}
So I am trying to make a addBefore method in Java. It has two parameters input and before. We have to push the input before the given value without replacing anything. After I run this code. The array that is prints out is {1,3,1,1}. I need it to stop replacing and just pushing it forward.
Are you looking for something like this:
public static int[] addBefore(int[] array, int input, int before)
{
//create a new array with 1 more space
int[] newArray = new int[array.length + 1];
//copy in the original array up to the insertion point
for (int x = 0; x < before; x++)
{
newArray[x] = array[x];
}
//element at index 'before' will be pushed one forward; 'before' is now the new one
newArray[before] = input;
//fill in the rest
for (int x = before + 1; x < newArray.length; x++)
{
//need to offset it by one to account for the added int
newArray[x] = array[x - 1];
}
return newArray;
}
public static void main(String[] args)
{
int[] vals = {1,3,2,5};
for(int i = 0; i<vals.length; i++){
System.out.print(vals[i] + ",");
}
System.out.println();
vals = addBefore(vals, 1, 2);
for(int i = 0; i<vals.length; i++){
System.out.print(vals[i] + ",");
}
}
remove vals[position] = input;
public class Arrays {
private static int[] vals = { 1, 3, 2, 5 };
public void addBefore(int input, int before) {
int[] temp = new int[vals.length * 2];
// int[] temp2 = new int [vals.length * 2];
int position = 0;
boolean check = false;
for (int i = 0; i < vals.length; i++) {
check = false;
if (vals[i] == (before)) {
check = true;
temp[i] = input;
position = i;
break;
}
temp[i] = vals[i];
}
// vals[position] = input;
int previous = input;
int current = 0;
for (int i = position; i < vals.length; i++) {
current = vals[i];
vals[i] = previous;
previous = current;
}
}
public static void main(String[] args) {
Arrays a = new Arrays();
a.addBefore(1, 2);
for (int i = 0; i < vals.length; i++) {
System.out.println(vals[i]);
}
}
}
I need to create a method within my class to add two 2d arrays together. One is implemented as a parameter in the method, while the other is a class object. I need to make sure the arrays are the same size, and if so, add them together. I keep getting an Array Out of Bounds error. Whats wrong with my code?
// method to add matrices
public int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
if (userArray[row][column] == matrix[row][column]) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
if (userArray[row][column] == matrix[row][column]) is the problem.
Remember that arrays are zero-indexed so the elements are numbered from zero to row - 1. Trying to access row row is guaranteed to throw an ArrayIndexOutOfBoundsException because the last row is at index row - 1.
I'm not sure why you even have this line. If you change row to row - 1 and column to column - 1 then this line checks if the bottom-right values in the two matrices are the same. If they're not then the matrices will not be summed. Is that what you intended to do?
I think this is what you are trying to do :
public class Test {
static int row =3;
static int column =2;
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}};
public static void main(String[] args) {
add(new int[][] {{4,4},{5,5},{6,6}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
//check arrays are of the same size
if ((userArray.length == matrix.length) && (userArray[0].length == matrix[0].length) ) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (column -1)) {
for(int col = 0; col < column; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
}
return addedMatrices;
}
}
or better:
public class Test {
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}, {4,4}};
public static void main(String[] args) {
add(new int[][] {{5,5},{6,6},{7,7},{8,8}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
//check arrays are of the same size
if ((userArray.length != matrix.length) || (userArray[0].length != matrix[0].length) ) {
System.out.println("Error: arrays are not of the same size");
return null;
}
int rows = userArray.length;
int cols = userArray[0].length;
int addedMatrices[][] = new int[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (cols -1)) {
for(int col = 0; col < cols; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
return addedMatrices;
}
}
to make the print out more elegant you could change the for loop to :
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
}
System.out.println(Arrays.toString(addedMatrices[i]));
}
The line if (userArray[row][column] == matrix[row][column]) { should be replaced by a line to check if the dimensions of both matrices are the same (I guess that is what's intended). Assuming they are both rectangular arrays, and non empty:
public class MatrixAdder {
static public int[][] userArray = {{1,2},{3,4},{5,6}};
static public int[][] add(int[][] matrix) {
final int nb_rows1 = matrix.length; // nb rows in matrix
final int nb_cols1 = matrix[0].length; // nb columns in matrix
final int nb_rows2 = userArray.length; // nb rows in userArray
final int nb_cols2 = userArray[0].length; // nb columns in userArray
// this assumes A[0] exists, and A[0].length == A[1].length == ...
// both for matrix and userArray
int addedMatrices[][] = new int[nb_rows1][nb_rows1];
if ((nb_rows1==nb_rows2) && (nb_cols1==nb_cols2)) {
for (int i = 0; i < nb_rows1; ++i) {
for (int j = 0; j < nb_cols1; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
static public void main(String[] args)
{
int[][] mx1 = {{10,100},{20,200},{40,400}};
int [][] mx2 = add(mx1);
}
}
To be more robust, you could check that the dimensions of all sub-arrays are the same. You could also check if the matrix has zero dimension (otherwise array[0] will give an error).
If the dimensions are not the same, the returned matrix is filled with zeroes.
If this is not exactly what you need, it should give you enough hints.
if (userArray[row][column] == matrix[row][column]) {}
This is strange to me, I honestly don't know what the intentions are (Your just comparing the last element of each array).
I would do
if(addedMatrices.length == userArray.length && addedMatrices.length == matrix.length){}.
This is ugly but I don't know anything about userArray or matrix. I am presuming userArray is global. Also do j++ and i++, it has the same end result but it is more of the norm.
I came across this problem called compress. The objective is to take an array, remove any repeated values and return a new array.
I know this would be very easy with ArrayLists, but I want to do it without them.
So far, I've just written a loop to determine the number of unique values so I can construct a new array of the appropriate length. How can I then get the unique values into the new array?
public static int[] compress(int[] array){
int length = 0;
boolean contains = false;
for (int i = 0; i < array.length; i++){
contains = false;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
contains = true;
j = i;
} else {
contains = false;
}
}
if (!contains){
length++;
}
}
int[] uniqueArray = new int[length];
}
Not Tested but I think this should do the trick.
public static int[] copyArray(int [] num){
int x = 0;
int numDuplicate = 0;
int[] copy = new int[num.length]; // we use this to copy the non duplicates
HashMap<Integer, Integer> count = new HashMap<>(); //hashmap to check duplicates
for(int i = 0; i < num.length; i++){
if(count.containsKey(num[i])){
count.put(num[i], count.get(num[i])+1);
numDuplicate++; // keep track of duplicates
}else{
count.put(num[i], 1); // first occurence
copy[x] = num[i]; // copy unique values, empty values will be at end
x++;
}
}
// return only what is needed
int newSize = num.length - numDuplicate;
int[] copyNum = new int[newSize];
for(int i = 0; i < copyNum.length; i++){
copyNum[i] = copy[i];
}
return copyNum;
}
public static void main(String[] args) {
// sample elements
int[] nums = new int[20];
for(int i = 0; i < nums.length; i++){
nums[i] = (int)(Math.random() * 20);
}
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(copyArray(nums)));
}