Why does my Java "for" loop immediately end? - java

My first loop seems to build the array correctly and when I go to print out the results in the second "for" loop it immediately terminates. I cannot see the error. Here is the code:
public class CoinFlip
{
private static int Flip()
{
return (int)(2*Math.random()); //returns 0 or 1; 0=Tails,1=Heads
}
public static void main(String args[])
{
int HEADS = 1;
int[] ConsecArray = new int[1000]; // the odds of ever having more than 1000 HEADS consecutively flipped are nil
int Sequencecounter = 0;
for (int i = 0; i < ConsecArray.length; i++)
{
if (Flip() == HEADS)
{
Sequencecounter++;
}
else // we have a TAILS
{
// Check sequence counter, if > 0, logging to do...
if (Sequencecounter > 0)
{
// Update length counters
int index = Sequencecounter - 1;
ConsecArray[index]++;
Sequencecounter = 0;
}
// consecutive tails, continue in loop
}
}
int j = ConsecArray.length;
System.out.println("Length" + " " + "NumberRunsOfHeads");
for (int k = 0; k == j; k++)
{
int index = k + 1;
String bucketName = Integer.toString(index);
String bucketValue = Integer.toString(ConsecArray[k]);
System.out.println(bucketName + " " + bucketValue);
}
}
}

The first iteration of your 2nd loop:
k is 0
j is 1000
the test k == j fails
the loop never runs

Change
for (int k = 0; k == j; k++)
into
for (int k = 0; k < j; k++)

I think you mean either k <= j or k < j, but you put k == j. This is not true during first iteration, so loop body never executes.
for (int k = 0; k == j; k++)
{
int index = k + 1;
String bucketName = Integer.toString(index);
String bucketValue = Integer.toString(ConsecArray[k]);
System.out.println(bucketName + " " + bucketValue);
}

Instead of for (int k = 0; k == j; k++) (which is equivalent to if (k == j)) you meant to write or for (int k = 0; k < j; k++), i.e. loop j times, not loop as long as k == j.

This:
for (int k = 0; k == j; k++)
Should be this:
for (int k = 0; k < j; k++)

kett_chup is right. I Think you want "k < j". You're thinking of "until" rather than "for".

Related

Calculate total number of combinations of size k in array using recursion in Java?

I am attempting to write a recursive method that COUNTS the number of combinations of k size in an integer array.
I can easily do this for a known value k (e.g. 3) as so:
int[] arr = {1,2,3,4};
int count = 0;
for(int i = 0; i < arr.length; i++) {
for(int j = i+1; j < arr.length; j++) {
for(int k = j+1; k < arr.length; k++) {
count++;
}
}
}
However, I would like to be able to do this without a known k. I have found methods online that print the combinations using recursion, such as this one:
https://www.techiedelight.com/find-distinct-combinations-of-given-length/, but none that count them.
Simple case of modifying the method linked.
public static int recur(int[] A, int i, int k)
{
int count = 0;
if (k == 0) {
count++;
}
for (int j = i; j < A.length; j++) {
count = count + recur(A, j + 1, k - 1);
}
return count;
}

Sorting Method Not Sorting Properly

This method is supposed to sort the words from a given file in alphabetical order after it is selected. Everything is working except it doesn't properly sort it. The input file reads "kundu is a man kundu man", but no matter what I try I get "[is, kundu, a, man, kundu, man]".
I tried taking away the "-1" and the "+1" but that did nothing to help.
private String[] selectionSort(String[] stringArray)
{
for(int j = 0; j < stringArray.length - 1; j++)
{
int min = j;
for(int k = j + 1; k < stringArray.length; k++)
{
if(stringArray[k].compareTo(stringArray[min]) < 0)
min = k;
swap(stringArray, j, min); //this method swaps the words
// by using a temp
//swap(intArray, j, min);
}
}
return stringArray;
}
private void swap(String [] stringArray, int i, int j) //swap method
{
String temp = stringArray[i];
stringArray[i] = stringArray [j];
stringArray[j] = temp;
}
Your swap call should be after the inner loop. Like,
private String[] selectionSort(String[] stringArray) {
for (int j = 0; j < stringArray.length - 1; j++) {
int min = j;
for (int k = j + 1; k < stringArray.length; k++) {
if (stringArray[k].compareTo(stringArray[min]) < 0) {
min = k;
}
}
swap(stringArray, j, min);
}
return stringArray;
}
After that, with no other changes and your input, I get
[a, is, kundu, kundu, man, man]

Why is this condition satisfied? (j == nElems)

I wrote this code to find an element in an array which is working pretty well but I do not understand how it works 100%. My question is, how come (j == nElems) when it only runs from 0 to 9? I've also noticed that the condition is satisfied outside the for loop when the search key is not found.
public class ArrayApp {
public static void main(String args[]) {
int nElems = 10;
int[] arr = new int[nElems];
int j;
int searchKey;
arr[0] = 77;
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
System.out.println();
//Find 66 in array
searchKey = 66;
for (j = 0; j < nElems; j++) {
if (arr[j] == searchKey) {
break;
}
}
if (j == nElems) {
System.out.println("Cant find " + searchKey);
} else {
System.out.println("Found " + searchKey + " in position " + j);
}
//Remove 55 from array
searchKey = 55; // delete item with key 55
for (j = 0; j < nElems; j++) { // look for it
if (arr[j] == searchKey) {
break;
}
}
for (int k = j; k < nElems - 1; k++) { // move higher ones down
arr[k] = arr[k + 1];
}
nElems--;
for (j = 0; j < nElems; j++) {
System.out.print(arr[j] + " ");
}
}
}
Let's have look at your for loop:
for (j = 0; j < nElems; j++) {
if (arr[j] == searchKey) {
break;
}
}
Here's what Oracle's documentation says about for loop:
The increment expression is invoked after each iteration through the
loop; it is perfectly acceptable for this expression to increment or
decrement a value.
So, in the above loop, j is incremented after each iteration. In the second last iteration, j will be nElems-1. It will execute the loop and increment j which would then make it equal to nElems.
As if condition is placed after the loop, by the time control reaches it, j will already be equal to nElems and hence, it will be true.
We can attempt to simplify what this for loop means
for (j = 0; j < nElems; j++) {
if (arr[j] == searchKey) {
break;
}
}
The for loop essentially breaks down to the following:
int j = 0;
int nElems = 10;
while(j < nElems) {
if(arr[j] == searchKey) {
break;
}
j++;
}
You can see that the final condition would be when j is equivalent to 10 (nElems).
for (j = 0; j < nElems; j++) {
if (arr[j] == searchKey) {
break;
}
}
nElems is 10. So j < nElems will be satisfied until j reaches 10. At that point, it will exit the loop. It'll only reach that point, however, if
arr[j] == searchKey
is never satisfied (ie. the search key is not found). So what you're seeing is that the search key is never found, j is incremented up until 10, at which point the loop is exited. At this point, j == nElems.
At the end of every iteration, j is incremented. After that, the stopping condition is tested. If that condition is true, the loop exits. Otherwise, it continues with the new value of j.
This means that your for loop runs as long as j < nElems. Once j == nElems, the for loop is done. Hence at the end, j must necessarily be equal to nElems; otherwise the loop will never terminate.

WAP to return the length of longest common substring between two strings

Two strings are given and we have to find the length of longest common substring. I don't know what's wrong with my code.
The outer loop takes a substring of B and the inner loop increases the substring by one character at a time.
For the input "www.lintcode.com code", "www.ninechapter.com code" the output is coming 5 but it should be 9
public class Solution {
/**
* #param A, B: Two string.
* #return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
int k = 0, temp = 0;
if(B.length() == 0){
return 0;
}
for(int i = 0; i < B.length()-1; i++){
String bb = B.substring(i, i+1);
if(A.contains(bb)){
for(int j = 1; j < A.length()-i; j++){
String bbb = B.substring(i, i+j);
if(!A.contains(bbb))
break;
temp = bbb.length();
}
}
if(temp > k)
k = temp;
}
return k;
}
}
Just replace this:
for(int j = 1; j < A.length()-i; j++)
with this:
for(int j = 1; j < B.length()-i+1; j++)
I believe you could reduce your function size a little with this...not sure if your method is more efficient or not though...
public int longestCommonSubstring(String A, String B) {
int longestSubstring = 0;
for (int x=0; x < A.length(); x++) {
for (int y=x; y < A.length() + 1; y++) {
String testString = A.substring(x,y);
if (B.contains(testString) && (testString.length() > longestSubstring)) {
longestSubstring = testString.length();
}
}
}
return longestSubstring;
}

Arrays in for loops

I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?
Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once
Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20

Categories