Hi guys so right now I'm taking data structures in school and I'm having trouble understanding the code our homework is based on which was created by the teacher.
Basically its a program designed to store integers and assign them sets depending on if their positive, negative, and a set that keeps track of weather or not the last entry of an integer was either. We have a class that creates a new array with the storage of whatever int is passed to it. We also have a insert method that inserts an int into a collection only if its not already there. heres the code:
public IntColl1(int i){
c = new int[i+1];
c[0] = 0;
}
public void insert(int i){
if (i > 0){
int j = 0;
while ((c[j] != 0) && (c[j] != i)) j++;
if (c[j] == 0){
if (j == c.length - 1){
int newLength = (c.length * 2);
int[] d = new int[newLength];
for(int l = 0; l < c.length; l++){
d[l] = c[l];
}
c = d;
}
c[j] = i;
c[j + 1] = 0;
}
}
}
Its supposed to insert the Int into the array and if the array is too small, it creates a new one with double the length. For test we set Intcoll1(1), Can anyone help by explaining the while loop that is inside the first if statement? I always thought that when an empty array is created that the slots were all set to 0, and if thats the case then wouldn't that while loop always be false?
It appears that the while loop is trying to find the next "available" space in the array. Initially (as you correctly stated) the while condition will immediately be false. After a couple of inserts, it will be more useful.
Assuming an initial array size of 5, c would start out looking like
[0,0,0,0,0]
If I call insert(4), the condition
(c[j] != 0) && (c[j] != i)
Fails, so j is never incremented and 4 is inserted as position 0. Now c looks like
[4,0,0,0,0]
Now if I call insert(7), the condition will be initially satisfied when j is 0, but will fail when j is incremented to one, so 7 will be inserted as position 1:
[4,7,0,0,0]
Can anyone help by explaining the while loop that is inside the first if statement?
Well I feel that there is a problem in understanding your program above. So I am re-writing the code to make it clear to your:
public void insert(int i){
if (i > 0){
int j = 0;
while ((c[j] != 0) && (c[j] != i)){ //Introduced this bracket to show the start of while
j++;
} //Introduced this bracket to show the end of while
if (c[j] == 0){
if (j == c.length - 1){
int newLength = (c.length * 2);
int[] d = new int[newLength];
for(int l = 0; l < c.length; l++){
d[l] = c[l];
}
c = d;
}
c[j] = i;
c[j + 1] = 0;
}
}
}
The next if statement if (c[j] == 0) is not inside the while loop. Hope that now your understand it.
Related
I am implementing a code for counting number of occurrences for all the characters in a String. I have used indexOf() method to check occurrences. But it's not working for the first character.
The following code works fine for all characters except the first character.
public static void main(String[] args) {
String str = "simultaneously";
int[] count = new int[str.length()]; //counter array
for (int i = 0; i < count.length; i++) { //initializing counters
count[i] = 0;
}
for (int i = 0; i < str.length(); i++) {
int index = -1;
char c = str.charAt(i);
while (1 > 0) {
if (str.indexOf(c,index) > 0) { //This is not working for
//the first characters
index = str.indexOf(c, index) + 1;
count[i]++;
} else {
break;
}
}
}
for (int i = 0; i < count.length; i++) {
System.out.println(str.charAt(i) + " occurs " + count[i] + " times");
}
}
Index for arrays in java starts from 0.
Change the condition from
if (str.indexOf(c,index) > 0) {
to
if (str.indexOf(c,index) >= 0) {
And also, the for-loop to initialize the counter is redundant, by default, all the values in the int array is initialized to 0.
str.indexOf(c,index) would return 0 for the first character, but your condition checks whether str.indexOf(c,index) > 0. Change it to str.indexOf(c,index) >= 0.
There is some thing else you need to know
str.indexOf(c,index)
will search for the character c from the index 'index' which is -1 in your case for the first character that is it will never find this because starting point of string is 0
also change your condition as following
str.indexOf(c,index) >= 0
The index of arrays and Strings (which are array of characters) always start at 0 in Java.
You also want to check position 0, so include >=.
if (str.indexOf(c,index) >= 0) {
Also, using breaks can sometimes be confusing.
In your code, your while-loop is an infinite True and then you break out of it when necessary.
Take a look at this code below. It serves the same purpose that you want to accomplish.
It is much cleaner and clearer as it removes the break from the whileloop and you simply check to see if the statement is True at the beginning of the while-loop rather than inside it.
for (int i = 0; i < str.length(); i++) {
int index = 0;
char c = str.charAt(i);
while (str.indexOf(c,index) >= 0) {
index = str.indexOf(c, index) + 1;
count[i]++;
}
}
The job of this method is to remove the value toRemove from the array. The remaining elements should just be shifted toward the beginning of the array. (The array's size will not change.) Since the array will now have one fewer element, the position of the last element should just be filled with 0. If there is more than one occurrence of toRemove in the array, only the first occurrence should be removed. The method has no return value, and if the array has no elements, it should just have no effect.
The solution:
public static void remove(int[] arr, int toRemove) {
boolean done = false;
int position = 0;
for(int pos = 0; pos < arr.length; pos++) {
if(!done && arr[pos] == toRemove) {
done = true;
position = pos;
}
if(done) {
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
}
}
}
I am not following how this algorithm works. The use of boolean confuses me, I feel I don't fully understand what the primitive data type does, I know that it holds two things either true or false, and false by default. But what does that really mean? I don't understand boolean.
I understand why would want an int placeholder for the index of where the toRemove value was found. I understand we would want to use a for-loop to iterate one-by-one the indices and their respective values and pinpoint where exactly toRemove is found. I understand we would want a check point conditional to see if at some arbitrary index the toRemove value exists, andd therefore:
if(arr[pos] = toRemove) // then bingo we've found him
I don't understand the boolean !done, booleans confuse me.
why after this check point is there done = true? and then after that another check if(done)? and why another for loop for(int i = position + 1; i < arr.length; i++) and after that for loop the line arr[i - 1] = arr[i];? and finally at the end arr[arr.length-1] = 0 and position = pos;
I understand when we want to access a particular indicies value we write variablenameOfArr then the [] and put it inside the box. I am having difficulty putting this all together.
Thank you
In this case, the boolean done seems to control whether a value has already been removed or not. It begins the algorithm as false, as nothing has been removed yet.
The first if statement tests to see if the value of done is false. In if statements, instead of saying if(done == false), this can be simplified to if(!done). So, this if statement simply tests to see if a value has been found yet or not.
done is then set to true once a value has been removed, so that no future values will be removed.
Finally, the second if statement tests to see if a value has been removed or not. Like the first if statement, if(done == true) can be simplified to if(done).
I hope this helps, comment with any further questions if they arise.
public static void remove(int[] arr, int toRemove) {
boolean done = false; //This boolean is used to determine when the element has been found
int position = 0;
for(int pos = 0; pos < arr.length; pos++) { //Iterating through the array
//if we aren't already done, (!done = NOT DONE) and we have found the position to remove, then enter this logic
if(!done && arr[pos] == toRemove) {
done = true; //since we found the position to remove, set done to true
position = pos; //Save the index of the one that was removed
}
if(done) { //if we are done, enter this logic
//This loop starts above the index where removed, and iterates to the top
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i]; //This shifts each element down one
}
arr[arr.length -1] = 0; //This sets the empty slot at the top of the array to 0
}
}
}
The boolean is indeed not necessary since it is always true when if(!done && arr[pos] == toRemove) is true.
Besides, it makes no sense to go on the outer loop when you have removed an element as 1) the state of the array is nice : the inner loop has shifted the elements after the removed element to their left and 2) you cannot perform two removals.
By the way the position variable is also not required. You can use the pos variable directly as it is read only used.
This code :
for(int pos = 0; pos < arr.length; pos++) {
if(!done && arr[pos] == toRemove) {
done = true;
position = pos;
}
if(done) {
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
}
}
could be replaced by this without using the boolean and you could also exist the method after the array elements were shifted :
for(int pos = 0; pos < arr.length; pos++) {
if(arr[pos] == toRemove) {
for(int i = pos + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
return;
}
}
So, I am having to do some complicated Array manipulation and am having some difficulty. Thought i might ask you guys for help.
Anyhow, What i am trying to do is basically the following.
Let's say i have an array of numbers, with zeroes peppered. So, What i wanna do is move all elements up to the top of the array and therefore, fill the elements with zereos in them.
I'll use an example to explain ;
Let's say the array is : {4,4,0,2,0,2}
What i wanna do is : {4,4,2,2,0,0}
So, all the numbers are in one area basically and sorted.
Now, the second thing i wanna do is add all similar numbers, so if we continue with the above example : {8,4,0,0,0,0}
Now, what i have tried to is basically run through the whole loop and move the next item back when i see a zero and replace that with a zero but that is leading to some issues.
Some suggestions would be awesome. Thansk
Edit :
I figured out how to do the sorting etc and a little bit of the addition , Here is what i have. Please let me know if you suggestions to make it better.
for(int j = 0; j < row.length ; j++){
for(int i = 0 ; i < row.length ; i++){
if(row[i] == 0){
row[i] = row[i+1];
row[i+1] = 0;
} else if(row[i] == row[i+1] ){
row[i] = row[i+1] + row[i];
row[i+1] = 0;
}
}
}
}
However, the sorting is all fine but there is a slight issue with the addition of similar elements.
So, If we something like {2,2,2,2,0,0} after sorting then my addition part will do this : {8,0,0,0,0,0} which isn't what i want. What it should be is {4,4,0,0,0,0}
A simple way to do that is to split the work in two parts: Combine pairs, and push elements left. About the order of operations:
pushLeft then combine
Orignal array: {4,2,0,2,0,4}
After pushLeft: {4,2,2,4,0,0}
After combine: {4,4,4,0,0,0}
With this order, you have to take care of the holes you create while combining values.
combine then pushLeft
Orignal array: {4,2,0,2,0,4}
After combine: {4,4,0,0,0,4}
After pushLeft: {4,4,4,0,0,0}
Those can be implemented using a simple loop for each function. There is also the possibility to do it all in a single loop (combining and pushing left), but it is more tricky.
My code is below (2nd method), but you may want to give it a try yourself before:
public static int[] goLeft(int[] a) {
int[] arr = a.clone();
for (int j = 0, i = 0; j < arr.length; j++) {
if (arr[j] != 0) {
arr[i] = arr[j];
if (i++ != j) arr[j] = 0;
}
}
return arr;
}
public static int[] combine(int[] a) {
int[] arr = a.clone();
for (int j = 1, i = 0; j < arr.length; j++) {
if (arr[i] == 0 && arr[j] != 0) {
i = j;
} else if (arr[j] != 0 && i != j) {
if (arr[j] == arr[i]) {
arr[i] *= 2;
arr[j] = 0;
i = j;
} else {
i = j;
}
}
}
return arr;
}
public static void main(String[] args) {
int[] a1 = new int[] {4,2,0,2,4};
System.out.println(Arrays.toString(a1));
System.out.println(Arrays.toString(Main.goLeft(Main.combine(a1))));
// [4, 4, 4, 0, 0]
}
Hi I'm seeking to understand in java how you can take an int array and then in an if statement compare one single element from the int array against just a declared int. I want to just simply compare two ints against each other but one is inside of an int array. The == I guess doesn't work?
for (int count = 5; count >= 0; count--) {
if (gameBoardTokens[count] == 0) {
if (playerOneTurn) {
gameBoardTokens[count] = 1;
count = 0;
} else {
gameBoardTokens[count] = 2;
count = 0;
}
}
}
you need to change this (count < -1) for this (count > -1)
because at first 5 > -1 not -1 > 5.
gameBoardTokens[count] == 0 works. The thing that makes your code unfunctional is that the code in the for-loop is never executed, because count is initially 5, for which count < -1 is false. So the loop immediately aborts.
//Kevin Clement
//Week3A Magic Squares
Hey all, doing an introductory assignment to 2dimensional arrays. Below is the code I have done which is pretty much done.
My problem I get is I'm not entirely sure how to print out the array, as well as getting everything to run right with a test method. I get an error out of bounds at the line msq[order][order] = 1;
I apologize if my formatting of question is wrong, still not used to this site. Any help would be great. Thanks!
import java.util.*;
class Magic
{
private int order;
int msq[ ][ ];
public Magic(int size)
{
if(size < 1 || size % 2 == 0)
{
System.out.print("Order out of range");
order = 3;
}
msq = new int[order][order];
Build();
Display();
}
public void Build()
{
int row = 0;
int col =0;
msq[order][order] = 1;
for(int k = 1; k <= order * order; k++)
{
msq[row][col] = k;
if(row == 0 && col == order -1)
row++;
else if(row == 0)
{
row = order - 1;
col++;
}
else if(msq[row - 1][col + 1] != 0)
row++;
else if(msq[row -1][col + 1] == 0)
{
row--;
col++;
}
if(col == order - 1)
{
col = 0;
row--;
}
}
}
public void Display()
{
for(int i = 0; i < order; i++)
{
for(int k = 0; k < order; k++)
{
System.out.println(msq[i][k] + " ");
}
}
}
}
I get an error out of bounds at the line msq[order][order] = 1;
msq = new int[order][order];
// ..
msq[order][order] = 1;
If array size is n, then you need to access the elements from 0 to n-1. There is no nth index. In your case there is no order, order index. It is only from 0 to order-1 and is the reason for array index out of bounds exception.
What is the reason for this condition in the constructor?:
if(size < 1 || size % 2 == 0)
{
System.out.print("Order out of range");
order = 3;
}
Note that whenever you use a size input that doesn't satisfy the if clause, the variable order is not initialized and defaults to 0. As a result the 2d array has size zero and throws the out of bounds error. If you are trying to use 3 as a default value, then u want to move the line:
order = 3;
before the if block.
Other things to consider:
1. make the order variable final since u don't plan on changing it. Eclipse IDE would warn you about the situation described above if you do so.
or
2. If you are going to default to 3 for the value of order initialize it as such.
private int order = 3
Also you might consider printing a message saying order defaults to three when the condition is not satisfied.
To print a matrix of integers in Java
for (int i = 0; i < order; i++) {
for (int k = 0; k < order; k++) {
System.out.printf("%6d", msq[i][k]);
}
System.out.println();
}
The second part of your question is answered by Mahesh.
msq[order][(order] = 1;
--> here is a syntax error. You have an '('.
You get end of bound error because array start from 0 not 1 (which is a mistake every beginner makes) therefore change it to msq[order-1][order-1] = 1;
The answer above is the correct way to print out the array.