Inverting values in an array [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
The program is meant to invert the values in the array. When the program is run, the only values that show are 3 and 2, then it ends. I've been looking online but I can't figure out why this happens. Switching val[i] for temp in the SOP gives values of 0 and 1 then ends.
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length/2;i++)
{
temp=val[i];
val[i]=val[val.length - 1 - i];
val[val.length - 1 - i]=temp;
System.out.println(val[i]);
}

Because your for loop only iterate for values 0 and 1, then at the end it prints only 0th and 1st elements, try following
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length/2;i++) {
temp=val[i];
val[i]=val[val.length - 1 - i];
val[val.length - 1 - i]=temp;
}
for(int i=0;i<val.length;i++){
System.out.println(val[i]);
}

It makes sense to use val.lenth/2 to only traverse half of the array, swapping values as you go. It does not make sense to only traverse half of the array while trying to print the entire array. Try using another for loop to print out the contents of the ENTIRE array.
edit: I tried not to just give the answer

for(int i=0;i<val.length/2;i++)
val.length/2= 4/2 = 2 so that the for loop will only run twice. Thats why it prints only the 3 and 2.
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length;i++)
{
if(i<val.length/2){
temp=val[i];
val[i]=val[val.length- 1 - i];
val[val.length- 1 - i]=temp;
}
System.out.println(val[i]);
}

Related

How to delete close elements in java bidimensional array with same values [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 9 months ago.
Improve this question
I changed the request to be clearer. I need to know how to remove a group of neighboring elements that have the same value from a two-dimensional array.
For example if i have the following matrix with dimension 2 rows x 5 columns:
4, 2, 3, 4, 4 row 1
1, 3, 4, 4, 4 row 2
I would like to know how to delete this group of close elements with the same value 4 :
4, 2, 3, 4, 4 row 1
1, 3, 4, 4, 4 row 2
Not involving elements which don't form a group like the 4 in the top left corner.
I'd like to replace the deleted elements with value -1
say you created the array as:
int myArray[] = {4, 2, 3, 4, 4};
myArray has a size of 5. The size of an array is fixed.
You can replace them with a 0.
also are you trying to 'remove' a group of the same number?
You can try something like this..
for(int i = 1; i < myArray.length; i++){
// if previous element == current element set to 0
if(myArray[i-1] == myArray[i]){
myArray[i-1] = 0;
}
}
myArray[myArray.length] = 0;

Array index out of bound exception how to overcome [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public void updateGoalPositions(Goal[][] goals)
{
int row=(goals.length-1);
int col=(goals[0].length-1);
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
{
if(goals[i][j+1].isHit())
{
Goal temp=goals[i][j+1];
goals[i][j+1]=goals[i][j];
goals[i][j]=temp;
}
else
if(goals[i][j-1].isHit())
{
Goal temp=goals[i][j-1];
goals[i][j-1]=goals[i][j];
goals[i][j]=temp;
}
}
}
goals[i][j-1] shows error. How to override it?
when j = 0, j - 1 gives -1 which causes the error so test condition only if j - 1 >= 0
else
if(j - 1 >= 0 && goals[i][j-1].isHit())
{
Goal temp=goals[i][j-1];
goals[i][j-1]=goals[i][j];
goals[i][j]=temp;
}
On first j-iteration, j=0 and j-1's value is -1
Add if (j-1>-1) for example
When i = 0 and j = 0, goals[i][j-1] is going to mean goals[0][-1] that is your issue, you need to fix your algorithm.
Everywhere you have j+1 you'll exceed the limit in the last iteration.
Why? Because arrays are zero-based in Java, meaning that if you have an array of size N, the indexes will run between [0, N-1]. In your last iteration, when j is N-1, j+1 is actually N, which is out of bounds.
Read about arrays in the JLS - Chapter 10. Arrays.
Note also that you have places where j-1 will be -1 (in the first iteration where j is 0).

Using the contains method [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The objective of this program is to take the two arrays x and y and then create and array list contain numbers that occur in both x and y and then to print out this array of matching numbers. When I go to compile it gives me the error class expected on line 19 and another error saying ";" expected on the same line which I'm guessing is due to the other error. Is it just an error on that line or is it a bigger issue?
import java.util.ArrayList;
import java.util.Arrays;
public class FindCommon {
public static void main (String[] args) {
ArrayList list = new ArrayList();
int[] x = {1, 4, 3, 0, 1, 2};
int[] y = {6, 4, 5, 0, 6, 1};
for (int i = 0; i < x.length ; i++){
int number = x[i];
if (y[].(contains(x[i])){ // Line 19
list.add(x[i]);
}
System.out.println(list);
}
}
}
if (y[].(contains(x[i])){
The above line is invalid for a various of reasons. The index for y array is missing. Also according to the requirement, you need to call the contains() method on the list and not the array. And there seems to be an extra pair of braces.
if (!list.contains(x[i])){
list.add(x[i]); // Add to the list if it doesn't contain the value already
}
You need to do the same for the elements of y too.
Better Solution: You can use a Set instead of a List. It'll eliminate the duplicates for you. All you need to do is just add elements to your set from both the arrays.

"Yahtzee" game Java Programming [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My assignment is to make "Yahtzee" game on Java Program.
I am almost done except the Small Straight method. (Cannot figure it out.)
Small Straight is when the dice got 4 straight number. (Ex. 12334, 23345, 34556, and etc.)
Here is my code of isSmallStraight method (This code is not completed!):
public static boolean isSmallStraight(List<Die> dice) {
boolean result = false;
List<Die> copy = new ArrayList<Die>(dice);
Collections.sort(copy);
List<Die> testCase1 = new ArrayList<Die>();
testCase1.add(new Die(1));
testCase1.add(new Die(2));
testCase1.add(new Die(3));
if(copy.containsAll(testCase1)) {
result = true;
System.out.println(result);
}
return result;
}
What I want to do in here is I passed 5 random numbers of dice from the main method (List dice) and put them into the "copy" object.
Since I need to use java.util.List.containsAll() method(requirement), I think I need to make one other object "testCase1" to compare with "copy". (If you have other method to solve this question, it is fine at least you use java.util.containsAll() method.)
However, what I don't know right now is if I use dice.add(new Die(3)), it means the program picks random numbers from 1,2, and 3. (Not die number 3) - Also, it gave me compile-time error.
So, I want to know how I can store dice specific number 1,2,3, and 4 for "testCase1", 2,3,4, and 5 for "testCase2", and 3,4,5, and 6 for "testCase3" and use copy.containsAll(testCase1) becomes true.
Please help me as soon as possible!
PS. Die class is already programmed by my professor. (So, cannot change any in the Die class).
Put the numbers into a TreeSet to get rid of duplicates and get sorting for free.
You have 4 straight dice if:
The set contains exactly 4 numbers
The difference between the largest and the smallest is 3
The method I like to use (for large and small straights as well as all other scoring) is to create a new int array from the int array that holds the dice values. Like this:
int[] numDice = new int[6];
for (int i: diceValues)
numDice[i-1] += 1;
This counts up all your dice and puts the number of each, in order, in a new array. For instance, if the 5 dice you rolled were 3, 4, 3, 1, and 6, your new array would be {1, 0, 2, 1, 0, 1}, and a yahtzee of all 4s would turn into {0, 0, 0, 5, 0, 0}. From this new array it's fairly trivial to determine all of the scores. For straights:
int straightCount = 0;
for (int i: numDice) {
if (i > 0)
straightCount++;
else
straightCount = 0;
if (straightCount > 3)
smallStraight = true;
if (straightCount > 4)
largeStraight = true;
}
If you wanted to you could use this array to easily determine all the valid scores in one short method, and store the booleans in a single array.

How to get the max number in all sliding windows of an array? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Given an array of numbers and a sliding window size, how to get the maximal numbers in all sliding windows?
For example, if the input array is {2, 3, 4, 2, 6, 2, 5, 1} and the size of sliding windows is 3, the output of maximums are {4, 4, 6, 6, 6, 5}. The size of the sliding window is a variable passed to you.
A sliding window is basically a subarray of the original array that starts at a particular index. For instance, at index 0, with size 3, it's the first 3 elements. At index 1, with size 3, it's the 2nd, 3rd and 4th element.
How would you solve this in Java or any other programming language? Or pseudocode, if you so desire.
(Note: This is NOT a homework question, just a question I found on a site that I have my own solution to but want to compare it with others, I'll post my solution below afterwards too)
You can do it in O(N*Log(W)), where N is the size of your array, and W is the size of the sliding window.
Use a binary tree to store the first W numbers. For the following N-W steps, get the max value from the tree for your output, add the element at the current position i to the tree, and remove the element at i-W from the tree. These operations are all O(Log(W)), for the overall timing of O(N*Log(W)):
int[] data = new int[] {2, 3, 4, 2, 6, 2, 5, 1};
int W = 3;
TreeMap<Integer,Integer> counts = new TreeMap<Integer,Integer>();
for (int i = 0 ; i != W ; i++) {
if (counts.containsKey(data[i])) {
counts.put(data[i], counts.get(data[i])+1);
} else {
counts.put(data[i], 1);
}
}
for (int i = W ; i != data.length ; i++) {
Integer max = counts.lastKey();
System.out.println(max);
int tmp = counts.get(data[i-W])-1;
if (tmp != 0) {
counts.put(data[i-W], tmp);
} else {
counts.remove(data[i-W]);
}
if (counts.containsKey(data[i])) {
counts.put(data[i], counts.get(data[i])+1);
} else {
counts.put(data[i], 1);
}
}
System.out.println(counts.lastKey());
Demo on ideone.
Since you don't mind pseudocode/other langs, how about this (in Python):
l = [2, 3, 4, 2, 6, 2, 5, 1]
result = [max(l[i:i+3]) for i in range(len(l)-2)]
I always start with the naive algorithm if I'm trying to solve something like this. What's wrong with scanning the array window by window? Well, when you see what's not great about that (you're repeating the same comparisons over and over), you can start to look for other approaches.
One approach is suggested by visualizing the initial array as a mountain range: find the highest peak. Nothing's taller than that, so that's the max for the windows around it. Now you can proceed recursively. There are probably other, better approaches.

Categories