Not able to update elements in arrayList - java

I have two matrices for feature and weight elements.I am implementing an learning algorithm. I want to update elements of arraylist(vector for representing one sample of feature). Following is the code. But my elements of matrices(vector elements are not) updated. I have put the sample solution too. same value before and after updating is not expected. Could you please let me know where is the flaw in code?
for(int i =0 ; i< N ; i++){ //N is a large real number
ArrayList<Double> featureVector = new ArrayList<Double>();
featureVector = FeatureMatrix.get(i);
System.out.println("Before::"+ featureVector);
if(testList.contains(i)){
for(int j=0 ; j< testList.size(); j++){
if(i == testList.get(j)){
int indexInTestList= j;
List<Double> subListNextCandidate ;
subListNextCandidate = weightVectorNextCandidate.subList((10*indexIntTestList),((10)*(indexInTestList+1))); //clips a portion of member from long list of members
List<Double> approxWeight = new ArrayList<Double>();
approxWeight = getApproxWeight(FeatureVector, indexInTestList, FeatureMatrix,WeightMatrix, bias); //approxWeight is a vector of same dimension as of featureVector
for(int l=0 ; l< 10;l++){
double Update = featureVector.get(l)+ Rate*((subListCandidate.get(l)-approxWeight.get(l))-(lambda*featureVector.get(l)*(1/M)));//M is large real number
featureVector.set(l,Update);
}
}
}
}
else{
for(int l=0 ; l< 10;l++){
double Update = featureVector.get(l) -Rate*(lambda*featureVector.get(l)*(1/M));
featureVector.set(l, Update);
}
}
System.out.println("After:::"+ FeatureMatrix.get(i) );
}
Sample output is::
Before::[0.04539928251182193, -0.16233604402485394, 0.905018369795912, -1.2817141994528614, 0.7065420460225843, -0.8946090188977665, -1.74892020689701, -2.1539901172158187, 1.8229765478806985, -1.8109945435256574]
After:::[0.04539928251182193, -0.16233604402485394, 0.905018369795912, -1.2817141994528614, 0.7065420460225843, -0.8946090188977665, -1.74892020689701, -2.1539901172158187, 1.8229765478806985, -1.8109945435256574]

I can think of only a couple of reasonable reasons why this would happen:
Rate == 0
testList.contains(i) is always false
I would strongly suggest using breakpoints to debug this. At the very least, put a System.out.println where featureVector.set() is called to make sure it is ever called. I'm guessing it's never called because the conditions never become true.
Do use breakpoints, it'll be a life saver...

What is the return type of testList.get(j)? You're comparing an integer to what I suspect is a double. That's not very likely to go well ...

Related

Where is the Data Changing? - Permutations in Java

So for this extra credit problem in my calculus class, my other nerdy classmates and I decided that we would build a program to brute force a solution. One of these steps involves permutations. Through this algorithm, I managed to get it to work (I think):
public void genPermutations(int[] list, int k){
System.out.println("List: " + Arrays.toString(list));
System.out.println("----------------------");
if(k > list.length){
System.out.println("Not enough elements!");
return;
}
int[] counts = new int[list.length];
for(int i = 0; i < counts.length; i++){
counts[i] = 1;
}
int[] data = new int[k];
permutationHelper(list, counts, data, 0, k);
}
public void permutationHelper(int[] list, int[] counts, int[] data, int index, int k){
if(index == k){
//System.out.println(Arrays.toString(data));
permutations.add(data);
}else{
for(int i = 0; i < list.length; i++){
if(counts[i] == 0){
continue;
}
data[index] = list[i];
counts[i]--;
permutationHelper(list, counts, data, index + 1, k);
counts[i]++;
}
}
}
I have an ArrayList that stores all of the possible permutations (as integer arrays) that can be made from k elements of the list that I pass into the function. The problem is that if I print all of these permutations outside of the function, say after I call the genPermutations function, every permutation now is the same. But, when I print out the data where the comment is in the permutationHelper function, it correctly lists every possible permutation; I'm just unable to access them within the program later. My question is why are the values changing when I exit the function? Any help would be greatly appreciated.
Here are some pictures:
What is printed where the comment is.
What is printed later in the program.
The code used to print everything outside of the function is:
for(int i = 0; i < permutations.size(); i++){
System.out.println(Arrays.toString(permutations.get(i)));
}
I don't really know if that's necessary to know, but I just thought I'd include it just in case. Thanks in advance.
You're constantly modifying the same array object. Instead of adding different arrays to your list, you're in fact adding a reference to the same array over and over again.
To fix, instead of adding the data array to your list, you would have to add a copy of it, e.g. using Arrays.copyOf():
permutations.add(Arrays.copyOf(data, data.length));
Here the problem is that you are modifying the array after adding it to the list, you are modifying the same object again and again in different iterations. You were getting [3,2,1] in the list is because that was the outcome from last iteration. So as a fix you can use the following code. What it does is it will create a copy of data array and add that to the list.
int[] temp = Arrays.copyOf(data, data.length);
permutations.add(temp);
OR you can use clone() from array as follows.
int[] temp = data.clone();
permutations.add(temp);

Java - Improper Checking in For Loop

This is a chunk of code in Java, I'm trying to output random numbers from the tasks array, and to make sure none of the outputs are repeated, I put them through some other loops (say you have the sixth, randomly-chosen task "task[5]"; it goes through the for loop that will check it against every "tCheck" element, and while task[5] equals one of the tCheck elements, it will keep trying to find another option before going back to the start of the checking forloop... The tCheck[i] elements are changed at the end of each overall loop of output to the new random number settled on for the task element).
THE PROBLEM is that, despite supposedly checking each new random task against all tCheck elements, sometimes (not always) there are repeated tasks output (meaning, instead of putting out say 2,3,6,1,8,7,5,4, it will output something like 2,3,2,1,8,7,5,4, where "2" is repeated... NOT always in the same place, meaning it can sometimes end up like this, too, where "4" is repeated: 3,1,4,5,4,6,7,8)
int num = console.nextInt();
String[] tasks = {"1","2","3","4","5","6","7","8"};
String[] tCheck = {"","","","","","","",""};
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
for(int j = 0; j <=7; j++){
if(tasks[tNum].equals(tCheck[j])){
while(tasks[tNum].equals(tCheck[j])){
tNum = rand.nextInt(8);
}
j = 0;
}
}
tCheck[i] = tasks[tNum];
System.out.println(tasks[tNum]+" & "+tCheck[i]);
}
None of the other chunks of code affect this part (other than setting up Random int's, Scanners, so on; those are all done correctly). I just want it to print out each number randomly and only once. to never have any repeats. How do I make it do that?
Thanks in advance.
Firstly, don't use arrays. Use collections - they are way more programmer friendly.
Secondly, use the JDK's API to implement this idea:
randomise the order of your elements
then iterate over them linearly
In code:
List<String> tasks = Arrays.asList("1","2","3","4","5","6","7","8");
Collections.shuffle(tasks);
tasks.forEach(System.out::println);
Job done.
you can check if a certain value is inside your array with this approach.
for(int i = 0; i<= (num-1); i++){
int tNum = rand.nextInt(8);
boolean exist = Arrays.asList(tasks).contains(tNum);
while(!exist){
//your code
int tNum = rand.nextInt(8);
exist = Arrays.asList(tasks).contains(tNum);
}
}
if you are using an arraylist then you can check it with contains method since you are using an array we have to get the list from the array using asList() and then use the contains method. with the help of the while loop it will keep generating random numbers untill it generates a non duplicate value.
I used to created something similar using an ArrayList
public class Main {
public static void main(String[] args) {
String[] array = { "a", "b", "c", "d", "e" };
List<String> l = new ArrayList<String>(Arrays.asList(array));
Random r = new Random();
while(!l.isEmpty()){
String s = l.remove(r.nextInt(l.size()));
System.out.println(s);
}
}
}
I remove a random position in the list until it's empty. I don't use any check of content. I believe that is kind of effective (Even if I create a list)

Using Strings to Call Methods in Java

This is one of the first programs I am writing by myself. I want to make a physics calculator where many objects can interact with each other and give the user an option to add more objects. My idea is to have a for loop that runs through each object pulling on each other like this.
for(int n=1; n<=totalObjs; n++){
objName = "object"+n;
for(int i=1; i<n; i++){
obj2Name = "object"+i
objName.getMass();
//getting mass and position from both
//calculations here}
for(int x=n+1; x<=totalObjs; x++){
//same stuff as in the previous for loop}
}
I know there are probably huge syntax errors or logical errors in that but I'd like to sort through those on my own. Is there some way i could reference objects with the strings?
Is there some way i could reference objects with the strings?
Yes, via a Map<String, SomeType> such as a HashMap<String, SomeType>.
Think of this as being similar to an array or ArrayList, but instead of using number indices, you'd be using String indices.
Now looking at your code however, you might be better off using a simple ArrayList or array, since you appear to be trying to use numeric indices.
e.g.,
// assume a class called GravMass which has Mass, position, and momentum
List<GravMass> gravMassList = new ArrayList<GravMass>();
// fill your list
for(int i = 0; i < gravMassList.size() - 1; i++) {
GravMass gravMass1 = gravMassList.get(i);
int mass1 = gravMass1.getMass();
for(int j = i + 1; j < gravMassList.size(); j++){
GravMass gravMass2 = gravMassList.get(j);
int mass2 = gravMass2.getMass();
//getting mass and position from both
//calculations here}
}
}

Loop to check a variable

I want to loop through an array, then I want to do a check to see if the element in the arrayList is bigger than a certain number.
for(int i = 0; i < NewUser.getList().size(); i++){
if(UserAge < 50){
System.print.out.ln(UserAge)
}
}
but Im not sure on this, because i don't know how to use every element of the arrayList as part of the if, not UserAge
If it's an ArrayList you can simply iterate it without using counts etc:
for( int i : myList ){
if( i > 50 ){
}
}
To put it bluntly, you're not retrieving the elements from your list. You're comparing against a static value which will never change throughout the loop.
(You've also got some fun syntax issues, but I'll overlook those for now...)
To retrieve the elements, you have two options:
Use the i variable:
for(int i = 0; i < NewUser.getList().size(); i++){
Integer userAge = NewUser.getList().get(i);
if(userAge < 50){
System.out.println(userAge);
}
}
Use the enhanced-for statement, giving you a variable for free:
for(Integer userAge : NewUser.getList()){
if(userAge < 50){
System.out.println(userAge);
}
}
Enhanced for is recommended for collections, as it reads a lot clearer. Only index into collections and arrays if you need to get something at an exact position.

Accessing array in a return method

Good evening people,
I have a method that creates, populates, and returns an array to the function call as so:
public double[] getTotalDistances(){
double[] distance;
distance = new double[3];
for(Activity r: diary ){
if(r instanceof Run){
distance[0] += r.getDistance();
}
}
return distance;
}
and i can't seem to find a way to access this returned array to print it out in the main method, i have tried this: (where m is the object i have instantiated)
for(int i = 0; i< m.getTotalDistances().length; i++){
System.out.println(m.getTotalDistances().distance[i]);
}
this says it cannot find the variable distance.
i am aware that i can do something like:
for(double i: m.getTotalDistances()){
System.out.println(i);
}
this will print out the returned array, however, i would like to know how to do it in the "classic" way.I know that this must be extremely novice, but i couldn't find an answer. Any kind of help will be greatly appreciated.
It should be m.getTotalDistances()[i] and not m.getTotalDistances().distance[i]
Use a variable to store it before iterating.
double[] distance = m.getTotalDistances();
for(int i = 0; i < distance.length; i++){
System.out.println(distance[i]);
}
Your approach would call your getTotalDistances() method over and over inside the loop. You only need it once to work with.
You get this error
this says it cannot find the variable distance.
because the variable distance is only known in the scope of your method getTotalDistances() and thus you cannot use it outside of that (and it wouldn't make sense either).
The way it is written, distance is not defined. You will need to create a pointer the the returned value if you want to reference it.
double[] distance = getTotalDistances();
for(int i = 0; i < distance.length; i++) {
System.out.println(distance[i]);
}
Also, as it is written, any values other than the first will always be 0, and an accumulator makes more sense.
Another thing to note is that, as it is written, getTotalDistances() will run twice on each iteration of your for loop; once for the condition and again for the println(). If you were to scale this concept to a larger use case, the performance implications would be huge.

Categories