Java Variable expected inside a for loop - java

I'm pretty new here and new to Java in general. I'm trying to solve a projecteuler question and I thought I had a solution but got stick with this error that I cannot fix. Just to give you an idea of what I was going for(in case it wasn't clear) this is the question:
"What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
I don't want a solution but rather any help with getting rid of the "Java Variable expected inside a for loop." error would be appreciated.
public class Main {
public static void main(String[] args) {
int remainder = 0;
int remainders[] = new int[20];
int j = 1;
int remaindersMax = 0;
while (true) {
for (int i = 1; i <= 20; i++) {
j % i = remainders[i];
for (int k = 0; k < remainders.length; k++) {
if (remaindersMax < remainders[i]) {
remaindersMax = remainders[i];
}
}
}
if (remaindersMax == 0) {
break;
}
System.out.println(j);
}
}
}

j % i = remainders[i];
is invalid syntax. The left hand side (LHS) of a variable assignment can only contain a variable, not an expression. The right hand side (RHS) can contain arbitrarily complex expressions. You want to assign the array remainders at index i the value of the modulo operation. Swap LHS and RHS to make your program compile:
remainders[i] = j % i;

Related

Program entering in a infinite loop only with a specific value

I just started with java and while was doing an exercise about permutations (the exercise asked to create a permutation of N elements using an array a[] meeting the requirement that no a[i] is equal to i.) I've created the following code. While testing it, I realized that it entered in a infinite loop sometimes when N = 6 specifically.
Any thoughts on where is the problem?
public class GoodPerm {
public static void main(String arg[]) {
int n = Integer.parseInt(arg[0]);
int[] guests = new int[n];
for (int i = 0; i < n; i++) {
guests[i] = i;
}
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int q = guests[r];
guests[r] = guests[i];
guests[i] = q;
if(guests[i] == i){
i --;
}
}
for(int q : guests){
System.out.println(q);
}
}
}
Maybe the code enters in a inf-loop in another values, but I didn't found any others.
This code can always enter an inf-loop. As I understand the code, you try to do some random switches to achieve your needed result. But if the last element of your array has never been switched, it won't be possible to switch it to any "later/higher" position (because there are no more). In the "last" iteration of your second for-loop (so i + 1 == n holds at the beginning) r will always evaluate to i thus no real switch happens. If the last element is still in place, you gonna repeat this forever.

Ordering a list of 10 numbers

I have an atomic integer array of size 10. I am using this array to organize numbers 1-10 sent in by threads. This 1-10 will eventually be able to change to be a range of numbers larger than 10 and the list is to contain the 10 greatest numbers in that range. I can see the numbers going into the loops and recognizing that they are greater than a number currently there. However, there is never more than 2 numbers in the array when it is printed out. I have tried to trace my code in debug mode, however, it looks as if it is working as intended to me. I feel like there may be a simple error to my logic? I am completely sure all values are entering in the function as I have triple checked this. I start at the end of the array which should contain the highest value and then swap downwards once the slot has been determined. I would appreciate the assistance. This is just a simple experiment I am doing in order to grasp the basics before I try to tackle a homework assignment.
Here an example of my code:
public class testing{
static AtomicIntegerArray maxList = new AtomicIntegerArray(10);
final static int n = 10;
static void setMax(int value)
{
for(int i = 9; i >= 0; i--)
{
if(value > maxList.get(i))
{
int temp = maxList.get(i);
maxList.set(i,value);
if(i == 0)
{
maxList.set(i, value);
}
else
{ for(int j = i-1; j > 0; j--)
{
maxList.set(j, temp);
temp = maxList.get(j-1);
}
}
break;
}
}
public static void main(String[] args)
{
for (int i = 0; i < n; i++)
{
setMax(i);
}
}
}
Here is an example of how it is being called:
Brooke, there is a small bug in your 'j' loop. You had saved the state of a variable (temp), however your logic in the j loop lost the state. This new logic preserves the state of the previous element in the list.
Try this:
for (int j = i - 1; j >= 0; j--) {
int t2 = maxList.get(j);
maxList.set(j, temp);
temp = t2;
}

List of Non-Repeating Ints in Java? Assignment

I'm trying to create a list of 20 integers between 0 and 26 (so in the 1-25 range) that does not repeat as a part of an assignment. I thought I had it figured out, but the program keeps looping over and over without ever ending. Can anyone help me out?
import java.util.Random;
public class prog433a
{
public static void main(String args[])
{
Random r = new Random();
int[] list = new int[20];
for (int k = 0; k < list.length; k++)
{
boolean notADupe = false;
while (notADupe == false)
{
list[k] = r.nextInt(25) + 1;
for (int j = 0; j < list.length; j++)
{
if (list[j] == list [k] && j != k)
{
notADupe = true;
}
else
{
notADupe = false;
break;
}
}
System.out.println(list[k]);
}
}
}
}
EDIT: This is different from the other question because I am trying to figure out how to check for uniqueness using the methods that I am allowed to use in my assignment (essentially, the ones I'm already using in the code).
I think you've reversed the condition out there. Inside if, you should set notADup to false, rather than true. However, I would make the variable isDup instead, and change the while loop accordingly.
One more suggestion: instead of while (notADupe == false), you should just use while (!notADupe). Never compare boolean variables like that. It might surprise you at times.
So to solve your issue, just change your if-else block to:
if (list[j] == list [k] && j != k) {
notADupe = false;
break;
} else {
notADupe = true;
}
BTW, your solution is a bit complex. For every element, you are iterating over whole array to find duplicate. Rather I would suggest you to maintain a Set<Integer> storing the already seen numbers, and check in that every randomly generated number. If present, skip it and re-generate.
Pseudo code would look something like this:
arr = [] // Your list array, initialize to size 20
seen = [] // A Set
for i from 1 -> arr.length
num = rand.nextInt(25) + 1
while seen contains num
num = rand.nextInt(25) + 1
seen.add(num)
arr[i] = num

Dynamically change the number of nested for loops

I don't know if this is a stupid question, but I need to dynamically change the number of for-loops without using recursion.
For example, if n=3, I need 3 nested for-loops.
for(int i=0; i<size; i++){
for(int j=0; j<size-1; j++){
for(int k=0; k<size-2; k++){
//do something
}
}
}
If n=5:
for(int i=0; i<size; i++){
for(int j=0; j<size-1; j++){
for(int k=0; k<size-2; k++){
for(int l=0; l<size-3; l++){
for(int m=0; m<size-4; m++){
//do something
}
}
}
}
}
Is there any way to achieve this without recursion?
Another question: what is the use of Multiple Dispatch in Java? I'm trying to code something in ONE METHOD, and it should run different events in different cases of the parameter. NO IF STATEMENTS / TERNARY OPERATORS / CASES.
NOTE: I can ONLY have one method (part of the problem), and cannot use recursion. Sorry.
Think about how many times you run through this loop. It looks like (size!) / (size - n)!:
int numLoops = 1;
for (int i = 0; i < n; i++) {
numLoops*= (size - i);
}
for (int i = 0; i < numLoops; i++) {
//do something
}
It depends what exactly you're trying to do. Recursion can always be replaced with iteration (see this post for examples using a Stack to store state).
But perhaps the modulo (%) operator could work here? i.e. Have a single loop that increments a variable (i) and then the other variables are calculated using modulo (i % 3 etc). You could use a Map to store the values of the variables indirectly, if there are a varying number of variables.
You have to create array of loop counters and increment it manually.
Quick and dirty example:
public static void nestedFors(int n, int size) {
assert n > size;
assert size > 0;
int[] i = new int[n];
int l = n - 1;
while(l >= 0) {
if(l == n - 1) {
System.out.println(Arrays.toString(i));
}
i[l]++;
if(i[l] == size - l) {
i[l] = 0;
l--;
} else if(l < n - 1) {
l++;
}
}
}
Replace System.out.println(Arrays.toString(i)) with your own code.
You can check it here: http://ideone.com/IKbDUV
It's a bit convoluted, but: here is a way to do it without recursion, in one function and without ifs.
public static void no_ifs_no_recursion(int n){
int[] helper = new int[n-1];
int[] pointers = new int[n]; //helper for printing the results
int totalsize = 1;
for (int loops = 2; loops <= n; loops++){
helper[n - loops] = totalsize;
totalsize*=loops;
}
for (int i=0; i<totalsize; i++){
int carry = i;
for (int loops = 0; loops < n-1; loops++){
pointers[loops] = carry/helper[loops];
carry = carry - (pointers[loops]*helper[loops]);
}
System.out.println(Arrays.toString(pointers));
//or do something else with `i` -> `pointers[0]`, `j` -> `pointers[1]`, `k` -> `pointers[2]` etc..
}
}
I think you need a backtracking algorithm.
But then you would replace your nested loops with recursion.
I don't want to post links here as seems moderators don't like that.
Look at "eight queens puzzle" (you can Google it), you will get my idea.
I know this idea works as I've posed this same question (which you have) to myself on many occasions, and I've applied it several times successfully.
Here is a small example (I changed it as the previous one was a bit complex).
public class Test001 {
public static void main(String[] args) {
loop(0, 5, 10);
}
/**
* max_level - the max count of nesting loops
* size - the size of the collection
*
* 0 - top most level
* level 1 - nested into 0
* level 2 - nested into 1
* ...
* and so on.
*/
private static void loop(int level, int max_level, int size){
if (level > max_level) return;
for (int i=0; i<size-level; i++){
System.out.println("Now at level: " + level + " counter = " + i);
loop(level + 1, max_level, size);
}
}
}
But this still uses recursion.

Java - Repeat Function for Specific Numbers

I am exceptionally new to programming, but I am working on improving my skills as a programmer. Recently, I gave myself the challenge to determine what multiples of a given number are made up of distinct digits. I have gotten most of it to work, but I still need to make the code apply for every number that is a multiple of the input one. The code I have working so far is as follows:
Integer numberA = 432143;
Integer numberB = numberA;
Integer[] digitArray = new Integer[numberA.toString().length()];
int index;
for (index = 0; index < digitArray.length; index++) {
digitArray[index] = (numberA % 10);
numberA /= 10;
}
int repeats = 0;
for (int i = 0; i < digitArray.length; i++) {
for (int j = 0; j < digitArray.length; j++) {
if ((i != j) && (digitArray[i]==digitArray[j])) repeats = repeats + 1;
}
}
if (repeats == 0) {
System.out.println(numberB);
}
This will determine if the number is made up of distinct digits, and, if it is, print it out. I have spent quite a bit of time trying to make the rest of the code work, and this is what I've come up with:
Integer number = 1953824;
Integer numberA = number;
Integer numberB = numberA;
for (Integer numberC = number; numberC.toString().length() < 11;
numberC = numberC + number) {
Integer[] digitArray = new Integer[numberA.toString().length()];
int index;
for (index = 0; index < digitArray.length; index++) {
digitArray[index] = (numberA % 10);
numberA /= 10;
}
int repeats = 0;
for (int i = 0; i < digitArray.length; i++) {
for (int j = 0; j < digitArray.length; j++) {
if ((i != j) && (digitArray[i]==digitArray[j])) repeats = repeats + 1;
}
}
if (repeats == 0) {
System.out.println(numberB);
}
}
I can't figure out why, but his just prints whatever the number is a bunch of times if it is made up of distinct digits, and leaves it blank if it is not. If anyone could tell me why this is occurring, or even tell me what I need to do to fix it, that would be superb. Remember, I am very new to programming, so please give a short explanation for any terms you use that are at all out of the ordinary. I am eager to learn, but I currently know very little. Thank you for your time, and I greatly appreciate any and all help you can give me.
You assign the value of numberA to numberB (which is the value of number) right before the for loop. After that, numberB is never modified or assigned to a new value, so for every pass through the for loop, you're simply printing the value of numberB, which is always 1953824 in this case.
There are several corrections that can be made to achieve the result you desire, while cleaning up the code a little. The first thing is to change the print statement to print the correct number:
System.out.println(numberC);
Since numberC is the variable that is being updated by the for loop, that's what you'll want to conditionally print out if there are no repeat digits. Since we've replaced numberB with numberC, that means numberB is not longer needed, you can delete the declaration for it.
Now, the next issue is when you're defining the digital array - you should use the length of numberC, not numberA. Also, inside the for loop, you should assign numberA the value of numberC, or else eventually nothing but 0s will be stored in your digitArray. Overall, here's what it should look like.
Integer number = 1953824;
Integer numberA = number;
for (Integer numberC = number; numberC.toString().length() < 11;
numberC = numberC + number) {
Integer[] digitArray = new Integer[numberC.toString().length()];
numberA = numberC;
int index;
for (index = 0; index < digitArray.length; index++) {
digitArray[index] = (numberA % 10);
numberA /= 10;
}
int repeats = 0;
for (int i = 0; i < digitArray.length; i++) {
for (int j = 0; j < digitArray.length; j++) {
if ((i != j) && (digitArray[i] == digitArray[j]))
repeats = repeats + 1;
}
}
if (repeats == 0) {
System.out.println(numberC);
}
}
This should produce the desired result. It seems to work on my machine :)
If you want, you can take Jeffrey's suggestion and change the Integer to the primitive int to avoid the overhead of boxing. However, you still need to use the Integer class to use the toString() method, but you can accomplish that using Integer.valueOf():
Integer.valueOf(numberC).toString()
So if I understand correctly you are trying to find out if certain multiple exists within your number. Instead of constantly dividing by 10 instead use the modulus symbol. You can even embed it in conditional statements.
For example:
if(numberOne % 2 == 0)
Then we know that numberOne divided by 2 has a remainder of zero and is thus a multiple of 2

Categories

Resources