I want to copy the old array to the new one and I want to add the empty elements to the new array
import java.util.Arrays;
public class testArray2D {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}};
// make a one bigger
int add = 3;
a = Arrays.copyOf(a, a.length + add);
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = 1;
}
}
for (int i[] : a) {
System.out.println(Arrays.toString(i));
}
}
}
The expected output is
1 2 3
1 1 1
1 1 1
1 1 1
Why I can't run this?
You need to initialize the new array elements.
import java.util.Arrays;
public class testArray2D {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}};
// make a one bigger
int add = 3;
a = Arrays.copyOf(a, a.length + add);
for (int i = 1; i < a.length; ++i) {
if(a[i] == null) {
a[i] = new int[3];
}
for (int j = 0; j < a[i].length; ++j) {
a[i][j] = 1;
}
}
for (int i[] : a) {
System.out.println(Arrays.toString(i));
}
}
}
If you want to copy existing array to a new array having size larger than the existing array, I would suggest the following.
int[][] source_arr = {{1, 2, 3}};
int add = 3;
int[][] dest_arr = new int[source_arr[0].length+add][source_arr[0].length];
for (int i = 0; i < source_arr.length; i++) {
System.arraycopy(source_arr[i], 0, dest_arr [i], 0, source_arr[i].length);
}
Related
Java Array List is overriding the data added and put the last items added only.
The output expected is 1.0, 1.0, -1.0,-1.0, -1.0, 1.0,-1.0, -1.0, -1.0,-1.0, -1.0, -1.0
But, the output I get is -1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0,-1.0 .
The code override the list by last array elements which is a=[-1,-1,-1,-1]. That is why all 12 elements of the list value is overridden to -1.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args){
double sum=0; int n=0,y=0,count=0,x=1;
double []a=new double []{1,0,1};
double []b=new double [a.length];
List<double[] >mylist= new ArrayList<>();
double [][]c=new double[][]{{0,0.66,0.66},{0.66,0,0.66},{0,0.66,0}};
mylist.add(0,a);
while(n>=0 && n<4){
for (int i = 0 ; i < 3 ; i++)
for (int j = 0 ; j < a.length; j++)
{
sum=sum+(c[i][j]*a[j]);
if(j==a.length-1)
{
if(sum>0)
sum=1;
else
sum=-1;
b[y]=sum;
y++;
count++;
sum=0;
}
if(count==a.length){
mylist.add(x,b);
x++;
y=0;
count=0;
for(int k=0;k<a.length;k++){
a[k]=b[k];
}
}
}n++;
}
for (int i = 0 ; i < mylist.size(); i++)
for (int j = 0 ; j < a.length ; j++)
{
System.out.print(mylist.get(i)[j]+",");
}
}
}
Arrays in Java are passed by reference to methods, you can check this link for detailed explanation "pass by referece and pass by value" for more about Java parameter passing.
In you code, you just have multiple references of array a and array b. So that is why when their values change all initial values also change. you can use a debugger and you will see it starts changing from the second insertion of b to the ArrayList.
To fix this create a copy of array a at the beginning (whose content will not change). for each new insertion, create a temporary array to hold the values and insert them to your ArrayList.
Below is a fix
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
double sum = 0;
int n = 0, y = 0, count = 0, x = 1;
double[] a = { 1, 0, 1 };
// Create a copy of a to insert at the beginning
double[] acpy = new double[] { 1, 0, 1 };
double[] b = new double[a.length];
List<double[]> mylist = new ArrayList<>();
double[][] c = new double[][] { { 0, 0.66, 0.66 }, { 0.66, 0, 0.66 }, { 0, 0.66, 0 } };
mylist.add(0, acpy);
double[] temp ;
while (n >= 0 && n < 4) {
// this will create a new reference whenever you are about to insert a new element
temp = new double[a.length];
for (int i = 0; i < 3; i++)
for (int j = 0; j < a.length; j++) {
sum = sum + (c[i][j] * a[j]);
if (j == a.length - 1) {
if (sum > 0)
sum = 1;
else
sum = -1;
b[y] = sum;
// copy values of b for insertion to ArrayList
temp[y] = sum;
y++;
count++;
sum = 0;
}
if (count == a.length) {
mylist.add(x, temp);
x++;
y = 0;
count = 0;
for (int k = 0; k < a.length; k++) {
a[k] = b[k];
}
}
}
n++;
}
for (int i = 0; i < mylist.size(); i++)
for (int j = 0; j < a.length; j++) {
System.out.print(mylist.get(i)[j] + ",");
}
}
}
I have found out the duplicate numbers in the array "a" but could not store the duplicate ones in another array "b". Any help much appreciated!
Here is my code:
public static void main(String[] args) {
int[] a = {1,2,3,3,5,6,1,7,7};
int[] b={};
for (int i = 0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i]==(a[j])){
System.out.println(a[j]);
}
}
}
Because the length of result is not know, I would like to use a ArrayList instead of an array :
int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7};
List<Integer> b = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j] && !b.contains(a[j])) {
b.add(a[j]);
System.out.println(a[j]);
}
}
}
System.out.println(b);//result : [1, 3, 7]
You can try finding duplicates in an array using collections framework too:
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class MyClass {
public static void main(String args[]) {
int[] a = {1,2,3,3,5,6,1,7,7};
Set<Integer> set=new HashSet<Integer>();
List<Integer> list=new ArrayList<Integer>();
for(int i:a) {
if(!set.add(i)) {
list.add(i);
}
}
int[] b=new int[list.size()];
for (int i=0;i<list.size();i++) {
b[i] =list.get(i);
}
}
}
Here I have used the fact that sets do not allow duplicate and if set.add returns false, that means that element is already available in the set
We cannot change the size of Array once it is initialized. Here we do not know how many duplicates item will be in the Array.
EDIT -- This might be a better solution, my earlier solution was throwing ArrayIndexOutOfBoundException as indicated by #YCF_L --
import java.util.Arrays;
public class T {
public static void main(String[] args) {
//int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7}; //Set-1, provided by #YCF_L
int[] a = {1,1,3,3,5,6,1,7,7}; //Set-2, provided by OP
int[] b = {};
for (int i=0, k=0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i] == a[j]){
System.out.println(a[j]);
k = k+1;
int[] p = new int[k];
for(int x=0; x < b.length; x++) {
p[x] = b[x];
}
p[k-1] = a[i];
b = p;
}
}
}
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(removeDuplicates(b)));
}
public static int[] removeDuplicates(int[] a) {
boolean[] bArr = new boolean[1000];
int j = 0;
for (int i = 0; i < a.length; i++) {
if (!bArr[a[i]]) {
bArr[a[i]] = true;
j++;
}
}
int[] b = new int[j];
int c = 0;
for (int i = 0; i < bArr.length; i++) {
if (bArr[i]) {
b[c++] = i;
}
}
return b;
}
}
Output with Set-1 :
[1, 3, 7]
[1, 3, 7]
Output with Set-2 :
[1, 1, 1, 3, 7]
[1, 3, 7]
I am having difficulties for writing an algorithm that will create an array of arrays, from a single array of integers.
Say, I have an
int[] intArray = new int[] {1,2,3,4,5};
What I need from it is an array of an arrays that will look like this:
int[][] array = new int[][]{
{-1,2,3,4,5},
{1,-2,3,4,5},
{1,2,-3,4,5},
{1,2,3,-4,5},
{1,2,3,4,-5};
Thank you in advance!!
EDIT:
The following code works for the case if I want to have only one negative value. How about if I would like to have 2,3,4... negative values? Is there a way to make it more dynamic? For example, from {1,2,3,4,5}; to get: {-1,-2,3,4,5}, {-1,2,-3,4,5}, {-1,2,3,-4,5}, {-1,2,3,4,-5}, {1,-2,-3,4,5},{1,-2,3,-4,5}, {1,-2,3,4,-5}.... or for 3 negative values: {-1,-2,-3,4,5}, {-1,-2,3,-4,5}, {-1,-2,3,4,-5}, {1,-2,-3,-4,5}, {1,-2,-3,4,-5}, {1,2,-3,-4,-5}...etc I hope you get my point! Thanks again guys!!
You could try this:
int l = intArray.length;
int[][] newArray = new int[l][l];
for (int i = 0; i < l; i++) {
for (int j = 0; j < l; j++) {
newArray[i][j] = j == i ? intArray[j] * -1 : intArray[j];
}
}
newArray will have the values you are expecting.
how about
public class x
{
public static int[][] convert(int in[])
{
int s = in.length;
int out[][] = new int[s][s];
for (int i = 0; i < s; ++i) { // row loop
for (int j = 0; j < s; ++j) {
if (i == j)
out[i][j] = -in[j];
else
out[i][j] = in[i];
}
}
return out;
}
public static void print(int in[][])
{
for (int i = 0; i < in.length; ++i) {
String sep = "";
for (int j = 0; j < in[i].length; ++j) {
System.out.print(sep + in[i][j]);
sep = ", ";
}
System.out.println("");
}
}
public static void main(String argv[])
{
int in[] = { 1, 2, 3, 4, 5 };
int out[][];
out = convert(in);
print(out);
}
}
int[] intArray = new int[] {1,2,3,4,5};
int algoIntArray[][] = new int[intArray.length][intArray.length];
for(int i = 0; i < intArray.length; i++){
for (int j = 0; j < algoIntArray[i].length; j++){
if (i == j){
algoIntArray[i][j] = -intArray[j];
} else {
algoIntArray[i][j] = intArray[j];
}
}
}
This code will work for you!
I have an array:
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
I'm trying to split it into a two-dimensional array with x amount of chunks, where all of the chunks have an equal length (in my case, 2), then assign each value of the original array to a corresponding index within the array. It would then increment the index of the chunk number and reset the index iterating through the individual arrays hit the length of one.
Problem is, the code I wrote to perform all that isn't outputting anything:
public class Debug
{
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
private static void chunkArray(int chunkSize)
{
int chunkNumIndex = 0;
int chunkIndex = 0;
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++)
{
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
while(chunkNumIndex < numOfChunks)
{
if (chunkIndex == chunkSize)
{
chunkNumIndex++;
chunkIndex = 0;
}
}
}
for(int i = 0; i < chunkNumIndex; i++)
{
for(int j = 0; j < chunkIndex; j++)
{
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
System.out.println();
}
}
public static void main(String args[])
{
chunkArray(2);
}
}
Could anyone be of assistance in debugging my program?
The problem is that you have an unnecessary while(chunkNumIndex < numOfChunks) which makes no sense. The if statement is sufficient to iterate your variables correctly:
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
if (chunkIndex == chunkSize) {
chunkNumIndex++;
chunkIndex = 0;
}
}
Also, remember that the values of chunkNumIndex and chunkIndex are dynamic, so for the last for loops, use twoDimensionalArray.length and twoDimensionalArray[0].length instead:
for(int i = 0; i < twoDimensionalArray.length; i++) {
for(int j = 0; j < twoDimensionalArray[0].length; j++) {
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
}
You're making this unnecessarily hard, there is no need to keep counters for chunkIndex and chunkNumIndex, we can just div and mod i.
int numOfChunks = (array.length / chunkSize) + (array.length % chunkSize == 0 ? 0 : 1);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[i / chunkSize][i % chunkSize] = array[i];
}
Something like this should already do the job.
I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}