I have a possible logic error while reversing an array [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
I've been trying to reverse an array using a for loop while not creating a new temporary array however the array only reverses halfway.
public void reverse() {
int y = 0;
int[] values = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
for (int x = values.length - 1; x >= 0; x--) {
int placeholder = values[x];
values[y] = placeholder;
y++;
System.out.print(values[y] + " ");
}
}
Right now the method returns the values of the array. However, the value is
"1 2 3 4 5 5 4 3 2 1"
The desired output is,
"1 2 3 4 5 6 7 8 9 10".

You're reassigning some of the previously overwritten values back to the array (so you lose half of the values). Instead, you should loop to half the length of the array and swap corresponding elements.
for (int i = 0, j = values.length - 1; i < j; i++, j--) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
System.out.println(java.util.Arrays.toString(values));

Instead of x >= 0, the loop should be terminated as soon as x and y meet or surpass each other, or swapped values would be swapped one more time and back into their original slots.
Also did you forget to assign values[y] to values[x] within the loop body?
public void reverse(int[] values)
{
if (values.length == 0) return;
int x = values.length - 1;
int y = 0;
while (x > y)
{
// swapping
int temp = values[x];
values[x] = values[y];
values[y] = temp;
// moving ptrs
x--;
y++;
}
}

Yes,you are not supposed to directly assign, you should swap, otherwise the value to the left of the equal sign will be overwritten.Another way is to find a variable to record the value on the left side of the equal sign and assign it to the right side.

Related

Printing Odd and Even Elements of an Array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to write a program that reads a sequence of integers and divide it into two sequences. The values on odd positions will be the first sequence and the values of even positions will be the second sequence. The program prints the elements of the first sequence and then the elements of the second sequence separated by a single space. The first input value specifies the number of elements.
Input: 7 1 2 4 5 6 8 9
Expected Output: 1 4 6 9 2 5 8
My Output: 2 0
package twosequences;
import java.util.Scanner;
public class TwoSequences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] values = new int[n];
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
}
int odd = 0;
int even = 0;
int i = 1;
if (i % 2 == 0) {
even = values[i];
} else {
odd = values[i];
}
i++;
System.out.printf("%d %d%n", odd, even);
}
}
I'm not sure why I'm outputting 2 0. Any suggestions?
You need two different loops to iterate over even and odd elements respectively to obtain the desired output.
for (i = 0 ; i < n ; i += 2) {
even = values[i];
System.out.printf("%d ", even);
}
for (i = 1 ; i < n ; i += 2) {
odd = values[i];
System.out.printf("%d ", odd);
}
Hope this helps.
Print the even-numbered elements in one loop; then use another loop to print the odd-numbered elements.
System.out.print(values[0]); // print by itself to avoid prepending " ".
for (int i = 2; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
for (int i = 1; i < values.length; i += 2) {
System.out.print(" " + values[i]);
}
System.out.println();
you take the second element of an array (2), and only for that one you are checking if it's even or not.
The result goes true for first 'if', and
even = 2;
, the if statement ends and odd stays as declares (0), that' why u got result like that.
If you want output whith more than 2 integers, you need to change
, where n would be all scanned even numbers.
Try to put a counter in first for loop, like
for (int i = 0; i < values.length; i ++) {
values[i] = sc.nextInt();
if(values[i]%2==0) evenCounter++;
}
Now to count odds just count values.length - evenCounter.
Also you do not need to make simple arrays like int[], you can go with
List<Integer> list = new ArrayList<>();
You will be able to add elements in for loop withour knowing how many elements you will be implementing.
Hope some of those helps.

Compare elements in 2d array java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
If I have a two-dimensional array in Java:
1 0 0
0 1 0
1 0 1
And I have another of smaller or equivalent size:
1 0
0 1
How would I find matches where an area of values inside the first array is equal to the second array?
For example, if we split the first array into multiple different small arrays that each have the same dimensions as the second...
This would be the top left corner:
1 0
0 1
Here's the top right corner:
0 0
1 0
And so on...
How can I check if one of the first array's splits is equal to the second array
This is the code I use to define arrays:
public static void main(String argv[])
{
int a[][] = { {1,0,0}, {0,1,0}, {1,0,1} };
int element[][] = {{1,0}, {0,1}};
}
And then I try to use Arrays.deepEquals(Array1, Array2) to compare them.
You can cut the array at x and y by looking at the values in [x, y] to [x + 1, y + 1].
public static int[][] cut(int[][] source, int x, int y)
{
return new int[][]{
new int[]{ source[x][y], source[x + 1][y] },
new int[]{ source[x][y + 1], source[x + 1][y + 1] }
};
}
Note this function assumes your array is square. Then iterate over the large array, cutting and comparing. Since our cut function takes a 2x2 array, we stop before x and y get to the edge of the large array (Hence the x < large.length - 1).
public static boolean test(int[][] large, int[][] small)
{
for (int x = 0; x < large.length - 1; x++)
for (int y = 0; y < large[0].length - 1; y++)
{
int[][] part = cut(large, x, y);
if (Arrays.deepEquals(part, small))
return true;
}
}

Find what number it used to be before element reset

Given an array with any size, in my case the array size is 5.
This array contains ALL numbers from 1 to 5 (must contain all of them)
[1 | 2 | 3 | 4 | 5]
0 1 2 3 4
And now, one element was reset and was set to 0, and the mission is to find what number it used to be before it turned 0.
So I have this simple solution:
Explained: First, loop from 1 to 5, create an inner loop to check if the i from the first loop exists in the whole array, if it doesn't exist, that means that it is the value it used to be before 0, because the array contained all numbers from 1 to 5 or 1 to 100 (doesn't matter) and there's on'y one rested element.
Code:
int[] numbers = new int[]{1, 2, 3, 4, 5};
numbers[1] = 0;
int lost = -1;
loop:
for (int i = 1; i <= numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (numbers[j] == i) {
continue loop;
}
}
lost = i;
break loop;
}
System.out.println(lost);
That solution is not bad, but I think there's a better solution, something more stable.
I have thought about it mathematically, in our example:
1 + x + 3 + 4 + 5 = 15
x = 2
Mathematically, it's really easy. Is there a way this can be done in a programming language as easy as it is mathematically?
Any better algorithms you can think of to solve this question?
This works for ONE element being reset. Just subtract each remaining element from the sum and what ever is left over would have been the previous number the element was before it was reset.
public static void main(String[] args) throws Exception {
int sum = 15;
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
numbers[4] = 0;
for (int i = 0; i < numbers.length; i++) {
sum -= numbers[i];
}
System.out.println(sum);
}
Results:
5
There is one more possibility, you can use HashMaps!
you don't have to traverse through any "for loops" then.
You can use Hashmaps to check whether is there any value for the key of "0", if yes then that is the case where some number is reset to 0.
Then you can traverse the Hashmap and compare which value is missing.
Everything is done With O(1) complexity and worst case of O(n) complexity.

Junit Testing error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have an assignment on arrays I'm working on and one of the questions is to write a code for a histogram.
The method histogram takes a positive number n indicating the number of divisions in which the span of the data is divided, and returns an array of integers of length n, where each element of the array contains the count of the elements that fall into this
division.
For example, if the data is (0:5; 1:2; 2:4; 9:8; 5:1; 10:5), then its span is
10:0 (from 0:5 to 10:5).
histogram(4) would divide this range into four segments:
0.5—3.0, 3.0—5.5, 5.5—8.0, and 8.0—10.5.
Inspecting the data, we see that 3 values fall in the first segment, 1 value in the second, 0 values in the third, and 2 values in the fourth. Therefore, the returned value is an array of length 4 containing the values (3; 1; 0; 2) in that order.
Note that the sum of the elements in the returned array is equal to the number of
elements in the data array.
here is my code:
#Override
public int[] histogram(int divisions) {
int[] range = new int[divisions];
double segment = span() / divisions;
for (int i = 0; i < data.length; i++) {
if (data[i] <= (smallestElement() + segment)) {
range[0] += 1;
}
if (data[i] <= (smallestElement() + (2 * segment))) {
range[1] += 1;
}
if (data[i] <= (smallestElement() + (3 * segment))) {
range[2] += 1;
}
if (data[i] <= (smallestElement() + (4 * segment))) {
range[3] += 1;
}
}
return range;
}
and here is my Junit test for my method:
#Test
public void testHistogram() {
double[] data = new double[3];
data = new double[]{0.5, 1.2, 2.4, 9.8, 5.1, 10.5};
int[] dat = new int[4];
dat = new int[]{3, 1, 0, 2};
DoubleArrayStatisticalOutcomes x = new DoubleArrayStatisticalOutcomes(data);
assertArrayEquals(dat, x.histogram(4));
}
the test is not passing. can someone tell me what I did wrong ?
You are incrementing all the histogram bins for each value. In your for loop, if a value is less than smallestValue() + segment, all the conditional statements are executed, not just the smallest it matches.
This makes your histogram cumulative. There are four elements total in the first two bins.
Add a continue statement in each if or make if 2-4 into else ifs.
Your function also breaks down the moment you pass a value not equal to 4 as the tests are hardcoded. Try something like (untested):
double lowerBound = smallestElement();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < divisions; j++) {
if (data[i] <= (lowerBound + (j+1) * segment)) {
range[j] += 1;
continue;
}
}
}

How to print an int array into a horizontal arrow?

Having an array such as int[] arr = new int[]{9, 6, 5, 2, 1, 2, 6, 3, 2, 7, 3, 8, 1, 5, 4, 7}; I want to print it like this:
* Output:
* 9
* 6 1
* 5 2 2
* 2 6 7 1
* 3 3 5
* 8 4
* 7
Without the * basically that's what I am trying to do. I intended to go over the array and just use System.out.println();until I reached then "end" which would be the 7 and then go to the next line but that didn't work.
I also tried printing 9 then 6 and 1 and so on but I couldn't make it to work either, I'm at a loss here and would appreciate guidance as to how can I think this through please.
EDIT
The intermediate step I have is making the array a "block" like this:
* Intermediate Step:
* 9 6 5 2
* 1 2 6 3
* 2 7 3 8
* 1 5 4 7
It should work for an array of any size.
I think this should work
You iterate 2 times. first you get the first row and all the diagonal rows below it, and then the last row and all the diagonal rows above it. You have to create a second array though to hold this info. I assumed that the array is same size for both X and Y. 7x7, 4x4 etc. tested with 4x4 data (your data)
String[][] array2 = new String[array.length*2][array.length];
for (int mb = 0; mb < array.length; mb++) {
String p1 = array[0][mb];
array2[mb][0] = p1;
int count = 0;
for (int i=1;i<=mb;i++) {
count++;
String p2 = array[i][mb-i];
array2[mb][count] = p2;
}
}
int counter = -1;
for (int mb = array.length -1; mb > 0; mb--) {
counter++;
String p1 = array[array.length -1][mb];
array2[mb+array.length -1][counter] = p1;
for (int i=0;i<counter;i++) {
String p2 = array[array.length -2 - i][array.length -counter + i];
array2[mb+array.length -1][i] = p2;
}
}
Well lets think you have two-dimensional array (you can change your one-dimension to two-dimensional easily)
PseudoCode :
whereToGo = RIGHT;
i = 0;
j = 0;
maxX = WIDTH;
maxY = HEIGHT;
minX = 0;
minY = 0;
while (somethingLeft){
addNumberToPyramid(array[i][j]);
if (whereToGo == RIGHT){
i++;
if (maxX == i) {
whereToGo = DOWN;
minY++;
}
} else if (whereToGo == DOWN){
//Same as if you go RIGHT, but increasing "j", at the end, you decrease maxY and then goLeft
} //... other two directions
}
This is how to parse input. Similar way for adding it to pyramid. I would prefer creating another 2D array, put that directly there as pyramid and then write method for printing this array correctly :
public class Pyramid{
//initialize minX, maxX etc.
int[][] array;
whereToGo = DOWN;
int i = 0, j = 0;
//initialize array size in constructor
public void addNumberToPyramid(int value){
if (whereToGo == DOWN){
array[i][j] == value;
j++;
if (j == maxY){
whereToGo = UPRIGHT;
maxY -= 2;
} else if (whereToGo == UPRIGHT){
} //... other else if directions
}
}
}
OK, first of all: You can't print a triangle like that for every length of an array. Say for example you had that array but missing the last entry; then your triangle would be missing one element at some point. In fact, you can print such a triangle if and only if the number of elements is the square of a natural number; in your example 16 = 4^2. Now, that 4 is also the length of your longest row.
OK, now how to do it. If you look at the intermediate step
9 6 5 2
1 2 6 3
2 7 3 8
1 5 4 7
and call that arr2, you want to print arr2[0][0] in the first row, arr2[1][0] and arr2[0][1] in the second row and so on until row 4 (which is of course the root of the length of the initial array). So you can write a nested loop that counts up like that.
Then you want to print arr2[1][3], arr2[2][2] and arr2[3][1] in the next row, then arr2[2][3] an arr2[3][2] and finally in the last row just arr2[3][3]. That is most easily done in a second nested loop.
I won't give you the exact code of course as this is obviously a learning task. But I will tell you that if you have a counter i for the outer loops and a counter j for the inner ones, the indexes in the intermediate array will depend on both i and j.

Categories

Resources