What's the logical flaw in my iteration method? - java

When iterate() is first called i'm generating a random number between 1-1024 and then checking if that random number is equal to 1. If it is, then done = true and the return value should be 10. If it's not, then the value of x should be decremented (x now = 9). I then expect getRandNum() to be called again within iterate(), this time generating a random number between 1-512 and checking if it's equal to 1 etc, etc... until the return value for x can only be equal to 1.
import java.util.Random;
public class Main {
static boolean done = false;
public static int rand(int x) {
Random rand = new Random();
return rand.nextInt(x) + 1;
}
public static int value(int x) {
return (int) Math.pow(2, x);
}
public static int getRandNum(int x) {
return rand(value(x));
}
public static int iterate() {
int x = 10;
do {
if (getRandNum(x) == 1) {
done = true;
}
else {
if (x > 1) {
x--;
}
else {
x = 1;
done = true;
}
}
} while (done = false);
return x;
}
public static void main(String[] args) {
System.out.println(iterate());
}
}
Right now iterate() only returns 9. I need it to return anything from 1-10. There's clearly a logical error, but i can't see it.

Small error: you did while(done = false). This assigns done to false. The correct way to do this is while(!done).
public static int iterate() {
int x = 10;
do {
if (getRandNum(x) == 1) {
done = true;
}
else {
if (x > 1) {
x--;
}
else {
x = 1;
done = true;
}
}
} while (!done);
return x;
}
If you do this it prints 1.

Related

Multiply objects in an array witrh another object recursively in Java

Hello there I am learning Java and after doing some tasks to learn recursion I was giving my self some exercises to learn it a bit more but now I am struggeling with some..
So the main Problem is that I dont know how I can multiply every element in an Array recursively when the elements in that array are object (Maybe there is at the end no difference if objects are in there or not). So the exercise I gave myself was: check if 1 / 3 is in the given Array. If Yes then multiply everything in that array with 2 / 1.
This is Fraction:
private int numerator; // Zaehler
private int denominator; // Nenner
public Fraction ( int num, int denom )
{
if ( denom != 0 )
{
if ( denom < 0 )
{
numerator = -num;
denominator = -denom;
}
else
{
numerator = num;
denominator = denom;
}
reduce();
}
else
{
// error: division by zero
throw new IllegalArgumentException();
}
}
public Fraction()
{
numerator = 0;
denominator = 1;
}
public Fraction( int num )
{
numerator = num;
denominator = 1;
}
So I got it done by doing it with an for loop:
public static Fraction[] mulWithFor(Fraction[] arr)
{
for (int i = 0; i<arr.length; i++)
{
arr[i] = arr[i].multiply(new Fraction(2,1));
}
return arr;
}
But thats not my Main goal I want to do it recursively so that was my approach:
public static Fraction[] mulAus(Fraction[] arr, int i)
{
if (i>= 0 && i<arr.length)
{
rekurMul(arr,i);
//return mulAus(rekurMul(arr,i-1));
}
return arr;
}
public static Fraction rekurMul(Fraction[] arr, int i)
{
if (i>= 0 && i<arr.length)
{
return arr[i].multiply(new Fraction(2,1));
return arr[i].multiply(new Fraction(2, 1)); // Does Not Work!!!
}
throw new IndexOutOfBoundsException();
}
Maybe there is someone who can Help me! Thank you for your attention.
OK Thanks to #Chaï Sarfati and also to the others trying to help me out. I now know how to multiply recursive things in an Array! I used the Methods from #Chaï Sarfati but wrote an alternative method for his "oneThirdIsPresent" which is also a recursive method : So now my working code looks like this
public static Fraction[] mulAus(Fraction[] arr)
{
if(contains(arr,arr.length-1,new Fraction(1,3)))
{
rekurMul(arr,0);
return arr;
}
throw new IllegalArgumentException("1/3 does not exist in the Input-Array");
}
public static void rekurMul(Fraction[] arr, int i)
{
if(i == arr.length)
{
return ;
}
arr[i] = arr[i].multiply(new Fraction(2,1));
rekurMul(arr,i+1);
}
The Method to check if 1 / 3 exists in the given Array.
public static boolean contains(Fraction[] arr, int i, Fraction x)
{
if (i>= 0 && i < arr.length)
{
if (arr[i].equals(x))
{ return true;}
else
{ return contains(arr, i-1,x); }
}
return false;
}
I hope other People can learn from the code.. Maybe there are better solutions but I am just starting Programming so I dont know them for now.
Bye
Assuming you have a multiplyBy(Fraction f) method that works properly in you Fraction class.
Moreover, it will be better (more readable, more time & space complexity saving) to do it iteratively.
For the sake of the example, I would do like this:
First define:
private static boolean oneThirdIsPresent(Fraction[] arr){
for (int i = 0; i < arr.length; i++) {
if(arr[i].numerator == 1 && arr[i].denominator == 3) {
return true;
}
}
return false;
}
private static void recursivelyMultBy2(Fraction[] arr, int index){
if(index == arr.length){
return;
}
arr[index] = arr[index].multiplyBy(new Fraction(2));
recursivelyMultBy2(arr, index+1);
}
In order to solve finally:
public static void multBy2IfOneThirdIsPresent(Fraction[] arr){
if(oneThirdIsPresent(arr)){
recursivelyMultBy2(arr, 0);
}else{
return;
}
}
Here's a quick example of just the recursive multiplication part:
public static void main(String[] args)
{
Fraction[] fractions = new Fraction[] {new Fraction(1,2), new Fraction(2,3), new Fraction(3,1)};
System.out.println("Fractions:");
for(Fraction f: fractions)
{
System.out.println(f);
}
System.out.println("Multiplying array by 2...");
Fraction.mulAus(fractions, new Fraction(2, 1));
for(Fraction f: fractions)
{
System.out.println(f);
}
}
Modified Fraction Class (multiplication code at the bottom):
public class Fraction
{
private int numerator; // Zaehler
private int denominator; // Nenner
public Fraction(int num, int denom)
{
if (denom != 0)
{
if (denom < 0)
{
numerator = -num;
denominator = -denom;
}
else
{
numerator = num;
denominator = denom;
}
reduce();
}
else
{
// error: division by zero
//throw new IllegalArgumentException();
}
}
private void reduce()
{
// ...
}
public Fraction()
{
numerator = 0;
denominator = 1;
}
public Fraction(int num)
{
numerator = num;
denominator = 1;
}
public String toString()
{
return numerator + " / " + denominator;
}
public void MultiplyBy(Fraction F)
{
if (F != null)
{
numerator = numerator * F.numerator;
denominator = denominator * F.denominator;
reduce();
}
}
public static void mulAus(Fraction[] arr, Fraction F)
{
if(arr != null && F != null)
{
rekurMul(arr, 0, F);
}
}
private static void rekurMul(Fraction[] arr, int i, Fraction F)
{
arr[i].MultiplyBy(F);
if (i < (arr.length - 1))
{
rekurMul(arr, ++i, F);
}
}
}
Output:

code doesn't run, gives no error messages (java, new to programming)

I'm pretty much brand new to programming, working through a class online. I am trying to write code that will tell you if a number is a square. When I run this code, it just loads for a while and then says killed. Is there something wrong with it? Usually if theres something wrong there is an error message or something, this just gives me nothing.
class Number {
int number;
public boolean isSq() {
int y = 1;
int sqNum = y*y;
while (sqNum < number) {
y++;
}
if (sqNum == number) {
return true;
} else {
return false;
}
}
}
Number myNumber = new Number();
myNumber.number = 36;
System.out.println(myNumber.isSq());
while (sqNum < number) {
y++;
}
never ends. You need to change sqNum inside the loop.
You should have included sqNum = y * y; inside the while after y++;
Check the below code
public class Number {
int number;
public boolean isSq() {
int y = 1;
int sqNum = y * y;
while (sqNum < number) {
y++;
sqNum = y * y;
}
if (sqNum == number) {
return true;
} else {
return false;
}
}
public static void main(String args[]) {
Number myNumber = new Number();
myNumber.number = 8;
System.out.println(myNumber.isSq());
}
}
or you change your isSq() as follows
public boolean isSq() {
int temp = (int) Math.sqrt(this.number);
if (this.number == temp * temp){
return true;
}else{
return false;
}
}

Java Inheritance Primes Homework

I have a multiphase homework due soon and my I'm on my last leg of it, but I'm very confused by it. The first assignment has me instantiating different Primes that all are dependent on each other and are all effected together no matter which one I refer to. The second part that I'm having trouble with is making it instantiable so that each Prime is effect independently and doing so by making a second class to show that they are independent.
My first class is this:
package project1;
public class Prime {
//Part 2: Primes
//Place your methods in here
public static void main (String[] args) {
Prime p = new Prime();
Prime p2 = new Prime();
p.getPrime();
p2.getPrime();
Prime.getPrime();
p.reset();
p2.getPrime();
p2.sumPrimes(4);
p2.getPrime();
p.getPrime();
}
static int num = 0;
static int count = 0;
public static boolean isPrime(int p) {
if (p <= 1){
return false;
}
for (int i = 2; i < p; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static int getPrime() {
while (Prime.isPrime(num) == false) {
num ++;
}
if (Prime.isPrime(num) == true) {
System.out.println(num);
num ++;
return num;
}
return num;
}
public static void reset() {
num = 0;
}
public static int reset(int n) {
num = n;
while (Prime.isPrime(num) == false) {
num ++;
}
if (Prime.isPrime(num) == true) {
return num;
}
return num;
}
public static int sumPrimes(int n) {
int sum = 0;
while (n > count) {
while (Prime.isPrime(num) == false) {
num ++;
}
if (Prime.isPrime(num) == true) {
sum += num;
count ++;
num ++;
}
}
System.out.println(sum);
return num;
}
}
I know it's not the prettiest code, but I'm a Java beginner. I only need to take this and make it so p and p2 are two separate variables by using instantiation and a new class called PrimeTest that has a main method that shows their independent. Anyone have any tips or examples I can look at?

Recursive method checking whether a row of integers is descending: return true/false

I have to write a recursive method in Java that returns true if a row is descending and false it does not.
This is what I tried, but it doesn't work properly:
ArrayList<Integer> getallen = new ArrayList();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else if (getallen.size() > 0) {
getallen.remove(0);
return isDescending(getallen);
} else {
return true;
}
} else {
return false;
}
}
I think you have unnecessary cases if the size is less than 2 you can only assume true.
Try:
public static boolean isDescending(ArrayList<Integer> getallen) {
if (getallen.size() >= 2) {
if (getallen.get(0) < getallen.get(1)) {
return false;
} else {
getallen.remove(0);
return isDescending(getallen);
}
} else {
return true;
}
}
If I had to grade this, it would get a big fat X for
Having been fraudulently asked on stackoverflow
Being quite inefficient (try running this test on a list of a million elements, then realise that removing element 0 in an ArrayList causes all elements to shift down)
Instead consider:
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0);
}
public static boolean isDescending(List<Integer> getallen, int from) {
return from >= getallen.size() - 1
|| getallen.get(from) < getallen.get(from + 1)
&& isDescending(getallen, from + 1);
}
How about little bit more efficient approach with logarithmic recursion depth? Just as an exercise.
public static void main(String[] args) {
List<Integer> getallen = new ArrayList<Integer>();
getallen.add(500);
getallen.add(400);
getallen.add(300);
getallen.add(200);
getallen.add(100);
getallen.add(0);
System.out.println(isDescending(getallen));
}
public static boolean isDescending(List<Integer> getallen) {
return isDescending(getallen, 0, getallen.size());
}
private static boolean isDescending(List<Integer> getallen,
int start, int end) {
if (end - start <= 1)
return true;
if (end - start == 2) {
return getallen.get(start) > getallen.get(start + 1);
}
int middle = (start + end - 1) / 2 + 1;
return (getallen.get(middle - 1) > getallen.get(middle)) &&
isDescending(getallen, start, middle) &&
isDescending(getallen, middle, end);
}

Recursive method to add odd numbers

I have the below snippet of code to use a recursive method to add the sum of odd numbers.
I have already coded the iterative method successfully that adds the sum of all odd numbers between n and m which are entered by the user. I'd like to reach that goal but am started slow to make sure I understand what is happening.
I know that it makes more sense to do it iteratively, however I am experimenting with the two types to see which is more efficient. I am stuck on the below as it is not doing what i want it to and i can't understand why.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
int x = add(n);
}
public static int add(int x)
{
if (x == 0)
{
return 0;
}
else
{
return (x + add(x-1));
}
}
}
I have changed the above to the below. It compiles however stops after I enter the number.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
if (n%2 == 0)
{
System.out.println("The number entered is even");
}
else
{
int x = add(n);
}
}
public static int add(int x)
{
if (x <= 0)
{
return 0;
}
else
{
return (x + add(x-2));
}
}
}
import java.util.*;
public class OddR{
public static void main (String Args [])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an odd number");
int max = s.nextInt();
if((max% 2) == 0) {
System.out.println(max + " is Even number and therefore is invalid");
}
else{
System.out.println("Enter a greater odd number");
int m = s.nextInt();
if (m <max){
System.out.println("Invalid data");
}
else{
if((m % 2) == 0) {
System.out.println(m + " is Even number and therefore is invalid");
}
else{
int data = (addodd(m)- addodd(max))+max;
System.out.print("sum:"+data);
}
}
}
}
public static int addodd(int m)
{
if(m<=0)
{
return 0;
}
if(m%2 != 0)
{
return (m+addodd(m-1));
}
else
{
return addodd(m-1);
}
}
}
This is the answer recursively of the sum of odd numbers from n to m
public int addOdds(int n) {
if (n <= 0) {
return 0;
}
if (n % 2 == 0) {
return addOdds(n - 1);
}
return x + addOdds(n - 1);
}
Take care, I never tested the code.
class Oddsum {
public int addodd(int n)
{
if(n<=0)
{
return 0;
}
if(n%2 != 0)
{
return (n+addodd(n-1));
}
else
{
return addodd(n-1);
}
}
}
public class Xyz {
public static void main (String[] v)
{
int n = 9;
Oddsum o = new Oddsum();
int data = o.addodd(n);
System.out.print("sum:"+data);
}
}
This is working fine
public static void main (String[] args){
public static int oddSum(int s){
if (s <= 0)
return 0;
else
return s + oddSum(s -2);
}
}

Categories

Resources