How to call to function - java

I'm new in java.
I need to write a function that gets array A (The array size is n) and return true only if:
A[x]>A[y]-10 (While 0≤x<n 0≤y<n x≠y)
for example this array return true: A={1, 2, 5, 7, 9, 3}
Ok so here's my code, I'm trying to call the function "checkIfLargebyTen" but it doesn't work. what's wrong?
package Ass2;
public class Part0 {
public static boolean forAllExists(int[] A) {
boolean ans = true;
for(int i=0; i<A.length; i++)
{
if(checkIfLargebyTen(A,i)==false)
{
ans=false;
}//if
}//for
//Boolean function that check if A[x]>A[y]-10
boolean checkIfLargebyTen(int[] arr, int x) {
boolean ans=false;
for(int y=0; y<arr.length && ans==false; y++)
{
if (x!=y && arr[x]>arr[y]-10)
{
ans=true;
}//if
}//for
return ans;
}//CheckFunction
return ans;
}//AllExixstsFunction
}//class

In Java, you cannot define a method within a method. You should close the 'forAllExistsmethod before declaring thecheckIfLargeByTen` one:
public class Part0 {
public static boolean forAllExists(int[] A) {
boolean ans = true;
for(int i=0; i<A.length; i++)
{
if(checkIfLargebyTen(A,i)==false)
{
ans=false;
}//if
}//for
return ans; // return missing in the OP
} // close forAllExists - missing in the OP
//Boolean function that check if A[x]>A[y]-10
static boolean checkIfLargebyTen(int[] arr, int x) {
boolean ans=false;
for(int y=0; y<arr.length && ans==false; y++)
{
if (x!=y && arr[x]>arr[y]-10)
{
ans=true;
}//if
}//for
return ans;
}//CheckFunction
}//class

I guess you could make function which goes through all the values with two for loops and as soon as some pair (x, y) does not fit your condition, return false. I think you are doing the same thing, but this is all in one method.
public static boolean checkSomething(int[] arr)
{
for(int i = 0;i < arr.length;i ++)
{
for(int j = 0;j < arr.length;j ++)
{
if(arr[i]<=arr[j]-10) return false;
}
}
return true;
}
Jesse.

Related

boolean from array - function in java, input from command line

I have a problem, which read N numbers from the command line, and I want to check if all those numbers are the same.
This is my code
class q2 {
public static boolean check(int[] arr) {
for (int i = 0; i < arr.length-1; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[i]==arr[j]) return false;
}
}
return true;
}
public static void main(String[] args) {
int[] arr = new int[args.length];
boolean result = check(arr);
System.out.println(result);
}
}
but in any case (but no input at all) it return false and I don't know where is the mistake.
If you are passing the values from the command line, you need to add those values into the array that you will pass into the check method:
public static void main(String[] args) {
int[] arr = new int[args.length];
for(int i = 0; i < arr.length; i++){
arr[i] = Integer.parseInt(args[i]);
}
boolean result = check(arr);
System.out.println(result);
}
You can simplify your check method e.g. you do not need a double loop. Just compare the current element with the next one as shown below:
public static boolean check(int[] arr) {
for (int i =0;i<arr.length-1;i++)
if (arr[i] != arr[i + 1])
return true;
return false;
}

Why do I have to initialise variable?

My code is checking if a given string is in a certain format. The first char of the string has to be an uppercase letter and the rest of the string has to be any number that is from 1 to given dimension.
If the first char of the string contains a string from the alphabet array, then the code checks if the rest of the string contains a number from the numbers array. To be a valid coordinate both conditions must be true, if one of them is false it is not a valid coordinate. I want to return the boolean isValidCoordinate but however IntelliJ is telling me that I have to initialise isValid coordinate. Why do I have to initialise it, the boolean expression depends on the 'if' conditions.
Thanks.
public static boolean validCoordinate(String coordinate, int dimension) {
boolean isValidCoordinate;
String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int [] numbers = new int [dimension];
int one = 1;
for(int i = 0; i < dimension; i++){
numbers[i] = one + i;
}
for(int i = 0; i < dimension; i++){
if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
for(int j = 0; j < dimension; j++) {
if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
isValidCoordinate = true;
}
else {
isValidCoordinate = false;
}
}
}
else {
isValidCoordinate = false;
}
}
return isValidCoordinate;
}
This is my final code:
public static boolean validCoordinate(String coordinate, int dimension) {
boolean isValidCoordinate;
String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int [] numbers = new int [dimension];
int one = 1;
for(int i = 0; i < dimension; i++){
numbers[i] = one + i;
}
for(int i = 0; i < dimension; i++){
if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
for(int j = 0; j < dimension; j++) {
if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
isValidCoordinate = true;
}
else {
isValidCoordinate = false;
}
}
}
else {
isValidCoordinate = false;
}
}
return true;
}
All the cases inside the for loop are covered, but not the case when dimension is 0.
The method will go straight to return isValidCoordinate;, where the variable isn't initialized yet.
It is possible that your for loop will never be entered (for example, if dimension == 0). In that case, you will never assign a value to isValidCoordinate, but you will attempt to return the value of that variable in the last statement of your method.
What would be the value of isValidCoordinate in such case?
It wouldn't have any value.
Therefore, you are forced by the compiler to assign an initial value to isValidCoordinate, to make sure that it has a value before it is accessed.
EDIT:
Following your comments, I suggest you eliminate the boolean variable, and use return statements instead:
public static boolean validCoordinate(String coordinate, int dimension) {
String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int [] numbers = new int [dimension];
int one = 1;
for(int i = 0; i < dimension; i++){
numbers[i] = one + i;
}
for(int i = 0; i < dimension; i++){
if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
for(int j = 0; j < dimension; j++) {
if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
return true;
}
}
}
}
return false;
}
This way you don't have to worry about breaking out of nested loops when the boolean variable is set to true.
import java.util.regex.*;
public static boolean validCoordinate(String coordinate, int dimension)
{
Pattern p = Pattern.compile("[A-Z]+");
Matcher m = p.matcher(coordinate);
return m.matches();
}

Calculating the 10001 prime number, no output is printed

public class Prime
{
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
}
Whenever I run this code, no result is printed out. I'm assuming its because the code is inefficient, but I don't know what is wrong with this code.
Your problem is that you don't reset flag to true before the for loop; so once it is false, it remains false, so counter is never incremented, meaning the while loop guard never becomes false.
This is an example of why you should declare variables in the tightest possible scope (i.e. inside the while loop).
while(counter < 10001)
{
int flag = true;
for (...) {...}
if (flag) { counter++; }
// ...
}
It's also an example of why you should make sure your code is correct before you think about whether it is efficient. Had you debugged the code (or even just added in a few System.out.printlns), you could have found that it wasn't actually doing the right thing.
As mentioned by #AndyTurner you should declare flag = true; in while loop and also there is a slight error in your logic for finding the prime number.
You are incrementing the num after it is checked for prime. So, if your 3rd prime is 5, then it will print 6 as the answer. lly, if your 10001th prime is X, then it will print X + 1 as the answer.
I have posted the correct logic for your problem below. I hope it helps you.
public class Main
{
public static void main(String [] args)
{
int num = 2;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
num++;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
}
System.out.println(num);
}
}
Its not printing cause its going in infinite loop as counter is not incremented once flag become false
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
Try this. hope it helped

Not able to find possible solutions for N-Queens puzzle

I am trying to find all possible solutions for N-Queens puzzle. I have to print single queen on each row, and no two queens should be adjacent to each other like no one or more queens diagonally, no one or more queens in a same row, no one or more queens in a same column.
I have written the algorithm and think that most part of it is correct, but the solutions are not getting printed. I don't understand why. I have spent a lot of time on this.
Any help will be appreciated.
Following is my code:
public class NQueens {
int[] x;
public NQueens(int n) {
x = new int[n];
} // CONSTRUCTOR
public void printQueens(int[] x) {
int N = x.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (x[i] == j) {
System.out.print("Q ");
} else {
System.out.print("* ");
}
}
System.out.println();
}
System.out.println();
}
//Promising method
public boolean canPlaceQueen(int r, int c) {
for (int i = 0; i < r; i++) {
if (x[i] == c || (i - r) == (x[i] - c) ||(i - r) == (c - x[i]))
{
return false;
}
}
return true;
}
//permute method
public void placeNqueens(int r, int n) {
for (int c = 0; c < n; c++) {
if (canPlaceQueen(r, c)) {
x[r] = c;
if (validSol(r,n)) {
printQueens(x);
} else {
placeNqueens(r + 1, n);
}
}
}
}
public boolean validSol(int r, int n){
if(r== n) {
return true;
}
else {
return false;
}
}
public void callplaceNqueens() {
placeNqueens(0, x.length);
}
public static void main(String args[]) {
NQueens Q = new NQueens(8);
Q.callplaceNqueens();
}
}
Your code looks fine. It is only missing a key check in the validSol method.
Change the validSold method to the following and your code should work fine.
public boolean validSol(int r, int n){
if(r== n-1) {
return true;
}
else {
return false;
}
}
Let me know if this works for you.

Core Java Practical Questions

A Test array has the following property:
a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...
The length of a Test array must be n*(n+1)/2 for some n.
Write a method named isTestArray that returns 1 if its array argument is a Test array, otherwise it returns 0. The function signature is:
int isMadhavArray(int[ ] a)
Example:
This is what I have tried:
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a){
boolean isEq=true;
for(int i=0;i<a.length;i++){
int n=i, value=a.length;
int equation=n*(n+1)/2;
if(value==equation)
{
for(int x=0,y=1;y<a.length;x++,y++){
if(a[0]==a[x]+a[y]){
//having problem over here :(
}
}
}
else
isEq=false;
}
if(isEq)
return 1;
else
return 0;
}
}
Number of elements in sum increases by 1 in every portion.
You should do 2 things:
Write a method that will calculate sum of N elements starting from K position in array
Increment i with the number of the smallest portion in iteration
example code:
int portionSize = 1; // number of elements to sum
int position = 0; // index of first element
while (position + 2 * portionSize + 1 < array.length) { // condition for last iteration
if (sum(position, portionSize) != sum(position + portionSize, portionSize + 1) {
return false; // if not equal, return immediately
}
position += portionSize;
portionSize++;
}
Here is my attempt for your troubling inner for loop. Because each time you loop, you increment the number of indexes you need to add by one, so I think you need another nested loop like this. I know it is ugly. Can't blame me, I am a beginner.
public class TestArray {
public static void main(String[] args) {
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a) {
boolean isEq = false;
for(int i=0; i < a.length; i++) {
int n=i, value = a.length;
int equation= n*(n+1)/2;
if (value==equation) {
int index = 1;
for (int x = 1; x < a.length; x++) {
int total = 0;
for (int y = index, count = 0; count < x+1; y++, count++) {
if (y!= a.length) {
total += a[y];
if (total == a[0])
isEq = true;
else
isEq = false;
index++;
}
else
break;
}
}
}
}
if (isEq)
return 1;
else
return 0;
}
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1}));
System.out.println(isTestArray(new int[] {3, 1, 2, 3, 0}));
}
static int isTestArray(int[] a){
boolean isEq=false, isEx=false;
int equation=0,value=a.length;
//for equation check
for(int n=0;n<value;n++){
equation=n*(n+1)/2;
if(value==equation){
isEx=true;
break;
}
}
//if equation is true
if(isEx)
{
int x=1,y=3,c=0,sum=0;
do{
for(int I=x,J=y;I<J;I++){
sum=sum+a[I];
}
if(a[0]==sum){
isEq=true;
sum=0;
}
else{
isEq=false;
break;
}
c++;
x=y;
y=x+2+c;
}while(x<a.length);
}
//last operation of return
if(isEq)
return 1;
else
return 0;
}
}
import java.io.*;
public class StackQues1{
static boolean flag = true;
static int arrLength = 0;
public static void main(String args[]){
Console c = System.console();
System.out.println("Enter the length of array - ");
arrLength = Integer.parseInt(c.readLine());
//Let max val of n<=20
//To check n(n+1)/2
boolean nFlag = false;
for(int n=1;n<=20;n++){
if(arrLength == (n*(n+1))/2){
nFlag = true;
}
}
if(!nFlag){
System.out.println("Length of array is not in the form of (n*(n+1))/2");
}else{
int arr[] = new int[arrLength];
System.out.println("Enter the elements of array - ");
for(int i=0;i<arr.length;i++){
arr[i] = Integer.parseInt(c.readLine());
}
System.out.println("Returned value = "+isTestArray(arr));
}
}
//Logic Implementation
public static int isTestArray(int[] arr){
int sum = 0;
int noOfElements=0;
for(int i=0;i<arr.length;){
noOfElements++;
sum=0;
for(int j=1;j<=noOfElements;j++){
sum=sum+arr[i];
i++;
}
if(arr[0] == sum){
flag = true;
}else{
flag = false;
break;
}
}
if(flag){
return 1;
}else{
return 0;
}
}
}

Categories