I am trying to swap the values of two sections of an image in a specific fashion: I want to move one block of pixes to the right 225 pixels, and take the block that was there and move it to the left 225 at the same time. However, it looks like the only transformation that takes hold is the first one:
public void exchange() {
int[][] stablePic = picArray.clone();
for (int i = 80; i < 230; i++)
{
for (int j = 50; j < 250; j++)
{
picArray[i][j] = stablePic[i][j+225];
picArray[i][j+225] = stablePic[i][j];
}
}
}
"picArray" is initialized earlier in the code - this compiles and runs, but only makes the first exchange - the second portion of the image still has the appearance of the first portion. Is there any way to have both transformations take place at once?
Are you sure the second fragment is the only one working? It seems to me that is the first one which is working.
To copy one array to other array don't just assign it. Use 2 for-loops for this, and when you see it works, investigate about how to replace the inner for-loop with Arrays.copyOf.
Here you have:
int[][] stablePic = picArray;
Which makes both variables point to the same memory, then when you modify your picArray you are modifying your stablePic also.
You are trying to swap two sections of an image for understanding purpose just take it as how can you swap two variables i.e
int a=10;
int b=20;
int temp ;//take a temp variable for swapping
temp =a;
a=b;
b=temp;
like this you have to take a temporary array.For swapping .in your code second one is working because it is overriding with the previous one.
Related
Tried changing around the for loop condition several times, still get ArrayIndexOutOfBounds when I pass zero as a parameter. Every other number works fine, I am trying to account for zero by setting it equal to zero automatically, am I doing that part incorrectly? Everything compiles and runs fine except for zero.
private static int iterativeCalculation(int userEntry)
{
int iterativeArray[] = new int[userEntry + 1];
iterativeArray[0] = 0;
iterativeArray[1] = 1;
for (int i = 2; i <= userEntry; i++)
{
iterativeArray[i] = (3 * iterativeArray[i - 1]) - (2 * iterativeArray[i - 2]);
iterativeEfficiencyCounter++;
}
return iterativeArray[userEntry];
}
public static void main(String[] args) {
System.out.println(iterativeCalculation(0));
}
Tried debugging my way through the code, still not understanding what is going wrong. Would appreciate any help! Thanks!
When you pass zero as parameter, userEntry + 1 = 1.
But here:
iterativeArray[1] = 1;
You are trying to set the second element's value. Remember that length of array is one less than its actual size. So removing this line will fix it. Or use userEntry + 2 instead and alter your loop accordingly.
EDIT:
If you really want to fix first and second element, then use this instead:
int iterativeArray[] = new int[userEntry + 2];
iterativeArray[0] = 0;
iterativeArray[1] = 1;
This will create an array of adequate base size.
And remember, length you enter in [...] while creating array has to be one more than the actual length you want. Because actual array starts counting from 0.
In your case, you were setting length as 1 (minimum). That would create an array which can store only one element; that is iterativeArray[0] = //something. Anything above that is OutOfBounds.
You are setting iterativeArray[1] = 1; regardless of whether or not there are actually 2 or more items in the array. That will be out of bounds with one element.
I think you should step through the code in debugger to best understand what the problem is. You'll see exactly where it's got a problem if you single-step through the code. This is a fundamental technique and tool.
to describe my issue I must first discuss what I am trying to do, http://i.imgur.com/rcHwze5.png here is an image of a letter with a 10*10 grid over it. For every box in the grid if 1/3 of the pixels are colored a 1 is added to the ArrayList, otherwise a 0 is added. Here is my 3 methods that I have created to do this: https://gist.github.com/VincentMc/7ddf3c282e80bbff7835 BoundBM is a bitmap object with the letter drawn onto it.
Here is an image of my desired output http://i.imgur.com/B0QnUW8.png
Here is an image of my actual output http://i.imgur.com/WgRVXLv.png
It seems once a 1 is added on a row it is constantly added until it reaches the next row, but I can't seem to see why??
Any help would be greatly appreciated I have been at this quite a while, Thanks!
do it in two step:
1: sort each string:
public String sortString(String s1){
char[] chars = s1.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
return sorted;
}
2: put each of your string in an array and use:
Arrays.sort(stringArray);
Out of the Code-Segmet you offered, i cant see an obvious mistake. But your design is inviting mistakes. To avoid these you may try:
Don't use count as a classwide variable, thou its not relevant for the hole class but only for the method. So make it an return statement, that you dont loose control over it, that it may be set anywhere or is only changed locally in a method.
totalp should not be calculated in every countPixel() method call, because it is a fixed value for your BoundBM. Initialize it in your constructor maybe, or with loading the bitmap.
At last, you know how large your output array is supposed to be, it doesnt make much sense for me, to keep it a list and to add it. Create an 2D array, and write it directly.
Hope it will help
reineke
EDIT: found the mistake!
in code line 27 you set x to 0 and not to the initial value of the input x, so you continue at the wrong position!!
Here is what i would do:
final int GRID=10;
totalp = boundBM.getWidth()/GRID * boundBM.getHeight()/GRID;
//this method now does not need to read boundBM, so it is more opject-oriented
public int countPixels(int x, int y, int h, int w){
count = 0;
for (i=x; i<x+w; i++){
for(k =y; k<y+h; k++){
if(c != boundBM.getPixel(i, k)) count++;
}
}
//funny thing
return (count>totalp/3) ? 1 : 0;
}
public void createNeuralInput(){
int h = boundBM.getHeight()/GRID;
int w = boundBM.getWidth()/GRID;
int[][] array= new int[GRID][GRID];
for(int i = 0; i < GRID; i++) {
for(int j = 0; j < GRID ; j++) {
n1.add(countPixels(i*h, j*w, h, w));
//i would prefer:
//array[i][j]=countPixels(i*h, j*w);
}
}
}
Given a matrix filled in with all its values, there's the need of pulling out data randomly in order to create a random matrix (intialized with null values each position). The issue lies while checking if a position (within the randomMatrix) is different from null, as shown below:
public void randomLogic(String[][] givenMatrix){
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int positioni = this.randInt(0, 1);
int positionj = this.randInt(0, 1);
int x = this.randInt(0, 3);
int y = this.randInt(0, 2);
/*In here lies the reported issue while checking if empty. */
while (!this.randomMatrix[x][y].isEmpty()) {
x = this.randInt(0, 3);
y = this.randInt(0, 2);
this.randomMatrix[x][y] = givenMatrix[positioni][positionj];
}
}
}
}
I've also tried with the following: while(this.randomMatrix[x][y] != null) and the code breaks down right away. All the solving-logic work out as expected (because if I ommit that part it works with flaws but works) the only problem is that validation. Regardless of what position is being evaluated it always stops working.
Is there any other way of checking a matrix position value?
are you trying to pull random values (and consequently, some will be repeated) from a givenMatrix OR do you want to specifically randomize the givenMatrix?
If it's the latter, I would approach it differently.
First of all, gather all values of the givenMatrix in one linear-array or list.
Then, you can randomize this array, and you'll be left with a big array of rows*columns items, with all the values from the original matrix already randomized.
Then, you can systematically fill the new randomized matrix, taking each element of the array in order, till you complete each row and column of the new matrix.
I would choose this approach, because it's easier, and it will finish in a fixed number of steps; rather than filling random positions, because maybe you land 2 times in the same place to fill, and you'll have to randomize until you hit all the spots.
(Also, if you don't care of repeating the values for the new matrix, then instead of taking each element of the randomized array, you can simply pick a random position of this array each time)
Have you declared String[][] randomMatrix as a class level member variable? If you have declared the randomMatrix correctly then the isEmpty() and != null checks should work.
i am using the import becker.robots file for this assignment!
I must create a class DistributeBot (extended RobotSE) which will put down a number of 'things' in the shape of 2 squares.
When the main method is then created, a single call to a method (which i must create myself using stepwise refinement and also contains a parameter) called this.putThings();
The method i am to create should have a single variable parameter to define the size of the squares! ie a parameter of (4) will make a 4x4 square of 'Things'.
The robot should set out the Things one line at a time from left to right! (once one line is displayed, it should move back to the LHS before displaying the next line)
I think i will be able to complete the scenario without problem whenever i am certain on how to create the method with the parameter i have specified.
Assumptions.
1. Starting position of the robot will always be the same. ie starting at 1, 1.
2. There will always be enough 'things' in the robots backpack to display the two squares.
Anyone have an idea how I would go about setting up this method initially with the variable parameter?
If you have your method starting
Public void MakeSquare(int size)
{
for(int i = 0; i < size; i++)
{
for(int x = 0; x < size; x++)
{
//drop thing
//move right
}
for(int y = 0; y < size; y++)
{
//move left
}
//move up
}
}
Whilst reading the question you should try and break it down into its simplest parts.
start with Build a square that is the most abstract form of the scenario and so makes your method, then break it down
//I want to move up until I hit size limit
for each number in "the size you want"
//I want to move right and drop a thing, until I hit size limit
for each number in "the size you want"
drop a thing
move one right
endloop
//I want to move back to the LHS until I hit size limit
for each number in "the size you want"
move one left
endloop
//then make the move up
move up
endlood
If you make this method and call it twice you will make the 2 squares as required)
I have been debugging my implementation of Game of Life, and my main problem looks like its coming from how I use arrays.
public boolean[][] oldState;
public boolean[][] newState;
private boolean gameState = true;
public LifeBoard(Seed seed) {
oldState = seed.getSeed();
newState = new boolean[oldState.length][oldState[0].length];
run();
}
public void run() {
//debug code to run for x generations
for (int i = 0; i < 5; i++) {
BoardPrinter.print(oldState);
evaluateCells();
oldState = newState;
}
BoardPrinter.print(oldState);
System.out.println("game over");
}
the boolean[][] from Seed is a 5x5 grid, all false (dead) except the 3 horizontal middle cells in the middle row
00000
00000
0+++0
00000
00000
evaluateCells() looks at each cell in the grid, looks at the 8 cells around it, counts them, and based on the number of neighbors it writes a new value to newState.
What should happen: use oldState to calculate newState, copy newState to oldState, then go back through newState, writing each cell again based on the new oldState.
What really happens: the first generation works correctly, but after that the results are increasingly weird, it evaluates cells to be false that I know to be true, etc. The problem seems to be in the way I am copying the arrays.
If I initialize a 3rd blank array blankState[][] = new boolean[5][5];
and during the loop in run say:
public void run() {
//debug code to run for x generations
for (int i = 0; i < 5; i++) {
BoardPrinter.print(oldState);
evaluateCells();
oldState = newState;
newState = blankState;
}
BoardPrinter.print(oldState);
System.out.println("game over");
}
...then the game works correctly for an additional 1 generation, then the weird garbage returns.
I have 2 questions: first, it looks like I have to use System.arraycopy(), but unless someone tells me about a version for multidimensional arrays, I will have to write a simple loop.
My real question: why do you have to use this special System method to copy an array? Why can't you use the = operator?
EDIT: the conceptual answer is accepted below. Here is the code that solved the implementation problem:
for (int n = 0; n < oldState.length; n++) {
System.arraycopy(newState[n], 0, oldState[n], 0, oldState.length);
}
for (int t = 0; t < newState.length; t++) {
System.arraycopy(blankState[t], 0, newState[t], 0, newState.length);
}
Also for the record, System.arraycopy(boolean[][], 0, boolean[][], 0, boolean.length); did not work correctly, you have to iterate through each line.
My real question: why do you have to use this special System method to copy an array? Why can't you use the = operator?
This is actually an important Java lesson, so pay attention. Are you paying attention? Good. This will be important in the future.
Now, this applies for all objects in Java, as arrays are objects. If you use = then you only set the reference, and encounter all kinds of fun as seen here. Namely, if I have a simple class with a getter and setter called TestClass with a public int test, then the following code will work:
TestClass t=new TestClass();
t.test=1;
TestClass t1=t;
t1.test=6;
System.out.println(t.test); //prints 6.
Now, why? Because the references t and t1 point to the same object on the heap. And this holds for arrays as well. To get copies, you need to perform tasks that are object-specific. Some let you call clone() directly(Cloneable interface), some let you pass another instance into the constructor to get a new instance(Like the ArrayList constructor), and some use utility methods, like arrays here.
evaluateCells() looks at each cell in the grid, looks at the 8 cells
around it, counts them, and based on the number of neighbors it writes
a new value to newState.
What should happen: use oldState to calculate newState, copy newState
to oldState, then go back through newState, writing each cell again
based on the new oldState.
What really happens: the first generation works correctly, but after
that the results are increasingly weird, it evaluates cells to be
false that I know to be true, etc. The problem seems to be in the way
I am copying the arrays.
Without seeing your bit shifting code, I'd bet this is caused by a higher level problem. Most likely your bit shifting algorithm has a bug somewhere.
Have you stepped through your code with Eclipse's debugger? If not, read this tutorial and try a few different seeds. This will tell you where, if anywhere, in your algorithm the bit shift error occurs.
http://www.vogella.com/articles/EclipseDebugging/article.html