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]);
Related
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;
}
Say I have 10 integer variables, x1 to x10.
I have an integer array, as follows:
Int[] countup = new Int[10];
I would like to specify the elements of the array as follows:
countup[0] = x1;
countup[1] = x1 + x2;
countup[2] = x1 + x2 + x3;
And so on until countup[9] is the sum of x1 to x10.
I could do this manually if it was just 10 elements, but in the actual program I'm writing, there's over 100 elements of the array. Is there any way to set the variables of this array quickly?
A for loop is your best bet, simply put your 10 (or 100) integers into an array of it's own, then loop over your second array referencing indexes of the first array:
int[] xNumbers = { x1, x2, x3, ... x10 };
int[] countup = new int[10];
//Set the 0 index so we don't have to do extra check inside the for loop
//for out-of-bounds exception
countup[0] = xNumbers[0];
for (int i = 1; i < 10; i++) {
//countup[i-1] is why we set index 0 outside of the loop
countup[i] = xNumbers[i] + countup[i-1];
}
since countup[i-1] is the sum of the previous numbers, the previous additions are already done for you. In case you don't know what a for loop is, more information can be found here
Succinctly:
int[] xNums = { /*your x numbers here*/ };
int[] resultArray = new int[xNums.length];
for(int n = 0; n < xNums.length; n++)
{
for(int i = 0; i <= n; i++)
{
resultArray[n]+=xNums[i];
}
}
Hope that makes sense!
I wanted to find a way to do it in Java 8, and the other answer is probably better:
Here's what I have, but it seems redundant and a waste of time, but I'm unfamiliar with Java 8:
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = arr.length;
for (int i = 1; i < length; i++) {
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 0, i + 1)));
arr[i] = Arrays.stream(Arrays.copyOfRange(arr, 0, i + 1)).sum();
}
System.out.println(Arrays.toString(arr));
}
arr[9] is [1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
I believe I also interpreted the question differently. I think he wanted in index[i] the sum of all previous elements.
If my interpretation of your question is correct, to do it without Java 8, using 2 loops:
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = array.length;
for(int i = 1; i < length; i++) {
int sumSoFar = 0;
for(int j = 0; j <= i; j ++) {
sumSoFar += array[j];
}
array[i] = sumSoFar;
}
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);
}
}
private double[] myNumbers = {10, 2, 5, 3, 6, 4};
private double[][] result;
private double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
//System.out.println(result[0] +" "+ result[1]);
return result;
}
I'm trying to sort the one dimensional array in to a matrix, where numbers between 4 - 8 are in one, and all other numbers are in the other.
1) You're not initializing result[][]. You will get a NullPointerException.
Either loop through myNumbers, count the number of values for each category, and create result[][], or push your values into an ArrayList<Double>[2] and use List.toArray() to convert back to an array.
2) result[][] is declared outside your method. While technically valid, it's generally poor form if there is not a specific reason for doing so. Since you're already returning double[][] you might want to declare a double[][] inside your function to work with and return.
I'm not following exactly what you want, but this should allow your code to work.
class OneDimToTwoDim {
public static void main(String[] args) {
// declare myNumbers one dimensional array
double[] myNumbers = {10, 2, 5, 3, 6, 4};
// display two dimensional array
for (int x = 0; x < myNumbers.length; x++) {
System.out.print("[" + myNumbers[x] + "] "); // Display the string.
}
// pass in myNumbers argument for derp parameter, and return a two dimensional array called resultNumbers
double[][] resultNumbers = OneDimToTwoDim.divideNumbers(myNumbers);
System.out.println(); // Display the string.
System.out.println(); // Display the string.
for (int x = 0; x < resultNumbers.length; x++) {
for (int y = 0; y < resultNumbers[x].length; y++) {
System.out.print("[" + resultNumbers[x][y] + "] "); // Display the string.
}
System.out.println(); // Display the string.
}
}
private static double[][] divideNumbers(double[] derp) {
// declare result to be returned
double[][] result = new double[2][derp.length];
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
return result;
}
}
Your result array isn't initialized. Are you getting null pointer exceptions? Is that the problem?
private static double[] myNumbers = {10, 2, 5, 3, 6, 4};
private static double[][] result = new double[2][myNumbers.length];
private static double[][] divideNumbers(double[] derp) {
int j = 0, k = 0;
for (int i=0; i < derp.length; i++) {
if (derp[i] >=4 && derp[i] <=8) {
result[1][j] = derp[i];
j++;
}
else {
result[0][k] = derp[i];
k++;
}
}
result[0] = Arrays.copyOfRange(result[0],0,k);
result[1] = Arrays.copyOfRange(result[1],0,j);
return result;
}
I am trying to remove duplicates from a list by creating a temporary array that stores the indices of where the duplicates are, and then copies off the original array into another temporary array while comparing the indices to the indices I have stored in my first temporary array.
public void removeDuplicates()
{
double tempa [] = new double [items.length];
int counter = 0;
for ( int i = 0; i< numItems ; i++)
{
for(int j = i + 1; j < numItems; j++)
{
if(items[i] ==items[j])
{
tempa[counter] = j;
counter++;
}
}
}
double tempb [] = new double [ items.length];
int counter2 = 0;
int j =0;
for(int i = 0; i < numItems; i++)
{
if(i != tempa[j])
{
tempb[counter2] = items[i];
counter2++;
}
else
{
j++;
}
}
items = tempb;
numItems = counter2;
}
and while the logic seems right, my compiler is giving me an arrayindexoutofbounds error at
tempa[counter] = j;
I don't understand how counter could grow to above the value of items.length, where is the logic flaw?
You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.
double [] input = {1,2,3,3,4,4};
Set<Double> tmp = new LinkedHashSet<Double>();
for (Double each : input) {
tmp.add(each);
}
double [] output = new double[tmp.size()];
int i = 0;
for (Double each : tmp) {
output[i++] = each;
}
System.out.println(Arrays.toString(output));
Done for int arrays, but easily coud be converted to double.
1) If you do not care about initial array elements order:
private static int[] withoutDuplicates(int[] a) {
Arrays.sort(a);
int hi = a.length - 1;
int[] result = new int[a.length];
int j = 0;
for (int i = 0; i < hi; i++) {
if (a[i] == a[i+1]) {
continue;
}
result[j] = a[i];
j++;
}
result[j++] = a[hi];
return Arrays.copyOf(result, j);
}
2) if you care about initial array elements order:
private static int[] withoutDuplicates2(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
int[] result = new int[a.length];
int j = 0;
for (int i = 0 ; i < a.length; i++) {
if (keys.add(a[i])) {
result[j] = a[i];
j++;
}
}
return Arrays.copyOf(result, j);
}
3) If you do not care about initial array elements order:
private static Object[] withoutDuplicates3(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
for (int value : a) {
keys.add(value);
}
return keys.toArray();
}
Imagine this was your input data:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8
Value: 1, 2, 3, 3, 3, 3, 3, 3, 3
Then according to your algorithm, tempa would need to be:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8, ....Exception!!!
Value: 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 5, 6, 7, 8, 6, 7, 8, 7, 8, 8
Why do you have this problem? Because the first set of nested for loops does nothing to prevent you from trying to insert duplicates of the duplicate array indices!
What is the best solution?
Use a Set!
Sets guarantee that there are no duplicate entries in them. If you create a new Set and then add all of your array items to it, the Set will prune the duplicates. Then it is just a matter of going back from the Set to an array.
Alternatively, here is a very C-way of doing the same thing:
//duplicates will be a truth table indicating which indices are duplicates.
//initially all values are set to false
boolean duplicates[] = new boolean[items.length];
for ( int i = 0; i< numItems ; i++) {
if (!duplicates[i]) { //if i is not a known duplicate
for(int j = i + 1; j < numItems; j++) {
if(items[i] ==items[j]) {
duplicates[j] = true; //mark j as a known duplicate
}
}
}
}
I leave it to you to figure out how to finish.
import java.util.HashSet;
import sun.security.util.Length;
public class arrayduplication {
public static void main(String[] args) {
int arr[]={1,5,1,2,5,2,10};
TreeSet< Integer>set=new TreeSet<Integer>();
for(int i=0;i<arr.length;i++){
set.add(Integer.valueOf(arr[i]));
}
System.out.println(set);
}
}
You have already used num_items to bound your loop. Use that variable to set your array size for tempa also.
double tempa [] = new double [num_items];
Instead of doing it in array, you can simply use java.util.Set.
Here an example:
public static void main(String[] args)
{
Double[] values = new Double[]{ 1.0, 2.0, 2.0, 2.0, 3.0, 10.0, 10.0 };
Set<Double> singleValues = new HashSet<Double>();
for (Double value : values)
{
singleValues.add(value);
}
System.out.println("singleValues: "+singleValues);
// now convert it into double array
Double[] dValues = singleValues.toArray(new Double[]{});
}
Here's another alternative without the use of sets, only primitive types:
public static double [] removeDuplicates(double arr[]) {
double [] tempa = new double[arr.length];
int uniqueCount = 0;
for (int i=0;i<arr.length;i++) {
boolean unique = true;
for (int j=0;j<uniqueCount && unique;j++) {
if (arr[i] == tempa[j]) {
unique = false;
}
}
if (unique) {
tempa[uniqueCount++] = arr[i];
}
}
return Arrays.copyOf(tempa, uniqueCount);
}
It does require a temporary array of double objects on the way towards getting your actual result.
You can use a set for removing multiples.