I need the second for loop to pick up where it left off. Every time the if statement is true I need a slot to fill in the array used in the first for loop. But I don't want the same key value to keep getting added. I need the second for loop to move to the next key value. (In the code below, arrl is an ArrayList of objects that have a value)
int temp = 0;
int count = 0;
for(int i = 0; i < eeVal.length; i++)
{
count= 0;
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1 && count == 0)
{
eeVal[i] = arrl.get(j);
count++;
temp=j;
}
}
}
}
return eeVal;
You need another variable to track where the inside loop has gotten to. Something like the following:
int temp = 0;
for(int i = 0; i < eeVal.length; i++)
{
for(int j = temp; j < arrl.size(); j++)
{
if(arrl.get(j).getValue() == 1)
{
eeVal[i] = arrl.get(j);
}
temp=j;
}
}
}
return eeVal;
This way, once the outside loop runs the second time around, the inside loop will start from 'temp' until the end of the loop.
From your explanation, it sounds like you do not want the inner for loop. The traversal of arrl needs to be manually controlled using a variable, e.g.`cnt', which only gets incremented when your condition for incrementing it is satisfied.
What you probably are looking for is a List.
In your answer, you don't need the first loop. This one has issues though - index i can go out of bounds.
int i = 0;
for(int j = 0; j < arrl.size(); j++) {
if(arrl.get(j).getValue() == 1) {
eeVal[i++] = arrl.get(j);
}
}
return eeVal;
What you need is a dynamic collections such as List.
Using list (I am calling the type as MyType).
List<MyType> vals = new ArrayList<>();
for(MyType item : arrl) {
if(item.getValue() == 1) {
vals.add(arrl.get(j));
}
}
return vals.toArray(new MyType[vals.size()]);
The code was picking up where the last correct value was. I needed to add 1 to j when I wanted progress to know where I left off.
int count2 = 0;
int progress = 0;
for(int i = 0; i < retVal[h].length; i++)
{
count2 = 0;
for(int j = progress; j < arr.size(); j++)
{
if(arr.get(j).getLevel() == h && count2==0)
{
retVal[h][i] = arr.get(j);
count2++;
progress = j+1;
}
}
}
return retVal;
Related
I have a nested loop that loops through every element in the list comparing it/sorting it , then I am trying to square the numbers in the list(keep in mind they need to be sorted). The problem is when I run my program, the 'test' array list that I am using does not print the last one squared, but it prints the second to last one squared twice. For example, if my array list is (1,2,3,4,5) my code should print (1,4,9,16,25) but instead it prints (1,4,9,16,16). I can't seem to figure out why.
My code:
public static void sortSquares(List<Integer> tempList) {
int result = 0;
for (int i = 0; i < tempList.size(); i++) {
for (int j = tempList.size() - 1; j > i; j--){
if (tempList.get(i) > tempList.get(j)) {
result = tempList.get(j) * tempList.get(j);
}
else if (tempList.get(j) > tempList.get(i)) {
result = (tempList.get(i) * tempList.get(i));
}
}
System.out.println(result);
}
}
Solution won't work if tempList[i] == tempList[j].Replace else if with else and it will work.
In the last external loop when i = 4, the inner loop becomes:
for (int j = 4; j > 4; j--)
which does nothing, and the outer loop prints result, which contains the previous value (16).
The solution could be to replace the condition for the inner loop to j >= i. You also need to replace the condition of the if, as tempList.get(j) will now be equal to tempList.get(i):
for (int i = 0; i < tempList.size(); i++) {
for (int j = tempList.size() - 1; j >= i; j--){
if (tempList.get(i) > tempList.get(j)) {
result = tempList.get(j) * tempList.get(j);
}
else if (tempList.get(j) >= tempList.get(i)) {
result = (tempList.get(i) * tempList.get(i));
}
}
System.out.println(result);
}
It will work for (1,2,3,4,5).
That being said, the same result could be attained with a simpler code:
Collections.sort(tempList); /* Optional, if you want to sort the result */
List<Integer> result = new ArrayList<>();
for (int i = 0; i < tempList.size(); i++) {
result.add(tempList.get(i) * tempList.get(i));
}
System.out.println(result);
I am struggling with this code here. I want print out dna in java that shows format of (0, 10, 6) which need to pass a until test
instead of looking like this
ACAAGATGCC ATTGTCCCCC GGCCTCCTGC TGCTGCTGCT CTCCGGGGCC ACGGCCACCG
CTGCCCTGCC CCTGGAGGGT GGCCCCACCG GCCGAGACAG CGAGCATATG CAGGAAGCGG
CAGGAATAAG GAAAAGCAGC CTCCTGACTT TCCTCGCTTG GTGGTTTGAG TGGACCTCCC
AGGCCAGTGC CGGGCCCCTC ATAGGAGAGG AAGCTCGGGA GGTGGCCAGG CGGCAGGAAG
GCGCACCCCC CCAGCAATCC GCGCGCCGGG ACAGAATGCC CTGCAGGAAC TTCTTCTGGA
AGACCTTCTC CTCCTGCAAA TAAAACCTCA CCCATGAATG CTCACGCAAG TTTAATTACA
It looks like this
ATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGG....
here is my code
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for(int i = 0; i < groupsPerLine; i++) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
formattedSequence.append(sequence.charAt(num));
num++;
}
}
}
}
return sequence;
}
}
You should append a white space to the sequence after a dna sequence is appended (at the end of the inner for loop). Also, when a line is full, you should append a new line (\n) character to the sequence(at the end of the outer for loop).
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for(int i = 0; i < groupsPerLine; i++) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
formattedSequence.append(sequence.charAt(num));
formattedSequence.append(" ");
num++;
}
}
formattedSequence.append("\n");
}
}
return formattedSequence.toString();
}
Looking at your code, I think you just missed some little things here and there, add a new line break after a certain character count and a space after some groups, and also you were returning the wrong variable.
Here check this code I edited based on yours, I just added some simple stuff and you got the remaining right.
public String formatInGroups(int index, int basesPerGroup,
int groupsPerLine) {
// I suppose you have a 'sequences' list somewhere
sequences.add(dna());
StringBuilder formattedSequence = new StringBuilder();
String sequence = sequences.get(index);
int num = 0;
while(num < sequence.length()) {
for( int j = 0; j < basesPerGroup; j++) {
if(num < sequence.length()) {
if (num % (basesPerGroup * groupsPerLine) == 0){
formattedSequence.append("\n");
}
formattedSequence.append(sequence.charAt(num));
num++;
}
}
formattedSequence.append(" ");
}
return formattedSequence.toString().trim();
}
Little things to consider on your next problem:
1 - You were returning your original sequence instead of the formattedSequence.toString();
2 - Try to avoid using global variables, you can declare them inside your for loop;
3 - Try using better variable names, instead of num you could name your variable after something that it is doing, like charPositionCounter, it will improve your code readability.
I have 2 methods in my program, one to add ***** above and below the smallest int in the array and one to add %%%%% above and below the largest. The method for the largest is essentially the same as the other but for some reason isn't adding what is needed.
Here is the smallest element method:
public static ArrayList smallestElement() {
int smallest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] < smallest)
smallest = array[i];
String smallestString = String.valueOf(smallest);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
if (smallestString.equals(String.valueOf(array[i]))) {
list.add("*****");
list.add(Integer.toString(array[i]));
list.add("*****");
} else {
list.add(Integer.toString(array[i]));
}
}
return list;
}
Here is the method for the largest element:
public static ArrayList largestElement() {
int largest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] > largest)
largest = array[i];
String largestString = String.valueOf(largest);
for(int i = 0; i < array.length; i++) {
if (largestString.equals(String.valueOf(array[i]))) {
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
} else {
smallestElement().add(Integer.toString(array[i]));
}
}
System.out.println(smallestElement());
return smallestElement();
}
}
If anyone knows why this isn't performing correctly, I would really appreciate the help
You are creating a new object every time you are executing the smallestElement function. Instead do something like,
ArrayList<String> list = smallestElement();
Then use this list object every time you are calling smallestElement() method
You have already created the list 3 times over by this line
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
Create just 1 list and use it instead of calling the smallestelementelement() function multiple times
You are overcomplicating things here. There is no need to turn that minimum array value into a string right there (and to then do String comparisons later on). Btw: those string comparisons are also your problem: your code will definitely not work when your minimal value shows up several times in your array - because your code will put in those patterns for each match!
Instead, you could do something like:
int indexToUse = 0;
for (int i = 0; i < array.length; i++) { // please always use braces!
if (array[i] < array[indexToUse]) {
indexToUse = i;
}
}
List<String> valuesWithMarkerStrings = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (i == indexToUse -1 || i == indexToUse+1) {
valuesWithMarkerStrings.add("******");
} else {
valuesWithMarkerStrings.add(Integer.toString(array[i]);
}
}
(where my solution assumes that you want to have *** ... instead of array[i] for such rows ... )
I Need to Write a Solution That Checks for Duplicate Values (Like Birthdays) in Each Iteration and Return the Number of Iterations That Have a Duplicate value within It. If One Duplicate is Found You Can Stop The Current Iteration And Start the Next.
What Of My Solution Should Be Altered. How Should A Solution Be Written To Solve This Duplicates Problem.
static int runSim(int thePeople, int theCount) {
int count = 0;
// Runs the Sim by Count
for(int i = 1; i <= theCount; i++) {
List<Integer> listOfGenNums = new ArrayList<>();
Random rand = new Random();
rand.setSeed(i);
ppl: for (int j = 0; j <= thePeople; j++) {
int genN = rand.nextInt(365);
// Add Values to Arraylist
listOfGenNums.add(j, genN);
// Converted ArrayList to Array
Object[] array = listOfGenNums.toArray();
// Check Item by Item
for(int h = 0; h <= array.length; h++) {
for(int k = i+1; k <= array.length-2; k++) {
// Checks if Index[i] is Same as Index[j]
if (array[h].equals(array[k])) {
count += 1;
break ppl;
} // End IF
} // End Inner Loop
} // End Loop
} // End People Loop
} // End Simulation Loop
return count;
}
I would use a HashSet. This would allow constant access to see if you have already visited the current number. If it has already been visited you can break and increment count, otherwise add it to the hashset and continue.
Here is your code rewritten to be much more efficient.
static int runSim(int thePeople, int theCount) {
int count = 0;
// Runs the Sim by Count
for(int i = 1; i <= theCount; i++) {
Hash<Integer> setOfGenNums = new HashSet<Integer>();
Random rand = new Random();
rand.setSeed(i);
for (int j = 0; j < thePeople; j++) {
int genN = rand.nextInt(365);
if(setOfGenNums.contains(genN)){
count++; break;
}
listOfGenNums.add(genN);
} // End People Loop
} //End Count Loop
return count;
}
There are many symbol games working in this way so this should sound familiar to you.
Facts:
I have two arrays with same length of 4.
(A[4] and B[4])
I fill them with random integers from 1 to 6.
I can NOT sort them in any way (they must stay the same).
Problems:
I need to compare them and after that I need to have 3 values. FIRST one needs to count how many elements are the same and in the same place. I do it like this and it is working:
int first = 0;
int k = 0;
for (int j=1; j<=4; j++)
{
k++;
if (A[k] == B[j])
{
first++;
}
}
SECOND one needs to count how many elements are the same BUT not at the same place. THIRD one needs to count how many elements are not the same at all.
I need a solution to count either SECOND or THIRD number, because after that I can just subtract like 4-(first+second) or 4-(first+second).
Here's the logic you should use: loop over the first array; for each element, check if the corresponding element of the second array is the same - if yes, increment your first counter. If they are not the same, then check whether the second array contains the corresponding element of the first array. If it does, then it's definitely not in the same position (you just checked same positions) - increment your second count. Otherwise, increment your third count. The code can be as following:
int[] A = {...};
int[] B = {...};
List<Integer> lstB = new ArrayList<Integer>(B.length);
for (int index = 0; index < B.length; index++) {
lstB.add(B[index]);
}
int first = 0, second = 0, third = 0;
for(int i=0; i<4; i++) {
if(A[i] == B[i]) {
first++;
}
else if(lstB.contains(A[i]) {
second++;
}
else {
third++;
}
}
SOLUTION
Eventually I made the right algorithm. In general, the solution is to keep track of what fields you used when counting FIRST value. And here is the code:
int first = 0;
int second = 0;
int third = 0;
boolean[] codeUsed = new boolean[4];
boolean[] guessUsed = new boolean[4];
//same value and same place
for (int i = 0; i < 4; i++)
{
if (A[i] == B[i])
{
first++;
codeUsed[i] = guessUsed[i] = true;
}
}
//same value but not right place
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (!codeUsed[i] && !guessUsed[j] && A[i] == B[j])
{
second++;
codeUsed[i] = guessUsed[j] = true;
break;
}
}
}
//not the same value
third = 4 - first - second;