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.
Related
The method I have to create should take as parameter an array of integers and return the integer array with its contents sorted in descending order — largest to smallest.
Note - no libraries should be used in your implementation for this method.
I've attempted to use a regular selection sort and using a swap at the end but syntax errors just occurred:
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
If you call the method on the array [3, 6, 8,
3, 5, 7, 1], then the method should return the array [8, 7, 6, 5, 3, 3, 1].
Once you add the implementation of swap to your code (and put it all inside a class), it produces exactly the output you wanted it to. Maybe you thought swap was a java uitl, which it is for Collections, but an array is not a Collection.
So very little has changed in the below:
public class soSelect{ //embed in class, added
public static int[] reverseSelectionSort(int[] arrayToBeSorted) {
// implementation of Task 3 goes here
for(int i = 0; i < arrayToBeSorted.length; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < arrayToBeSorted.length - i; j++){
if(arrayToBeSorted[j] < arrayToBeSorted[minPosition]){
minPosition = j;
}
if(arrayToBeSorted[j] > arrayToBeSorted[maxPosition]){
maxPosition = j;
}
}
swap(arrayToBeSorted,minPosition,maxPosition);
swap(arrayToBeSorted,maxPosition,i);
swap(arrayToBeSorted,minPosition,arrayToBeSorted.length-i-1);
}
return arrayToBeSorted; // change this to return the sorted array
}
public static void swap(int[] a, int i, int j){ //had to implement it
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int[] array2 = {3, 6, 8, 3, 5, 7, 1};
int[] sorted = reverseSelectionSort(array2);
System.out.print("task: [");
for (int i = 0; i < sorted.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(sorted[i]);
}
System.out.println("]");
}
}//added outer brace
I ran it in java doodle and it printed:
task: [8, 7, 6, 5, 3, 3, 1]
I did not test beyond that, but this should at least get you unstuck, or, at best, finished. For sure you could compare with the implementation to which the above comment points you.
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;
}
I am working on a method that will take an integer array and fold it in half x number of times. This method would take an integer array like this {1,2,3,4,5} and output an the array {6,6,3} if it is folded once. Or it could take the input {5,6,7,8} and output {13,13} also folded once.
If the input is folded twice then {5,6,7,8} would turn into {26}.
import java.util.Arrays;
public class Kata
{
public static int[] foldArray(int[] array, int runs)
{
int[] tempArray = array;
for(int j=0; j<runs; j++){
for(int i=0; i<tempArray.length; i++){
tempArray[i] += tempArray[tempArray.length - i];
}
}
int[] outputArray = Arrays.copyOfRange(tempArray, (tempArray.length/2));
return outputArray;
}
}
The problem with your implementation is the way in which you use tempArray:
int[] tempArray = array;
This "aliases" tempArray to the original array, so any modifications to tempArray also happen to the original array. This means that tempArray's length is not going to change from run to run, so any fold after the first one would be invalid.
You need to make tempArray a copy of the initial ⌈n/2⌉ elements on each iteration of the outer loop. To round half-length up, use this expression:
int halfLength = (tempArray.length+1)/2;
int[] tempArray = Arrays.copyOfRange(tempArray, halfLength);
This will deal with arrays of odd length.
At the end of each outer loop iteration replace array with tempArray.
You can also solve your problem recursively:
public static int[] foldArray(int[] array, int runs) {
if (runs == 0) {
return array;
}
int[] tmp;
if (array.length % 2 == 0) {
tmp = new int[array.length / 2];
for (int i = 0; i < array.length / 2; i++) {
tmp[i] = array[i];
}
} else {
tmp = new int[array.length / 2 + 1];
for (int i = 0; i < array.length / 2 + 1; i++) {
tmp[i] = array[i];
}
}
for (int i = 0; i < array.length / 2; i++) {
tmp[i] += array[array.length - i - 1];
}
return foldArray(tmp, runs - 1);
}
public static void main(String[] args) {
System.out.println(Arrays.toString(foldArray(new int[]{1, 2, 3, 4, 5}, 1)));
System.out.println(Arrays.toString(foldArray(new int[]{5, 6, 7, 8}, 1)));
System.out.println(Arrays.toString(foldArray(new int[]{5, 6, 7, 8}, 2)));
}
Note that you need to be careful with the length of the input arrays - whether it's odd or even.
Solution in JavaScript:
function fold(arr, num) {
if (num === 0 || arr.length === 1) {
return arr;
}
let result = [];
while (arr.length > 1) {
result.push(arr.shift() + arr.pop());
}
if(arr.length === 1){
result.push(arr[0]);
}
return fold(result, num - 1);
}
Example:
const arr = [1, 2, 3, 4, 5];
fold(arr, 2); --> [9,6]
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);
}
}