I have one dimensional array list and I need to add one to the arraylist element each step if a certain condition was satisfied this is equavelent for example to number[i]=+1; I am applying the following loop
For(int i=0;i<Number;i++)
{if certain condition was met then
Array_list_element.get(i)=Array_list_element.get(i)+1;
else perform another action}
but how I can do this Array_list_element.get(i)=Array_list_element.get(i)+1;
I am a little confused if I did the following code
Array_list_element.get(i).add(1)
will the value of Array_list_element.get(i) will be always one or the one will be added at each step the condition is satified how you suggest to do this
Thanks in advance
The following code will increment the value of each element.
for (int i = 0; i < arrayList.size(); i ++) {
int oldVal = arrayList.get(i);
int newVal = oldVal + 1;
arrayList.set(i, newVal);
}
You just need to now put your conditional check either around the for loop if you want every element to increase. Or if you want specific elements to increase then you need to possibly perform a check on the oldVal if that is what you are basing it on.
Edit: So looks like you want the check inside the for loop so here is an example.
for (int i = 0; i < arrayList.size(); i ++) {
int oldVal = arrayList.get(i);
if (oldVal == 2) {
int newVal = oldVal + 1;
arrayList.set(i, newVal);
} else {
continue;
}
}
Related
I have this bit of code written here and I'm trying to search through all the numbers within the array to determine if it contains a number x, and then return a true or false boolean if it does. I am using a for loop to go through each element but I am having trouble determining how to properly check if the specific value x is within the array. The code I currently have is giving me a true or false if the array has the same index numbers as x. (Without using java.util.Arrays if possible)
for (int i=0; i<array.length; i++) {
if (x == array[i])
result = result;
else
result = !result;
}
Try this.
Assume it is not there so set result to false
Once you find a value equal, then set result to true and
break out of the loop.
boolean result = false;
for (int v : array) {
if (x == v) {
result = true;
break;
}
}
Or iterating with an index
boolean result = false;
for (int i = 0; i < array.length; i++) {
if (x == array[i]) {
result = true;
break;
}
}
Using Java streams gives an elegant solution:
result = Arrays.stream(array).anyMatch(v -> v == x);
I know this doesn't address fixing the OPs code, but I like to encourage the use of Java streams, as they have many advantages as code gets more sophisticated.
#WJS is right on in terms of giving you the two simplest, classic ways of addressing your problem.
Try this:
for (int i=0; i<array.length; i++)
if (x == array[i])
return true;
return false;
Explanation
if at any point in the loop the desired item is found, return true;
if the end of the loop is reached, this means no item was found, so return false;
Please bear within as it might be difficult to understand
I have an array of jbuttons 50 size big, for this example ill use 7 I have jbutton object within 1 2 3 4 6 7 but not 5. These are printed on the screen. I want to remove these jbuttons however all buttons up to 5 are removed while the last two are not.
for(int i = 1; i < 51; i++){
if(seat.buttonArray[i] == null){
remove(seat.buttonArray[i]);
seat.buttonArray[i] = null;}
}
There is no way to remove element from array, assuming you want latter indexes changed after remove. For this purpose, you should use List:
Iterator buttonIterator = seat.buttonList.iterator();
while (buttonIterator.hasNext()) {
Object button = buttonIterator.next(); //or more specific type, if your list was generified
if (button == null) { //or some other criteria, wrote this just as an example
buttonIterator.remove();
}
}
If using array is mandatory, you have two options:
Set seat.buttonArray[i] to null value, indicating it has been removed;
Recreate array each time you deleted something. See System.arraycopy javadoc for details, although I do not recommend this approach because of performance considerations.
You could store the values in a temp array and then copy what you want back into your original array. Somewhat similar to this:
int myArray[50];
int temp[50];
int good;
for (int i = 0; i < 50; i++) {
myArray[i] = i;
}
for (int i = 0; i < 50; i++) {
temp[i] = myArray[i];
}
good = 0;
for (int i = 0; i < 50; i++) {
if (i < 10) {
} else {
myArray[good] = temp[i];
good += 1;
}
}
Looks messier than I first thought... But it essentially does what you're wanting.
In my program, i "deleted" an element by turning it into a null as you can't delete an element from an array so employee [i] = null. However, I was wondering, if I wanted to work with the array that had a null element, like add all the numbers in the array, how do I do this without any problems?
[UPDATE:]
My array contains the first names, last names and ages of 4 employees, I've "deleted" one of the employees details by making it null. As per all of the suggestions I got, I tried to add all the ages using:
int sum = 0;
for (int i = 0; i < employee.length; i++) {
if (employee[i] != null)
sum += employee[i].getAge();
}
but all I get is that sum = 1.
If the only operation you're going to perform on your array is the sum of all elements, it would make more sense to set the deleted elements to 0 instead of null. This way, you will not need the extra null check on every iteration.
You have to check if that element is null or not. If it is, add to the sum. If not, do nothing.
int sum = 0;
for (int i = 0; i < employee.length; i++) {
if (employee[i] != null)
sum += employee[i];
}
public int addAllNums(int[] nums)
{
int sum=0;
for(int i=0;i<nums.length;i++)
{
if(nums[i]!=null)sum+=nums[i];
}
}
You just have to iterate over your array and check if the current employee is not null :
int sum = 0;
for(int i = 0; i < employee.length; i++) {
if(employee[i] != null) {
sum += employe[i].getNumber();
}
}
How to count duplicates in ArrayList and count only once.
Here is what I have so far:
/**
* Gets the number of duplicates in the list.
* Get the next word. It is at index i. Does it match any of the words with index > i?)
* #return the number of duplicate words in the list
*/
public int countDuplicates() {
int duplicates = 0;
for (int i = 0; i < list.size(); i++) {
for (int j = i; j < list.size(); j++) {
if (list.get(i).equals(j)) duplicates++;
}
}
return duplicates;
}
Here is check output:
Actual: 0
Expected: 3
I am missing something very easy. However, couldn't find what exactly it is.
How to solve this trouble?
You don't get the jth element you just compare to j directly. And as a commenter points out, j should start at i+1 to avoid comparing an element to itself. Therefore, you need to write
public int countDuplicates()
{
int duplicates = 0;
for (int i = 0; i < list.size(); i++) {
for (int j = i+1; j < list.size(); j++) {
if (list.get(i).equals(list.get(j))) duplicates++;
}
}
return duplicates;
}
Should be:
public int countDuplicates()
{
int duplicates = 0;
// TODO: Write the code to get the number of duplicates in the list
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i).equals(list.get(j))) duplicates++;
}
}
return duplicates;
}
Use two sets for this:
final Set<X> set = new HashSet<>();
final Set<X> dups = new HashSet<>();
int dupCount = 0;
for (final X x: list) {
if (set.add(x)) // first time the element is seen
continue;
// Dup; see whether it is the first time we see it
if (dups.add(x))
dupCount++;
}
return dupCount;
This relies on the fact that Set's .add() returns true if and only if the set has been modified as the result of the operation. And note that it traverses the list only once.
I can see three problems with your current code:
You are not comparing pairs of elements. You are actually comparing an element with an index.
Your inner loop is comparing element i and element i ... and that would result in a false "duplicate" count.
If you have more than 2 copies of any given element, then you will get too many duplicate counts. (To see why, try to "hand execute" with a list of (say) three identical elements.
In fact, you have to EITHER use an auxiliary data structure (e.g. 2 Sets or a Map) OR modify the input list to avoid counting duplicates more than once.
I would note that your statement of the problem is ambiguous. "... only count each duplicate once" could mean that '[1, 1, 1]' gives either 1 or 2. It depends whether you consider each individual 1 to be a duplicate to be counted once or that we have 1 as one of a set of duplicates ... that must only be counted once.
You are comparing index j value instead of value of list list.get(j).
Do
if (list.get(i).equals(list.get(j)))
instead of
if (list.get(i).equals(j))
I am in the process of writing a sudoku solver (still need to write the box check and actually complete the program) but I'm testing it as I know. The puzzle I'm testing right now is "very easy" as in there is only one empty cell in any row/column. THe puzzle starts with "empty" cells as zeros. My issues is that when I run the program and print out the puzzle after solve() is called, the zeros aren't changing and the original puzzle is just printed out. Not sure what my issue is, would appreciate some direction!
public ArrayList<Integer> create(){
ArrayList<Integer> possible = new ArrayList<Integer>();
for(int i=1; i<10; i++){
possible.add(i);
}
return possible;
}
public sudoku( int size )
{
SIZE = size;
N = size*size;
Grid = new int[N][N];
for( int i = 0; i < N; i++ )
for( int j = 0; j < N; j++ )
Grid[i][j] = 0;
}
public void solve()
{
int a, b, c, d, i, j, k, l;
int count = 0;
int value= 0;
for(i=0; i<N;i++){
for(j=0; j<N;j++){
if(Grid[i][j]==0){
ArrayList<Integer> possible = create();
//check row
for(a=0; a<N;a++){
for(b=0; b<N; b++){
if(Grid[a][0]==possible.get(a)){
possible.set(a, 0);
}
}
}
//check column
for(c=0; c<N;c++){
for(d=0; d<N;d++){
if(Grid[0][d]==possible.get(d)){
possible.set(d,0);
}
}
}
for(k=0; k<9; k++){
if(possible.get(k)!=0){
count++;
}
}
if(count==1){
for(l=0; l<9; l++){
if(possible.get(l)!=0){
value=possible.get(l);
}
}
}
Grid[i][j]=value;
}
}
}
}
Look at your line if(Grid[a][0]==possible.get(a)) (and similar spots). What is it doing there vs what do you actually want?
Your possible array looks something like this:
[1,2,3,4,5,6,7,8,9]
and your grid (just the first row, since you're only checking Grid[a][0]) might look something like this:
[3,7,8,1,2,9,5,0,4]
Your loop is looking at each element stepwise individually and seeing if they're equal, like this:
if(1 == 3) ... it's not
if(2 == 7) ... it's not
if(3 == 8) ... it's not
... etc
So, as you can see, when you do your
for(k=0; k<9; k++){
if(possible.get(k)!=0){
count++;
}
}
Your possible array is still going to be full of options most of the time, unless your first row happens to be some variation on [1,2,3,4,5,6,7,8,9] with a 0 in one of the spaces... so count is definitely going to be > 1
So, your next loop (for(l=0; l<9; l++)) next gets executed, so value is still (as you initialized it) 0.
Try stepping through a debugger on these points and seeing how the arrays are interacting.
if(Grid[a][0]==possible.get(a))
if(Grid[0][d]==possible.get(d))
You don't use b or c in these lines. You probably want:
if(Grid[a][i]==possible.get(b))
if(Grid[j][d]==possible.get(c))
Also, the Grid[i][j]=value check should be inside the if block.
You might want to use a Set for the possible values instead of an ArrayList.
You are always checking only the first row and first column and the way you check for the possible numbers is also not doing what you want.
A few tips first:
First of all, it is not necessary to always define a new variable for the loops, you can reuse them and then you won't have too many of them and you won't get so easily confused in them.
Secondly, if you name all the variables a, b, c, d, etc. you can also easily get confused. While it is ok to name variables in loops as i, j, if you have too many loops, it may be better to think of better names. In this case row and column for example.
Why don't you remove the numbers from the possible list? Something like:
int index = possible.indexOf(a);
if (index != -1) possible.remove(index);
Then it would be easier to determine how many values you still have left. You can simply do:
if (possible.size()==1) value = possible.get(0);
And one last note, to obey the convention for variable names, you should probably use grid instead of Grid.
And now the code:
public void solve() {
int row, column, i;
int count = 0;
int value= 0;
int index = 0;
for(row=0; row<N; row++){
for(column=0; column<N; column++){
if(Grid[row][column]==0){
ArrayList<Integer> possible = create();
//check row
for(i=0; i<N; i++){
index = possible.indexOf(Grid[row][i]);
if (index != -1) possible.remove(index);
}
//check column
for(i=0; i<N; i++){
index = possible.indexOf(Grid[i][column]);
if (index != -1) possible.remove(index);
}
if (possible.size()==1) value = possible.get(0);
Grid[row][column]=value;
}
}
}
}
EDIT: Rewritten the whole answer into a better form.