subset counting using dynamic programing in java - java

I am trying to write a java code for getting the total number of combinations of subset for which sum is equal to x where n is the number of elements using recursion ..I wrote the code but it seems it needs to be more optimized since its taking a lot of time to get the result
import java.util.*;
class subset
{
public static void main(String[] args)
{
int n,x,z;
int m[]=new int[30];
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
x=sc.nextInt();
for(int i=0;i<n;i++)
{
m[i]=sc.nextInt();
}
z=func(0,m,x);
System.out.println(z);
}
static int func(int i,int m[],int w)
{
if(i==m.length)
{
return 0;
}
if(m[i]==w)
return (1+func(i+1,m,w));
else
{
return((func(i+1,m,w-m[i])+func(i+1,m,w)));
}

well I found out how to optimize it.I simply sorted out the inputs and the put a constraint the if the sum calculated by the func function becomes greater than the subset sum(i.e x) it will discard it.
import java.util.*;
class subset
{
public static void main(String[] args)
{
int n,x,z;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
x=sc.nextInt();
int m[]=new int[n];
long b=System.currentTimeMillis();
for(int i=0;i<n;i++)
{
m[i]=sc.nextInt();
}
Arrays.sort(m);
for(int i=0;i<m.length;i++)
{
System.out.print(" "+m[i]+" " );
}
z=func(0,m,x);
System.out.println(z);
System.out.println(System.currentTimeMillis()-b);
}
static int func(int i,int m[],int w)
{
if(i==m.length||m[i]>w)
{
return 0;
}
if(m[i]==w)
return (1+func(i+1,m,w));
else
{
return((func(i+1,m,w-m[i])+func(i+1,m,w)));
}
}
}

Related

inspiration from Different Differences (codeforces problem 1772c)

link to problem
import java.util.Arrays;
import java.util.Scanner;
class Codechef { static boolean test(int[]a,int n){
for(int i=0;i<n;i++){
if(a[i]-a[i+1]>0)
System.out.println("not si");
return false;
}
return true;
}
static int[] array(int[]a,int n){
int[] a1=new int[n-1];
if(test(a,n )){
for(int i=0;i<n-1;i++){
a1[i]=a[i+1]=a[i];
}
}
return a1;
}
static int type(int[]a,int n){
int c=0;
int []k=array(a, n);
Arrays.sort(k);
for(int i=0;i<n-2;i++){
if(k[i]!=k[i+1])c++;
}
return c;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Array & no of elements");
int n=in.nextInt();
int []a=new int[n];
for(int i=0;i<n;i++)
a[i]=in.nextInt();
int c=type(a, n);
System.out.println(c);
}`
the following code gives the output:
Array & no of element
5
0
2
8
10
16
0 (output)
clearly not the desired results. So where am i going wrong? please enlighten me.
Ive tried a set of "nested" methods and was expecting for the value of c to be greater than zero...

Why below code throwing IllegalFormatConversionException error?

import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
//your code here
Scanner sc =new Scanner(System.in);
int N=sc.nextInt();
int[] arr=new int[N];
for(int i=0;i<N;i++)
arr[i]=sc.nextInt();
Solution s=new Solution();
s.Answer(arr,N);
}
}
class Solution
{
public void Answer(int [] arr,int N)
{
int p=0,ne=0,z=0,i=0;
while(i<arr.length)
{
if(arr[i]>0)
p++;
else if(arr[i]<0)
ne++;
else z++;
i++;
}
System.out.printf("%1.4f \n", p/N);
System.out.printf("%1.4f \n", ne /N);
System.out.printf("%1.4f\n ", z / N);
}
}
I have written the above code for the question Given an array of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers, and zeros in the array up to four decimal places.
Examples:
Input: a[] = {2, -1, 5, 6, 0, -3} 
Output: 0.5000 0.3333 0.1667 
There are 3 positive, 2 negative, and 1 zero. Their ratio would be positive: 3/6 = 0.5000, negative: 2/6 = 0.3333, and zero: 1/6 = 0.1667.
I compiled the above code but it showing an Illegalformatexception. But I am not getting why it is showing like that.
I checked all syntaxes which I have used in this code. but I couldn't find that problem.
please help me in solving this plus-minus problem.
package ddd;
import java.util.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
//your code here
Scanner sc =new Scanner(System.in);
int N= sc.nextInt();
int[] arr=new int[N];
for(int i=0;i<N;i++)
arr[i]=sc.nextInt();
Solution s=new Solution();
s.Answer(arr,N);
}
}
class Solution
{
public void Answer(int [] arr,int N)
{
int p=0,ne=0,z=0,i=0;
while(i<arr.length)
{
if(arr[i]>0)
p++;
else if(arr[i]<0)
ne++;
else z++;
i++;
}
System.out.printf("%1.4f \n", p/(float)N);
System.out.printf("%1.4f \n", ne/(float)N);
System.out.printf("%1.4f\n ", z/(float)N);
}
}
I think just converting N to float would solve your problem.

This is regarding the NoSuchElementException

i tried the below code but my loop is going infinitely.Can someone please helpme with this
import java.util.Scanner;
public class nosuchelement {
public static void main(String[] args) {
sum();
}
static long sum() {
Scanner sc=new Scanner(System.in);
System.out.println("The length of the array is:");
int length=sc.nextInt();
long a[]=new long[length];
System.out.println("Enter the numbers of the array");
long sum=0;
for(int i=0;i<length;i++) {
while(sc.hasNextLong())
{
sum +=sc.nextLong();
}
}
return sum;
}
}
what I need is to find the sum of the long type numbers given in the array
These nested loops:
for(int i=0;i<length;i++) {
while(sc.hasNextLong()) {
//..
}
}
Should be
for(int i=0;i<length && sc.hasNextLong();i++) {
// ...
}
As you have it currently, you never stop the first iteration of the for loop until the stream is closed; and then all the subsequent iterations of the for loop do nothing, because hasNextLong() returns false.
Problem was with the while loop used. So just remove while(sc.hasNextLong())
import java.util.Scanner;
public class nosuchelement
{
public static void main(String[] args)
{
System.out.println(sum());
}
static long sum()
{
Scanner sc = new Scanner(System.in);
System.out.println("The length of the array is:");
int length = sc.nextInt();
long a[] = new long[length];
System.out.println("Enter the numbers of the array");
long sum = 0;
for (int i = 0; i < length; i++)
{
sum += sc.nextLong();
}
return sum;
}
}

Getting Odd numbers from Array

I've been working on this program and am currently stuck. The HW prompt is to prompt a user to input numbers, save it as an array, find the number of odd numbers & the percentages then display those values back to the user.
Currently I am trying to write to part of the code that finds the percentage of the odd numbers in the array but the return isn't displaying and i just cant figure it out. Any ideas? Thank you!
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
int inputs = Integer.parseInt(console.next());
int[] arraysize = new int[inputs];
Oddvalues(arraysize);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i = 1; i < size.length; i++) {
if(size[i] % 2 != 0) {
i++;
}
}
return countOdd;
}
}
Consider the following code, which appears to be working in IntelliJ locally. My approach is to read in a single line from the scanner as a string, and then to split that input by whitespace into component numbers. This avoids the issue you were facing of trying to directly create an array of integers from the console.
Then, just iterate over each numerical string, using Integer.parseInt(), checking to see if it be odd.
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
String nextLine = console.nextLine();
String[] nums = nextLine.split(" ");
int oddCount = 0;
for (String num : nums) {
if (Integer.parseInt(num) % 2 == 1) {
++oddCount;
}
}
double oddPercent = 100.0*oddCount / nums.length;
System.out.println("Total count of numbers: " + nums.length + ", percentage odd: " + oddPercent);
}
In the function Oddvalues you promote i instead of promoting countOdd. And the loop should start from 0 not 1.
Try this
import java.util.*;
import java.lang.*;
import java.io.*;
public class OddVals{
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int[] array = new int[sc.nextInt()]; // Get the value of each element in the array
System.out.println("Please input a series of numbers");
for(int i = 0; i < array.length; i++)
array[i] = sc.nextInt();
System.out.println("Number of Odds:" +Oddvalues(array));
printOdd(array);
}
public static int Oddvalues (int[] size) {
int countOdd = 0;
for (int i=0; i < size.length; i++){
if(size[i]%2 != 0)
++countOdd;
}
return countOdd;
}
public static void printOdd(int[] arr)
{
for(int i=0;i<arr.length;++i)
{
if(arr[i]%2==1)
System.out.print(arr[i]+" ");
}
}
import java.util.*; // import java course for Scanner class
public class Integers {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<Integer>();
Scanner console = new Scanner(System.in);
System.out.println("Please input a series of numbers");
while (console.hasNext())
{
String str = console.next();
try
{
if(str.equals("quit")){
break;
}
int inputs = Integer.parseInt(str);
System.out.println("the integer values are" +inputs);
intList.add(inputs);
}
catch (java.util.InputMismatchException|NumberFormatException e)
{
console.nextLine();
}
}
console.close();
double d = Oddvalues(intList);
System.out.println("the percent is" +d);
}
public static double Oddvalues (List<Integer> list) {
int count = 0;
for( Integer i : list)
{
if(!(i%2==0))
{
count++;
}
}
double percentage = (Double.valueOf(String.valueOf(count))/ Double.valueOf(String.valueOf(list.size())))*100;
return percentage;
}
}
If this helps

Use Variable Which is in main method in Another Method

I'm trying to create a simple program to output the number of stars entered by user. I'm trying to learn how to use more than one method to do this
Here's my code
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
}
public static void Loop ()
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
The problem I'm facing is that in the Loop method, I am unable to use the variable n
Is there a way to use a variable which is in the main method, in another one?
Ty
-Pingu
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n); //calls Loop function and passes parameter n
}
public static void Loop(int n) //this function now expects a number n
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
simply pass it as parameter:
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
Loop(n);
}
public static void Loop (int count)
{
for (int counter = 1; counter <= count; counter++)
{
System.out.println("*");
}
}
Pass it as a paramteer
import java.util.Scanner;
public class Alpha
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter no. of stars");
n = input.nextInt();
loop(n); // added this
}
public static void loop (int n) // changed here
{
for (int counter = 1; counter <= n; counter++)
{
System.out.println("*");
}
}
}
I think you should use it as a instance variable and for better understanding name your class like StarClass it can provide better understanding. Good programming practice.
But you should avoid unneccesserily making instance variable without any logic behind it.
I also think you could declare n as a public variable.
That should make it accessible throughout the code.
public int n;
But I guess that passing it as parameter is a better practice, since you don't create a deppendance inside your code. What I mean is, if something changes with the variable you break the function. It's good practice to always keep things "modular" in your code, so it makes it more resilient to changes and debugging.
It's better if you get used to it from the beggining =)
Two ways.. one has been posted already as answer and the other one would be using the variable as a field. This way you can access (and modify) it in every method without having to pass it on.
public class Alpha
{
static int n;
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter no. of stars");
n = input.nextInt();
loop();
}
public static void loop ()
{
for (int counter = 0; counter < n; counter++)
{
System.out.println("*");
}
}
}
And please start method names with lowercase and counting with 0. It's common practise and it helps a lot to use the standards right from the beginning.
Like this you can use variable from different methods in different methods
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum=0;
int a=Sum(sum);
System.out.println("The Average of the numbers is: "+a);
}
public static int Sum(int sum) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the total count of number for Average: ");
int a=sc.nextInt();
for(int i=1;i<=a;i++) {
System.out.println("Enter the"+i+"Number: ");
int b=sc.nextInt();
sum+=b;
}
int avg=sum/a;
return avg;
}

Categories