So if I have one int[3][3] temp1 and an int[3][3] temp2, both filled up, how would I combine them to make one temp1and2[6][3]? What I'm trying to do is splice a grid array, where x is the array to be spliced and y is the column I want to remove. I tried
public static int[][] splice(int[][] x, int y){
int[][] temp1 = new int[y][x[0].length];
for(int i = 0; i < y; i++){
for(int j = 0; j < x[0].length; j++)
temp1[i][j] = x[i][j];
}
int[][] temp2 = new int[x.length-y][x[0].length];
for(int i = y; i < x.length; i++){
for(int j = 0; j < x[0].length; j++)
temp2[i][j] = x[i][j];
}
int[][] temp1and2 = new int[temp1.length + temp2.length][x[0].length];
System.arraycopy(temp1, 0, temp1and2, 0, temp1.length);
System.arraycopy(temp2, 0, temp1and2, temp1.length, temp2.length);
return temp1and2;
}
but that didn't work. I am getting the error:
java.lang.ArrayIndexOutOfBoundsException: 2 on the temp2[i][j] = x[i][j]; line.
So for example, temp1 and temp2 would both be would be:
1 2 3
4 5 6
7 8 9
and the combined would be:
1 2 3 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
This is how i would do it by hand
//returns a new 2D array with temp1 stacked on top of temp2 or
// null if the arrays aren't the correct dimensions
public int[][] stackArrays(int[][] temp1, int[][] temp2)
{
int [][] temp1n2 = null;
if(temp1.length != 0 && temp1.length == temp2.length
&& temp1[0].length == temp2[0].length)
{
//create the new array to hold both
temp1n2 = new int[temp1.length + temp2.length][temp1[0].length];
for(int i = 0; i < temp1.length; i++)
{
for(int j = 0; j < temp1[i].length; j++)
{
temp1n2[i][j] = temp1[i][j];
temp1n2[i + temp1.length][j] = temp2[i][j];
}
}
}
return temp1n2;
}
The result of stackArrays(allZero2DArray, allOnes2DArray) gives the following 2D array:
000
000
000
111
111
111
Related
(link: https://www.interviewbit.com/problems/array_2d/)
having difficulty in performing a dry run for the following code with performOps being called with
A : [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] .
ArrayList<ArrayList<Integer>> performOps(ArrayList<ArrayList<Integer>> A) {
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>();
for (int i = 0; i < A.size(); i++) {
B.add(new ArrayList<Integer>());
for (int j = 0; j < A.get(i).size(); j++) {
B.get(i).add(0);
}
for (int j = 0; j < A.get(i).size(); j++) {
B.get(i).set(A.get(i).size() - 1 - j, A.get(i).get(j));
}
}
return B;
}
Can anyone please help me in understanding it?
The output will be
4 3 2 1
8 7 6 5
12 11 10 9
You must be trying to initialize A.That is not the case here.The value of A is
1 2 3 4
5 6 7 8
9 10 11 12
and then the output of the further code is asked in the question.Please read the question carefully.Reach out if you need anything else.Cheers
Try substituting the variable values for one or two loops. That will be easier to understand such questions and if possible code it in editor and debug through the code one step at a time.
I have tried for one loop.
ArrayList<ArrayList<Integer>> performOps(ArrayList<ArrayList<Integer>> A) {
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
//A.size() is 3
for (int i = 0; i < 3; i++) {
B.add(new ArrayList<Integer>());
//First Loop i = 0; A.get(0).size() = 4; Four elements in first index of array list
for (int j = 0; j < 4; j++) {
B.get(0).add(0); //Setting all elements to zeros
}
for (int j = 0; j < 4; j++) {
B.get(0).set(4 - 1 - j, A.get(0).get(j));
//For j = 0
// B.get(0).set(3, 1); //A.get(0).get(0) = 1
//For j = 1
B.get(0).set(2, 2); //A.get(0).get(1) = 2
//For j = 2
B.get(0).set(1, 3); // A.get(0).get(2) = 3
//For j = 3
B.get(0).set(0, 4); //A.get(0).get(3) = 4
}
//At the end of above loop B=[[4, 3, 2 ,1]]
}
return B;
}
By the way the output will be two dimensional collection with each inner collection elements in reverse order.
I apologize for my english. So far I got this code that sort an array. The user input 10 numbers and after that, the program makes the sorting. But what I want is that every time the user inputs a number, the program immediately makes the sort. How can I do that?
For example, if I input 5 and then 3, immediately takes the 3 to the first position. And then if I put 2, immediately take it to the first position and sort the others (2,3,5). Then if I put 1, takes it to the first position, sorting the others(1,2,3,5) and so on.
import java.util.Scanner;
public class Nine{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for(int i = 0; i < 10; i++){
System.out.print("Número: ");
num[i] = input.nextInt();
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
System.out.println();
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10 - i - 1; j++){
if(num[j+1] < num[j]){
temp = num[j+1];
num[j+1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for(int i = 0; i < 10; i++){
System.out.print(num[i] + " ");
}
}
}
Now I have this code and it works. It does what I wanted to do. But to me it's a little bit complicated. I'm still a beginner. I understand what it does but is there a better way to do it. An easier way? Thanks
import java.util.Scanner;
public class practice {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] num = new int[10];
int n = 0, l = 0, t = 0;
for(int i = 0; i < num.length; i++){
System.out.print("Número: ");
n = input.nextInt();
l = 0;
while(num[l] < n && l < i){
l = l + 1;
}
t = i;
while(t > l){
num[t] = num[t - 1];
t = t - 1;
}
num[l] = n;
for(int temp : num){
System.out.print(temp + " ");
}
System.out.println();
}
}
}
here you go
public class TestProgram {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int temp = 0;
int[] num = new int[10];
for (int b = 0; b < 10; b++) {
System.out.println("Número: ");
num[b] = input.nextInt();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10 - i - 1; j++) {
if (num[j + 1] < num[j]) {
temp = num[j + 1];
num[j + 1] = num[j];
num[j] = temp;
}
}
}
System.out.println();
for (int k = 0; k < 10; k++) {
System.out.println(num[k] + " ");
}
}
}
}
To do this create a sort method which you can call to sort an array then return a new sorted array. Next every time a user inputs run a for loop which will create an array with the current amount entered. While entering just use i+1. Finally, with the new array call the sort method and the sorted array will be returned and you can do as you wish with the new array.
You make things more difficult for yourself using an array but assuming you want to start with an array of size 10 filled with 0s (so 0 is not a valid input) the basic algorithm is to go through the currently sorted array and if the current value is less than the indexed value move all the values in the sorted array to the right and insert the current value at the current index. As others have already mentioned for larger datasets this is very inefficient but for an array of size 10 it's not a big deal.
int current = input.nextInt();
for (int j = 0; j < sorted.length; j++) {
if (sorted[j] == 0) {
sorted[j] = current;
break;
}
if (current < sorted[j]) {
for (int k = sorted.length - 1; k > j; k--) {
sorted[k] = sorted[k - 1];
}
sorted[j] = current;
break;
}
}
Here's what the output at each iteration would look like for the input 5, 3, 2, 1, 4, 10, 20, 15, 13, 5:
5 0 0 0 0 0 0 0 0 0
3 5 0 0 0 0 0 0 0 0
2 3 5 0 0 0 0 0 0 0
1 2 3 5 0 0 0 0 0 0
1 2 3 4 5 0 0 0 0 0
1 2 3 4 5 10 0 0 0 0
1 2 3 4 5 10 20 0 0 0
1 2 3 4 5 10 15 20 0 0
1 2 3 4 5 10 13 15 20 0
1 2 3 4 5 5 10 13 15 20
I have a function that I need to calculate the sum of elements after the diagonal in the 2D array, but the problem is that the function return the sum of the elements in the diagonal.
What I need is that if I have a matrix like this:
1 2 3
4 5 6
7 8 9
The elements of the diagonal are = 1 5 9
What I need is to calculate the numbers that follow after these diagonal numbers, so it will be like this:
1 2 3
4 5 6
7 8 9
sum = 2+3+6 = 11
I would appreciate it if someone could help me to fix my problem.
this my code:
public int calculate(){
int sum = 0;
for(int row = 0; row <matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
if(row == col){
sum = sum + row+1 ;
}
}
}
System.out.println("the sum is: " + sum );
return sum;
}
public static void main(String[] args) {
int[][] ma = new int[2][2];
Question2 q2 = new Question2(2, 2, ma);
q2.fill();
q2.calculate();
}
the output is:
2 1
2 1
the sum is: 3
You want col to go through all elements, being always bigger than the diagonal.
Therefore try:
int sum = 0;
for(int i = 0 ; i < a.length ; ++i) {
for(int j = i + 1 ; j < a[i].length ; ++j) {
sum += a[i][j];
}
}
I am trying to write a method in Java that receives an array and returns a new array where each number is printed that number of times. Here is an example input and output: "1 2 3 0 4 3" ---> "1 2 2 3 3 3 4 4 4 4 3 3 3". I am stuck and my program will not compile. Does anyone see where I am going wrong?
public static int [] multiplicity(int [] nums) {
for (int i = 0 ; i < nums.length ; i++) {
int size = nums.length + 1;
int newNums[] = new int [size];
for (int j = 0 ; j < nums.length ; j++) {
int value = nums[j];
for (int v = 0 ; v < value ; v++) {
newNums[j + v] = value;
}
}
}
return newNums;
}
Your current code does not size your new array correctly, you could fix your compiler errors easily enough like
int size=nums.length+1;
int newNums [] = new int [size];
for (int i=0; i<nums.length; i++)
{
// int size=nums.length+1;
// int newNums [] = new int [size];
But that clearly won't allow you to populate all of your values. Instead (assuming you can't use a dynamic data-type like a Collection), you'll need to iterate the array once to get the final count of elements and then populate your array. Something like,
public static int[] multiplicity(int[] nums) {
// first pass
int count = 0;
for (int num : nums) {
for (int i = 0; i < num; i++) {
count++;
}
}
int[] ret = new int[count];
count = 0;
// second pass
for (int num : nums) {
for (int i = 0; i < num; i++) {
ret[count++] = num;
}
}
return ret;
}
Then you could test it like,
public static void main(String arg[]) {
int[] in = { 1, 2, 3, 0, 4, 3 };
int[] out = multiplicity(in);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < out.length; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append(out[i]);
}
String expected = "1 2 2 3 3 3 4 4 4 4 3 3 3";
System.out.println(expected.equals(sb.toString()));
}
Output is
true
Once you initialise your int[] newNums, you can't dynamically resize it. Initialising it again will discard the previous array.
Here's another way to solve the problem:
public static int [] multiplicity (int [ ] nums)
{
// create a list to contain the output
List<Integer> newNums = new ArrayList<Integer>();
// for each incoming int
if(nums != null) {
for (final int i : nums)
{
// repeat adding the value
for(int j = 0; j < i; j++) {
newNums.add(i);
}
}
}
// now copy from the List<Integer> to the result int[]
int[] result = new int[newNums.size()];
for(int i=0; i < newNums.size(); i++) {
result[i] = newNums.get(i);
}
// return the result
return result;
}
You can't know the new array size until you explore the whole input array.
So you can
Explore the whole array and compute the lengh, then, re-explore the input array and fill the new. You need only 1 memory allocation (only 1 new int[])
Create a vector and fill it. Then use the .toarray method
Exemple to fill the array (check he had the right size)
int k = 0
for(int i: nums) {
for(int j = 0; j < i; j++) {
newArray[k] = i;
k++;
}
}
I need to write a recursive method that multiplies 2 square matrices (size n-by-n).
It needs to run in theta(N^3) time but it's not Strassen's algorithm.
I've written a method but I am getting a stack overflow.
Matrix A is Matrix B is
1 2 1 0 3 2 3 0
2 3 2 0 2 1 2 0
1 2 1 0 3 2 3 0
The two matrices are both int[][]. here is the code I have written:
public int[][] ncubed(int [][]A, int [][]B){
int w = A.length;
int [][] C = new int[w][w];
if (w==1){
C[0][0] = A[0][0] * B[0][0];
}
else{
int [][]A1 = partition(1,A);
int [][]A2 = partition(2,A);
int [][]A3 = partition(3,A);
int [][]A4 = partition(4,A);
int [][]B1 = partition(1,B);
int [][]B2 = partition(2,B);
int [][]B3 = partition(3,B);
int [][]B4 = partition(4,B);
int [][]C1 = partition(1,C);
int [][]C2 = partition(2,C);
int [][]C3 = partition(3,C);
int [][]C4 = partition(4,C);
C1 = add(ncubed(A1,B1),ncubed(A2,B3));
C2 = add(ncubed(A1,B2),ncubed(A2,B4));
C3 = add(ncubed(A3,B1),ncubed(A4,B3));
C4 = add(ncubed(A3,B2),ncubed(A4,B4));
join(C1, C, 0 , 0);
join(C2, C, w/2 , 0);
join(C3, C, 0, w/2);
join(C4, C, w/2, w/2);
}
return C;
}
public int [][] partition(int quadrant, int[][] array){
int n = array.length;
int[][] Q = new int[array.length][array.length];
if(quadrant>4 || quadrant<1) return null;
switch(quadrant){
case(1):
for(int i = 0; i<(n/2); i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(2):
for(int i = n/2; i<n; i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(3):
for(int i = 0; i<(n/2); i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
case(4):
for(int i = (n/2); i<n; i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
}
return Q;
}
The methods add and join work fine because I've tested them so it's not in that part.
I just can't figure out my problem in the actual ncubed method(the matrix multiply method).
If anyone is able to help me understand something I'm doing incorrectly or show me another way to do this with the specifications stated at the top, that would be awesome. Thanks for any help.
The naive method will give you theta(n^3) time -- have you checked out something simpler?
Failing that, have you looked at these similar questions?