Multiplication in Java with recursion - java

I am sorry, I am not sure if the title is correct, if it is not I will correct it once someone tells me what this is called. As you can understand I am new to programming...
I want to accomplish the following:
I have a cycle:
for(int i=0; i < this.matrix.length; i++)
I will have a matrix for example like this:
1, 2, 2
2, 2, 3
0, 1, 2
I want to multiply the diagonal elements 1*2*2
I know how to get those elements each step of the cycle, but how can I used a temp variable, that every step will be multiplied by the new element? or is this not possible?
For example i make a variable:
double temp;
and each cycle step I want the new value to multiply by the old, but keeping the value, not sure if I am explaining this well.
But if we use this matrix i would want something like this:
temp = 1;
next step it
temp = 2;
next step
temp = 4;
I tried doing this myself but in the end would get the wrong results, I understand I am doing the multiplication wrong, because when i changed the 2 2 element of the matrix to 3 instead of 2 my end result would be 9 instead of 6.
I am sorry if this is badly explained...

In your question you are only requesting for the main left-to-right diagonal output, so i'm assuming this is your only goal.
Also, you are not specifying if the matrix will always be square or not; i will assume yes.
Lastly, you are not specifying how this matrix is stored exactly in the variable. I'm assuming we are talking about a bidimensional array.
Here we go:
public static void main (String[] args) throws Exception {
int[][] matrix = new int[3][];
matrix[0] = new int[] {1, 2, 2};
matrix[1] = new int[] {2, 2, 3};
matrix[2] = new int[] {0, 1, 2};
int result = 1;
for (int i=0; i<matrix.length; i++) {
result *= matrix[i][i];
}
System.out.println(result);
}
Edit: If you want also to include right-to-left:
public static void main (String[] args) throws Exception {
int[][] matrix = new int[3][];
matrix[0] = new int[] {1, 2, 2};
matrix[1] = new int[] {2, 2, 3};
matrix[2] = new int[] {0, 1, 2};
int resultL2R = 1;
int resultR2L = 1;
for (int i=0; i<matrix.length; i++) {
resultL2R *= matrix[i][i];
resultR2L *= matrix[i][matrix.length-1-i];
}
System.out.println("left-to-right: " + resultL2R);
System.out.println("right-to-left: " + resultR2L);
}

I guess you would like to have the solution like this:
public static void main (String [] args)
{
int[][] matrix = new int[][] {
{1, 2, 2},
{2, 2, 3},
{0, 1, 2}
};
int result = 1;
for(int i = 0; i < matrix.length; i++){
result = result * matrix[i][i];
}
System.out.println("Result: " + result);
}
Since you're declaring the result variable before you get into for loop, it will preserve the value evaluated inside the loop.

You have to multiply in the loop for the [i][i] element
int[][] array= {
{1,2,2},
{2,2,3},
{0,1,2}
};
int result=1;
for ( int i = 0; i < array.length ; i++) {
result=result*(array[i][i]);
}
System.out.println("Result "+result);

For Diagonal multiplication you can use below mentioned code
public static void main(String[] args) {
//2D Array
int a[][]={{1,2,3},{2,3,4},{3,4,5}};
int multiplier=1;
for(int i=0;i<a.length;i++){
multiplier=multiplier*a[i][i];
}
System.out.println(multiplier);
}

Ok I think this code does what you want for the above matrix:
int temp=1;
for(int r=0; r<3; r++)//traversing through row
{
for(int c=0; c<3; c++)//traversing through column
{
if(r==c)// condition for diagonal
temp*=array[r][c];
}// c close
System.out.println("Multiplication value after row "+(r+1)+" = "+temp);
}// r close

As your question title says , you wanna moltiply with recursion .
The possibility of a function to call itself is known as recursion.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] array= {
{1, 2, 2},
{2, 2, 3},
{0, 1, 2}
};
if(array[0].length==array.length) // check if numbers of columns == rows
System.out.println("Result "+multiD(0, array));
else
System.out.println("No matrix NxN");
}
public static int multiD(int pos, int [][] m) {
if (pos == m.length ) {//get out after the last element (multiply for 1 )
return 1;
} else
if ( m[pos][pos] == 0 ) {// get out if we found a 0 value , so we don't need to go forward
return 0;
} else
return m[pos][pos] * multiD(pos+1,m); //calculate the result
}
Assuming you have a matrix "m" 1000x1000 and the m[0][0] is 0 , you will iterate
1000 times when the result is known at the beginning .
To prevent this you should write something likethis :
(Missing in the other answers)
int result = 1;
for (int i=0; i<matrix.length; i++) {
result *= matrix[i][i];
if(result == 0)
break;
}

Related

Printing elements of array called top10 backwards

I am trying to write a code to print the elements of an array called top10 backwards. How would this be? Anything would be great as I have no clue how to begin.
It would look something like this:
int topTenBackwards[] = new int[] {1,2,3,4,5,6,7,8,9,10};
for(int i = topTenBackwards.length - 1; i >= 0 ; i--) {
System.out.println(topTenBackwards[i]);
}
To reverse an int array, you swap items up until you reach the midpoint, like this:
for(int i = 0; i < validData.length / 2; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
This is taken from another question, here:
How do I reverse an int array in Java?
I think its what you need. You just reverse it, and then iterate and print the first 10, with a function like:
int[] myarray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
for (int element: myarray) {
System.out.println(element);
}
So, endgame should look something like:
int[][] myarray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
for(int i = 0; i < myarray.length / 2; i++)
{
int[] temp = myarray[i];
myarray[i] = myarray[myarray.length - i - 1];
myarray[myarray.length - i - 1] = temp;
}
// array reversed
int x = 0;
for (int[] element: myarray) {
System.out.println(element);
x++;
if (x == 10) {
break;
}
}
// array printed
Using the int[] element: myarray gives me all the items in the array, and the break stops the printing loop when you reach the 10th, if you don't, it still stops when you run out of items (like with just 9)
If your array is multi-dimensional you can just nest the for-loops to iterate the inner levels, or use the Arrays.toString(myarray) function from java.util.Arrays;
Printing arrays taken from: Java Program to Print an Array - Programiz
Hope it helps. (If I made a mistake, I'm happy to be corrected)
I am writing here the code for Printing elements of an array called top10 backward. There are a lot of resource through you find it in a different language like PHP, C++, Python, and all.
public class GFG {
/* Function to reverse arr[] from
start to end*/
static void rvereseArray(int arr[],
int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
/* Utility that prints out an
array on a line */
static void printArray(int arr[],
int size)
{
for (int i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver code
public static void main(String args[]) {
int arr[] = {1, 2, 3, 4, 5, 6};
printArray(arr, 6);
rvereseArray(arr, 0, 5);
System.out.print("Reversed array is \n");
printArray(arr, 6);
}
}
Here I am also suggesting you learn from geeks for geeks, and other programming blogs.

Expanding an array to represent an index as many times as the magnitude of original value

Example: expand(new int[]{3, 2, 5}) -> {0, 0, 0, 1, 1, 2, 2, 2, 2, 2}
I am trying to have it make a a new array to print the index of say 3, 3 times. So 3 would be 0,0,0.
public static int[] expand(int[] input) {
int c = 0;
int[] myArray = new int[sum(input)];
if(input.length == 0){
return new int[0];
}
for(int i = 0; i < input.length; i++) {
int a = input[i];
for(int j = c; j < a; j++) {
c += j;
myArray[j] = i;
}
}
return myArray;
}
Currently this only partially works and I cant seem to figure out how to go through the full array properly. In addition, index zero seems to get skipped.
You were close! It seems that you just need to modify your nested for-loop slightly:
for (int j = 0; j < a; j++) {
myArray[c++] = i;
}
Seeing as you're using c to keep track of the current index, this simply sets the element at index c to i and increments c. You can also remove a and use input[i] in place of it.
Note: It is easier to start j from 0 rather than from c.
Functional method
public class Main {
public static void main(final String... args) {
int[] items = expand(new int[]{3, 2, 5});
System.out.println(Arrays.toString(items));
}
public static int[] expand(int[] input) {
return IntStream.range(0, input.length)
.flatMap(p -> IntStream.generate(() -> p).limit(input[p]))
.toArray();
}
}
This makes a stream of the index, and for each item takes that many of the index, putting all of them into an array

How to shift array elements after removing one?

I need to add a shift function only with loops (it means I can't use any ListArray method et simila, so this is not a copy of any other question with those methods.) to this method which removes a specific integer from a given array, and put the outcome into another array, and then returning it.
public static int[] removeInt(int v, int[] in) {
int length = 0;
length = in.length;
int[] toReturn = new int[length];
for (int b = 0; b < length; b++) {
toReturn[b] = 0;
}
for (int i = 0; i < length; i++) {
if (in[i] != v) {
toReturn[i] = in[i];
}
}
return toReturn;
}
If the input for the array is {1, 2, 3, 4, 5}, and the number to remove is {2}, the output will be {1 0 3 4 5}, but it needs to be {1 3 4 5}, and I can't find a way to shift numbers to the left.
'v' comes from the main, user input. Same for 'in', fullfilled before by the user.
You will have to iterate over the array two times: The first time, you count how often v is contained in in. If count is 0, you can return in, otherwise you would have to create a new array of length in.length - count. Then again you have to iterate over in and add every value that is not v to your Array.
int count = 0;
for(int i: in) {
if (i==v) {
count++;
}
}
int[] result = new int[in.length-count];
int pos=0;
for(int i: in) {
if (i!=v) {
result[pos] = i;
pos++;
}
}
But you could use Collections to make it easier:
public static void main(String[] args) {
int v = 2;
int[] in = new int[]{1, 2, 3, 4, 5};
List<Integer> list = new ArrayList<>();
for(int i: in) {
if (i!=v) {
list.add(i);
}
}
Integer[] result = list.toArray(new Integer[]{});
}
The disadvantage of this, however, would be that you have an Array of Integer and not of int.
Have you considered using a LinkedList? This internally manages the array so you don't need to deal with moving the elements yourself; you can just call remove().

Java filling in an array

How would one go about filling in an array so that, for example, if you had the following array.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 3;
arr[2] = 7;
arr[3] = 2;
arr[4] = -4;
so it would look like
arr = {1, 3, 7, 2, -4};
and you would pass it into your method to get a result of
arr = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4};
so that you essentially are filling in the numeric gaps. I'd like to make this under the assumption that I don't know how long the array passed in is going to be to make it a more universal method.
my current method looks like such right now...
public static void fillArray(int[] numbers){
int length = numbers.length;
for(int i = 0; i < numbers.length - 1; i ++){
if(numbers[i] <= numbers[i + 1]){
length += numbers[i + 1] - numbers[i];
}else if(numbers[i + 1] < numbers[i]){
length += numbers[i + 1] - numbers[i];
}
}
}
I have length to determine the size of my new array. I think it should work but I'm always down for some input and advice.
Looks like homework, providing algorithm only:
Navigate through the elements of the current array.
Get the distance (absolute difference) between the elements in the array.
Summarize the distances.
Create a new array whose length would be the sum of the distances.
Fill the new array using the elements of the first array and filling the gaps.
Return the array.
Like Luiggi Mendoza said, looks like HW, so here's another algorithm:
insert the first element into a list of integers.
loop on the rest of the elements.
for each two array elements X[i-1], X[i], insert the missing integers to the list
after the loop - use guava to turn the List to array.
This works. just check for array size < 2 for safety.
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
Integer[] result = fillArray(arr);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
private static Integer[] fillArray(int[] arr) {
List<Integer> list = new ArrayList<Integer>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
int prevItem = arr[i-1];
int gap = arr[i] - prevItem;
if(gap > 0){
fillGap(list, prevItem, gap, 1);
} else if(gap < 0){
fillGap(list, prevItem, gap, -1);
}
}
return list.toArray(new Integer[0]);
}
private static void fillGap(List<Integer> list, int start, int gap, int delta) {
int next = start+delta;
for (int j = 0; j < Math.abs(gap); j++) {
list.add(next);
next = next+delta;
}
}
Try
import java.util.ArrayList;
import java.util.List;
public class ArrayGap {
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
int high, low;
List<Integer> out = new ArrayList<Integer>();
for(int i=0; i<arr.length - 1; i++){
high = arr[i];
if(arr[i] < arr[i+1]){
for(int j=arr[i]; j<arr[i+1]; j++){
out.add(j);
}
} else {
for(int j=arr[i]; j>=arr[i+1]; j--){
out.add(j);
}
}
}
System.out.println(out);
}
}

How do i Swap Data of an Arrays?

public class Swap_Numbers {
public static void main(String[] args) {
int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers
System.out.println (numTens[3]); // I want my numTens displays numHundred
System.out.println (numHundred[4]); // I want my numHundred displays numTens
}
}
I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables.. hope some can explain me how Thanks!
I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables
You shouldn't, basically. Just take the simple route of a temporary variable:
int[] tmp = numTens;
numTens = numHundred;
numHundred = tmp;
For ints you can actually swap the values within the arrays using arithmetic without temporary variables (which is not the same as swapping which arrays the variables refer to), but it would be very odd to actually find yourself in a situation where you want to do that. Sample code:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5 };
int[] y = { 15, 60, 23, 10, 100 };
swapValues(x, y);
System.out.println("x: " + Arrays.toString(x));
System.out.println("y: " + Arrays.toString(y));
}
static void swapValues(int[] a, int[] b) {
// TODO: Validation
for (int i = 0; i < a.length; i++) {
a[i] += b[i];
b[i] = a[i] - b[i];
a[i] -= b[i];
}
}
}
Even there, I would actually write swapValues using a temporary variable instead, but the above code is just to prove a point...
For that I'm assuming both arrays are of same size. Then you can do :
for (int i = 0; i < numTens.length; i++)
{
numTens[i] = numTens[i] + numHundred[i]; // statement 1
numHundred[i] = numTens[i] - numHundred[i]; // statement 2
numTens[i] = numTens[i] - numHundred[i]; // statement 3
}
Lets take the 2nd elements of both array
Ten[2] = 3;
Hundred[2] = 300;
-------------------------------------
Ten[2] = 303 // after statement 1
Hundred[2] = 3 // after statement 2
Ten[2] = 300 // after statement 3
-------------------------------------
Ten[2] = 300;
Hundred[2] = 3;
Values are swapped without using temporary variable.
If you want to swap the numbers in the array you can do something like this:
void swap(int[] arr1, int[] arr2)
{
//if parameters are as bellow
//arr1 = {1, 2, 3, 4, 5};
//arr2 = {10, 20, 30, 40, 50};
if(arr1.length == arr2.length)
{
for(int i =0; i < arr1.length ; i++)
{
arr1[i] = arr1[i] + arr2[i];
arr2[i] = arr1[i] - arr2[i];
arr1[i] = arr1[i] - arr2[i];
}
}
else
{
throw new IllegalArgumentException;
}
}
int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers
for (int i = 0; i < numTens.length; i++) {
numHundred[i] = numTens[i];
numTens[i] = numTens[i]*100;
}
System.out.println (numTens[3]);
System.out.println (numHundred[4]);

Categories

Resources