inspiration from Different Differences (codeforces problem 1772c) - java

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...

Related

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.

How to accept the 2d array being returned

In my below code, I'm checking whether the entered rows and columns are equal and then accepting the array and proceeding to calculate the sum of the diagonal elements. I understand that I can take only one variable for rows and columns but this is what our assignment says.
import java.util.*;
class main
{
int[][] acceptarray(int a[][]) //Accepting the 2d array
{
Scanner xd = new Scanner(System.in);
System.out.println ("Enter the elements of array : ");
for( int i =0; i <a.length; i++)
{
for(int j=0; j<a[0].length; j++)
{
System.out.println("Enter element "+(i)+","+(j));
a[i][j] = xd.nextInt();
}
}
xd.close();
return(a);
}
boolean check(int b[][]) //checking whether rows and colums are equal or not
{
if(b.length==b[0].length)
{return(true);}
else
return(false);
}
int sum(int c[][]) // Sum of the the diagonal of the matrix
{ int sum=0;
for(int i=0;i<=c.length;i++)
{
for(int j=0;j<=c[0].length;j++)
{
if(i==j)
{
sum =sum+c[i][j];
}
}
}
return(sum);
}}
class dsum
{
public static void main(String Args[])
{
Scanner xd = new Scanner(System.in);
System.out.println("Enter number of Rows");
int m = xd.nextInt();
System.out.println("Enter number of Columns");
int n = xd.nextInt();
xd.close();
int a[][] = new int [m][n];
main s = new main();
boolean p = s.check(a);
if(p)
{
System.out.print("It is a Square Matrix:\n\n");
s.acceptarray(a);
int b[][] =s.acceptarray(); //line with the error message
s.sum(b);
}
else
{
System.out.println("It's not a square matrix");
System.exit(0);
}
}
}
The error message is:
b =s.acceptarray();
^
required: int[][]
found: no argument
reason: actual and formal argument lists differ in length
For the record, I'm a newbie so I'm not aware of the all the concepts.
So, Can someone please help me out on how to accept this 2d array that is being returned by the acceptarray function. It'll help me understand the only concept I'm not able to understand since a week.
Peace.
You never declared a method acceptarray that doesn't take an argument. Try int b[][] =s.acceptarray(a);

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;
}
}

Taking Space Separated Row Inputs in a Two dimensional Array

Im relatively new to programming and i was working with a problem that requires me to read space separated integers and input them into a two dimensional array but i dont seem to understand why I am not able to do so . any hint on possible approaches will be helpful
Eg. Input will look like this
2 //FOR DIMENSION
2 3 //ROW1
4 5 // ROW 2
import java.io.*;
import java.util.*;
import java.lang.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc= new Scanner(System.in);
System.out.println("Hello World");
System.out.println("Enter Dimension of Matrix");
int N= sc.nextInt();
int[][] m=new int [N][N];
for (int i=0;i<N;i++)
{ System.out.println("Enter Elements of row "+ i);
for(int j=0;j<N;j++ )
{
m[i]=sc.nextInt();
}
}
System.out.println(m);
}
}
I tested the above code and got the following result on the console
HelloWorld.java:16: error: incompatible types: int cannot be converted to int[]
m[i]=sc.nextInt();
^
First of all, I would like to know is my thinking(approach) right?
Second, what are the possible ways to do this correctly?
here you go:
import java.io.*;
import java.util.*;
import java.lang.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Dimension of Matrix");
int N = sc.nextInt();
int[][] m = new int[N][N];
for (int i = 0; i < N; i++) {
System.out.println("Enter Elements of row " + i);
for (int j = 0; j < N; j++) {
m[i][j] = Integer.valueOf(sc.next());//replaced line with proper code
}
}
sc.close();
System.out.println(Arrays.deepToString(m));//use this api to print arrays
}
}
m is a multidimensional array meaning you must specify m[i][?]. Like so
m[i][j]=sc.nextInt();
Your logic is a little off, you want to ask the user for input at row start i, and for the other columns j. Try this and happy coding :)
for (int i=0;i<N;i++){
for(int j=0;j<N;j++){
System.out.println("Enter Elements of row "+ i);
m[i][j]=sc.nextInt();
}
}
for (int i=0;i<N;i++){
for(int j=0;j<N;j++){
System.out.print(m[i][j]);
}
System.out.println();
}

subset counting using dynamic programing in 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)));
}
}
}

Categories