Working with two unknown integers - java

Can't find out how to go further when working with two unknown integers in parameters. Have several tasks regarding this.
returning the sum between two unknown integers, the two unknown numbers have to be included in the calculation as well
returning the even numbers between the two unknown
returning the odd numbers between the two unknown
returning the prime numbers between the two unknown
I know this probably is very easy, but still can't find out how to get started.
public int method(int a, int b){
sum = 0;
??for() {
}??

public static void main(String[] args) {
System.out.println("sum: " + sum(10, 12));
System.out.println("evens: " + evens(10, 20));
System.out.println("odds: " + odds(10, 20));
System.out.println("primes: " + primes(0, 100));
}
public static int sum(int from, int to) {
int sum = 0;
for (int i = from; i <= to; i++) {
sum += i;
}
return sum;
}
public static List<Integer> evens(int from, int to) {
List<Integer> evens = new ArrayList<>();
if (from % 2 != 0) {
from++;
}
for (int i = from; i <= to; i += 2) {
evens.add(i);
}
return evens;
}
public static List<Integer> odds(int from, int to) {
List<Integer> odds = new ArrayList<>();
if (from % 2 == 0) {
from++;
}
for (int i = from; i <= to; i += 2) {
odds.add(i);
}
return odds;
}
public static List<Integer> primes(int from, int to) {
List<Integer> primes = new ArrayList<>();
boolean prime = false;
for (int i = from; i <= to; i++) {
if (isPrime(i)) {
primes.add(i);
}
}
return primes;
}
public static boolean isPrime(int n) {
for(int i = 2; 2 * i < n; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}

Related

Type errors when sorting my array of objects

I need to sort my array of Money objects in ascending order, but I get 3 compiler errors.
TestMoney.java:44: error: bad operand types for binary operator '<'
if (list[j] < list[min]) {
^
first type: Money
second type: Money
TestMoney.java:50: error: incompatible types: Money cannot be converted to int
final int temp = list[i];
^
TestMoney.java:52: error: incompatible types: int cannot be converted to Money
list[min] = temp;
^
class TestMoney
{
public static void main(String [] args)
{
Money[] list = new Money[15];
for(int i =0; i<15; i++)
{
int dollar =(int) (Math.random() * 30 + 1);
int cent = (int) (Math.random() * 100);
list[i] = new Money(dollar, cent);
}
sortArray(list);
printArray(list);
}
public static void printArray(Money[] list)
{
for(int i =0; i <list.length; i++)
{
if(i%10 ==0)
{
System.out.println();
}
System.out.print(" " + list[i]);
}
}
public static void sortArray(Money[] list)
{
int min;
for (int i = 0; i < list.length; i++) {
// Assume first element is min
min = i;
for (int j = i + 1; j < list.length; j++) {
if (list[j] < list[min]) {
min = j;
}
}
if (min != i) {
final int temp = list[i];
list[i] = list[min];
list[min] = temp;
}
System.out.println(list[i]);// I print the in ascending order
}
}
}
class Money
{
private int dol;
private int cen;
Money()
{
dol = 0;
cen = 00;
}
Money(int dol,int cen)
{
int remainder = cen % 100;
int divisor = cen / 100;
this.dol = dol+ divisor;
this.cen = remainder;
}
public int getDollors(int dol)
{
return dol;
}
public int getCents(int cen)
{
return cen;
}
public void setDollors(int d)
{
dol = d;
}
public void setCents(int c)
{
cen = c;
}
public Money addMoney(Money m)
{
int d = this.dol + m.dol;
int c = this.cen + m.cen;
return new Money(d, c);
}
public int compareTo(Money m)
{
if(this.dol<m.dol && this.cen<m.cen)
return -1;
else if(m.dol<this.dol && m.cen<this.cen )
return 1;
return 0;
}
public Money subtract(Money m)
{
int cents1 = this.dol*100 + this.cen;
int cents2 = m.dol *100 + m.cen;
int cents = cents1 -cents2;
return new Money(cen/100,cen%100);
}
public String toString()
{
return String.format("$%d.%02d", this.dol,this.cen);
}
}
That's because you are trying to compare two Money objects with < operator which applies to Numbers only, you need to replce the following:
if (list[j] < list[min]) {
with
if (list[j].getDollors() < list[min].getDollors()
|| (list[j].getDollors() == list[min].getDollors() && list[j].getCents() < list[min].getCents())) {
Also, you don't need your getters to accept an argument, they can be zero argument methods as they just return a value.
Another way, maybe, is using Comparator interface, like this:
public class Money implements Comparator<Money>{
int n; //as an example, compare two object by them "n" variable
#Override
public int compare(Money o1, Money o2) {
int result;
if (o1.n > o2.n)
result = 1; //greater than case
else
result = o1.n < o2.n ? -1 // less than case
: 0; // equal case
return result;
}
}
In the compare method you can use the criteria of gt-ls-eq based on amount of money.
Finally do:
for (int j = i + 1; j < list.length; j++) {
if (list[j].compare(list[min]) < 0) { //you ask if is greater, less,
//or equal than 0
min = j;
}
}

Java - Recursion sum of number and how it work

I am trying to write a recursive function that when I call with number 5 for example then the function will calculate the sum of all digits of five.
1 + 2 + 3 + 4 + 5 = 15
The current code always returns 0, how can the amount each time the n?
public class t {
public static void main(String[] args) {
System.out.println(num(5));
}
public static int num(int n) {
int sum = 0;
sum += n;
if (n == 0)
return sum;
return num(n - 1);
}
}
thank you.
Instead of setting the sum to 0 you can -
Do this:
public int sumUp(int n){
if (n==1)
return 1;
else
return sumUp(n-1)+n;
}
The problem is you set the sum always 0.
public static void main(String[] args) {
System.out.println(num(5, 0));
}
public static int num(int n, int sum) {
if (n == 0) {
return sum;
}
sum += n;
return num(n - 1, sum);
}
public static int withRecursion(List<Integer> list) {
int size = list.size();
int a=0;
if(list.isEmpty() == true) {
return 0;
}else {
a = a + list.get(0) + withRecursion(list.subList(1, size));
return a;
}
}

Find smallest number K , if exists, such that product of its digits is N. Eg:when N = 6, smallest number is k=16(1*6=6) and not k=23(2*3=6)

I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);

Sum of 32 bits after inverting bits, final result going from binary to decimal

If my input is 1. Then 1 as 32 bits in binary is 00000000000000000000000000000001. If I invert the bits, its 11111111111111111111111111111110. And if I convert this inverted bit number from binary to decimal, I should get 4294967294. I wrote the following program to do this, but my final sum is wrong despite me being able to invert the bits correctly. I'm getting -3.
Here is my code:
public class FlippingBits {
public static void main(String[] args) {
FlippingBits fpb = new FlippingBits();
int i = 1;
int index = 0;
int[] bitArray = new int[32];
fpb.convertToBin(i, bitArray, index);
}
private void convertToBin(int decimalInput, int[] unsigned32, int index) {
if (decimalInput <= 1) {
unsigned32[index++] = flipBit(decimalInput);
for (int i = index; i < unsigned32.length; i++) {
unsigned32[i] = 1;
}
printArray(unsigned32);
System.out.println();
sumBit(unsigned32);
return;
}
int remainder = decimalInput % 2;
unsigned32[index] = flipBit(remainder);
index++;
convertToBin(decimalInput >> 1, unsigned32, index);
}
private void sumBit(int[] unsigned32) {
int sum = 0;
for (int i = 0; i < unsigned32.length; i++) {
sum += unsigned32[i] * (int) Math.pow(2, i);
}
System.out.println(sum);
}
private int flipBit(int remainder) {
if (remainder == 1) {
return 0;
} else {
return 1;
}
}
private void printArray(int[] unsigned32) {
for (int i = 0; i < unsigned32.length; i++) {
System.out.print(unsigned32[i]);
}
}
}
I'm not sure what's happening with my sumBit(int[]) method. I'm pretty sure I haven't forgotten how to convert from binary to decimal.
You aren't actually using unsigned ints. You are overflowing your variable.
This should help
public class FlippingBits {
public static void main(String[] args) {
FlippingBits fpb = new FlippingBits();
int i = 1;
int index = 0;
int[] bitArray = new int[32];
fpb.convertToBin(i, bitArray, index);
}
private void convertToBin(int decimalInput, int[] unsigned32, int index) {
if (decimalInput <= 1) {
unsigned32[index++] = flipBit(decimalInput);
for (int i = index; i < unsigned32.length; i++) {
unsigned32[i] = 1;
}
printArray(unsigned32);
System.out.println();
sumBit(unsigned32);
return;
}
int remainder = decimalInput % 2;
unsigned32[index] = flipBit(remainder);
index++;
convertToBin(decimalInput >> 1, unsigned32, index);
}
private void sumBit(int[] unsigned32) {
long sum = 0;
for (int i = unsigned32.length - 1; i >= 0; i--) {
sum += unsigned32[i] * (int) Math.pow(2, i);
}
System.out.println(sum);
}
private int flipBit(int remainder) {
if (remainder == 1) {
return 0;
} else {
return 1;
}
}
private void printArray(int[] unsigned32) {
for (int i = unsigned32.length - 1; i >= 0; i--) {
System.out.print(unsigned32[i]);
}
}
}
Java int data type is a 32-bit signed two's complement, see http://www.cs.uwm.edu/~cs151/Bacon/Lecture/HTML/ch03s09.html for more info

Make And Show All Permutations of An Integer Array [duplicate]

This question already has answers here:
Algorithm to find next greater permutation of a given string
(14 answers)
Closed 8 years ago.
I am currently making a Permutation class for java. One of my methods for this class, is advance(), where the computer will take the array, and then display all permutations of the array.
So, for example, if I give the array {0,1,2,3,4,5}, or the number 6, it should give me from 012345.....543210.
Here is the code I have so far:
import java.util.*;
public class Permutation extends java.lang.Object {
public static int[] permutation;
public static int[] firstPerm;
public static int[] lastPerm;
public static int length;
public static int count;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public Permutation(int n) {
length = n;
permutation = new int[length];
for (int i = 0; i < length; i++) {
permutation[i] = i;
}
}
public Permutation(int[] perm) {
length = perm.length;
permutation = new int[length];
boolean[] t = new boolean[length];
for (int i = 0; i < length; i++) {
if (perm[i] < 0 || perm[i] >= length) {
throw new IllegalArgumentException("INVALID ELEMENT");
}
if (t[perm[i]]) {
throw new IllegalArgumentException("DUPLICATE VALUES");
}
t[perm[i]] = true;
permutation[i] = perm[i];
}
}
public void advance() {
}
public int getElement(int i) {
return permutation[i];
}
public boolean isFirstPerm() {
firstPerm = new int[permutation.length];
for (int i = 0; i < permutation.length; i++) {
firstPerm[i] = permutation[i];
}
Arrays.sort(firstPerm);
if (Arrays.equals(firstPerm, permutation)) {
return true;
} else {
return false;
}
}
public boolean isLastPerm() {
lastPerm = new int[firstPerm.length];
for (int i = 0; i < firstPerm.length; i++) {
lastPerm[i] = firstPerm[firstPerm.length - 1 - i];
}
if (Arrays.equals(permutation, lastPerm)) {
return true;
} else {
return false;
}
}
public static Permutation randomPermutation(int n) {
if (n <= 0) {
throw new IllegalArgumentException("INVALID NUMBER");
} else {
length = n;
permutation = new int[length];
for (int i = 0; i < length; i++) {
permutation[i] = i;
}
Collections.shuffle(Arrays.asList(permutation));
return new Permutation(permutation);
}
}
public void reset() {
Arrays.sort(permutation);
}
public boolean isValid(int[] perm) {
boolean[] t = new boolean[length];
for (int i = 0; i < length; i++) {
if (perm[i] < 0 || perm[i] >= length) {
return false;
}
if (t[perm[i]]) {
return false;
}
}
return true;
}
public int[] toArray() {
return permutation;
}
public String toString() {
StringBuffer result = new StringBuffer();
for (int i = 0; i < permutation.length; i++) {
result.append(permutation[i]);
}
String perms = result.toString();
return perms;
}
public static long totalPermutations(int n) {
count = 1;
for (int i = 1; i <= n; i++) {
count = count * i;
}
return count;
}
}
As you can see, the advance() method is the last thing I need to do, but I can't figure it out. Any help will be grand.
One of methods you can employ is:
Fix the first element and recursively find all permutations of rest of the array.
Then change the first elements by trying each of the remaining elements.
Base case for recursion is when you travel the entire length to get 0 element array. Then, either print it or add it to a List which you can return at the end.
public void advance() {
int[] temp = Arrays.copyOf(arr, arr.length);
printAll(0,temp);
}
private void printAll(int index,int[] temp) {
if(index==n) { //base case..the end of array
//print array temp here
}
else {
for(int i=index;i<n;i++) {//change the first element stepwise
swap(temp,index,i);//swap to change
printAll(index+1, temp);//call recursively
swap(temp,index,i);//swap again to backtrack
}
}
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
The way your code looks right now, it sounds like you want to be able to control the permutation class externally, rather than only supporting the one operation of printing all the permutations in order.
Here's an example of how to calculate a permutation.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
public static int factorial(int x) {
int f = 1;
while (x > 1) {
f = f * x;
x--;
}
return f;
}
public static List<Integer> permute(List<Integer> list, int iteration) {
if (list.size() <= 1) return list;
int fact = factorial(list.size() - 1);
int first = iteration / fact;
List<Integer> copy = new ArrayList<Integer>(list);
Integer head = copy.remove(first);
int remainder = iteration % fact;
List<Integer> tail = permute(copy, remainder);
tail.add(0, head);
return tail;
}
public static void main(String[] args) throws IOException {
List<Integer> list = Arrays.asList(4, 5, 6, 7);
for (int i = 0; i < 24; i++) {
System.out.println(permute(list, i));
}
}
}
Just to elaborate, the idea behind the code is to map an integer (iteration) to a particular permutation (ordering of the list). We're treating it as a base-n representation of the permutation where each digit represents which element of the set goes in that position of the resulting permutation.
For example, if we're permuting (1, 2, 3, 4) then we know there are 4! permutations, and that "1" will be the first element in 3! of them, and it will be followed by all permutations of (2, 3, 4). Of those 3! permutations of the new set (2, 3, 4), "2" will be the first element in 2! of them, etc.
That's why we're using / and % to calculate which element goes into each position of the resulting permutation.
This should work, and it's pretty compact, only drawback is that it is recursive:
private static permutation(int x) {
if (x < 1) {
throw new IllegalArgumentException(x);
}
LinkedList<Integer> numbers = new LinkedList<>();
for (int i = 0; i < x; i++) {
numbers.add(i);
}
printPermutations(numbers, new LinkedList<>());
}
private static void printPermutations(
LinkedList<Integer> numbers, LinkedList<Integer> heads) {
int size = numbers.size();
for (int i = 0; i < size; i++) {
int n = numbers.getFirst();
numbers.removeFirst();
heads.add(n);
printPermutations(numbers, heads);
numbers.add(n);
heads.removeLast();
}
if (numbers.isEmpty()) {
String sep = "";
for (int n : heads) {
System.out.print(sep + n);
sep = " ";
}
System.out.println("");
}
}

Categories

Resources