Core Java Practical Questions - java

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

Related

Find minimum pair of numbers whose sum is 15

I am trying to find the minimum pair of numbers to achieve sum of 15. I am creating new array for them and passing that array to method which is adding element of that array and generating true or false. array size will increase if method returns false.
public class FindMinimum {
static int arr[] = { 10, 3, 2, 13 };
static int numArr[] = new int[30];
static int arrLength = 2;
static boolean status = false;
static int number;
public static void main(String args[]) {
for (int i = 0; i < arrLength; i++) {
numArr[i] = arr[i];
}
if (checkPair(numArr)) {
System.out.println("Number found");
} else {
arrLength = arrLength + 1;
System.out.println("Increasing array length by one");
}
}
public static boolean checkPair(int x[]) {
for (int i = 0; i < x.length; i++) {
number = number + x[i];
}
if (number == 15) {
status = true;
for (int i : x) {
System.out.println(i);
}
} else {
status = false;
}
return status;
}
}
Expected result is minimum pair of addition that is "13 ,2"
If I understand correctly need to find minimum pair which always add to 15. If this is correct below code should solve it.
public static void main(String args[]) {
Arrays.sort(arr);
for (int i=0,j=arr.length-1;i<arr.length && j>=0;) {
if ((arr[i]+arr[j])<15) {
/*System.out.println(arr[i]+"-"+arr[last-i]);
break;*/
i++;
} else if ((arr[i]+arr[j])>15) {
j--;
} else {
System.out.println(arr[i]+"-"+arr[j]);
break;
}
}
}
import java.util.Scanner;
public class FindMinimumPair {
static Scanner sc = new Scanner(System.in);
static int userArr[];
static int numArr[]; // New array to take number / pairs from main array to compare with else numbers
// in the main array
static int arrLength = 1; // increase the array length of numArr if pair is more than 2 numbers
static boolean status = false; // check method returns true or false
static int sum;
public static void main(String args[]) {
System.out.println("Sum of pair should be ?");
sum = sc.nextInt();
System.out.println("Enter the lenght of an array");
int userArrLength = sc.nextInt();
userArr = new int[userArrLength];
System.out.println("Enter array integers upto " + userArrLength);
for (int i = 0; i < userArrLength; i++) {
userArr[i] = sc.nextInt();
}
// Loop to read numbers from main array
for (int i = 0; i < userArr.length; i++) {
// Defines the length of new array
numArr = new int[arrLength]; // initialize the new array
// Loop to add numbers into new array
for (int j = 0; j < arrLength; j++) {
numArr[j] = userArr[j]; // add numbers into new array
}
if (check(numArr)) { // call check method and pass new array in it
for (int a : numArr) { // if returns true then print that array (contains the pair)
System.out.print(a + " ");
}
System.out.print(userArr[numArr.length]); // print the last number which is the part of numArr
System.out.println(" is equals to " + sum);
} else {
System.out.println("Numbers not found");
}
arrLength = arrLength + 1; // increase the array length if false
}
}
public static boolean check(int number[]) {
int x = 0;
// Loop to make sum of all numbers of numArr (make it single number)
for (int j = 0; j < number.length; j++) {
x = x + number[j];
}
outer: for (int i = 0; i < number.length; i++) { // loop for elements in numArr array
for (int j = 0; j < userArr.length; j++) { // loop for given array elements
if (x + userArr[j] == sum) { // check each number of given array with the sum of numArr
status = true;
break outer; // breaks outer loop and returns true
} else {
status = false;
}
}
}
return status;
}
}

Coding Heapsort Algorithm but am getting a Stack Overflow error and cannot figure out why

Below is my code, I keep getting a Stack Overflow error from the last statement in my code which is the recursive call for heapify (the max heapify) method. Please help.
Class 1 code
package hw3javasorttest;
import java.util.*;
public class HW3JavaSortTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Unsorted array");
System.out.print("[");
int[] arr = new int[30];
for(int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 100);
System.out.print(arr[i] + " ");
}
System.out.println("]");
Scanner in = new Scanner(System.in);
System.out.println("Please enter one of the corresponding numbers to choose the sorting method: ");
System.out.print("1.Heap Sort\n2.Quick Sort");
int Sorting = in.nextInt();
int x;
int q;
x = arr[0];
q = arr[29];
switch (Sorting) {
case 1: System.out.println("Heap Sort:");
HW3JavaSort.HeapSort(arr);
System.out.println(Arrays.toString(arr));
break;
case 2: System.out.println("Quick Sort:");
System.out.println();
// HW3JavaSort.quickSort(arr, x, q);
// System.out.println(Arrays.toString(a));
break;
default: System.out.println("invalid entry");
break;
}
}
}
Class 2 code
package hw3javasorttest;
public class HW3JavaSort {
public static void printArr(int[] arr) { //Method that displays arr
System.out.print("[");
for(int i= 0; i<arr.length; i++){
if(i==arr.length-1) {
System.out.printf("%d]\n", arr[i]);
}
else {
System.out.printf("%d,", arr[i]);
}
}
}
public static void HeapSort(int[] arr) {
int Length = arr.length;
int placeholder;
BuildMaxHeap(arr, Length);
for(int i = arr.length-1; i>0; i--) {
placeholder = arr[0];
arr[0] = arr[i];
arr[i] = placeholder;
heapify(arr, 1, i);
}
}
public static void BuildMaxHeap(int[] arr, int n){ //Organizes max heap
if(arr == null) {
throw new NullPointerException("null");
}
if(arr.length <=0 || n <= 0) {
throw new IllegalArgumentException("illegal");
}
if(n > arr.length) {
n = arr.length;
}
for(int i = n/2; i>= 0; i--) {
heapify(arr, i, n);
}
}
public static void heapify(int [] arr, int i, int n) { //Makes max heap
int largest;
int lc = 2*i;
int rc = 2*i + 1;
int temp = 0;
if(lc<=n && arr[lc-1] > arr[i-1]) {
largest = lc;
} else {
largest = i;
}
if(rc<=n && arr[rc-1] > arr[largest-1]) {
largest = rc;
}
if(largest!=i) {
temp = arr[i-1];
arr[i-1] = arr[largest - 1];
arr[largest - 1] = temp;
heapify(arr, largest, n); //HERE IS WHERE THE COMPILER SAYS I AM //GETTING THE ERROR, SAYS STACK OVERFLOW THEN THE HEAPIFY METHOD THEN THIS LINE //# AND DISPLAYS THE ERROR HUNDREDS OF TIMES
}
}
}
Incorrect formatting caused the algorithm to work differently than expected... fixed by formatting like Java (not Python).
Please take a look at this: https://blog.takipi.com/tabs-vs-spaces-how-they-write-java-in-google-twitter-mozilla-and-pied-piper/

Array of prime numbers doesn't print out contents correctly

I have some problems with an array in java. I try to use thread and add prime numbers in an array but it doesn't work. I want b[c] to store all of the prime number from firstnumber to secondnumber.
public class btl {
public static boolean IsPrime(int n) {
if (n < 2) {
return false;
}
int squareRoot = (int) Math.sqrt(n);
for (int i = 2; i <= squareRoot; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanIn = new Scanner(System.in);
int first = 0;
int second = 0;
try {
System.out.println("Input First Number");
first = scanIn.nextInt();
System.out.println("Input Second Number");
second= scanIn.nextInt();
}
catch(Exception e) {
System.out.println("Something wrong!");
}
int x = first;
int y = second;
int a;
int[] b = new int[y];
Thread threadA = new Thread(new Runnable() {
#Override
public void run() {
int c=0;
for(int i=x; i<y; i++)
{
if(IsPrime(i)) {
b[c] = i;
c++;
System.out.println(b[c]);
}
}
}
});
threadA.start();
}
Your main issue is that you append c first, and only later print out b[c], which is still a blank cell in the array. Try:
for(int i=x; i<y; i++) {
if(IsPrime(i)) {
b[c] = i;
System.out.println(b[c]);
c++;
}
}
By the way, when you define the array b - you don't need all of y cells. It's a little more cost efficient to declare:
int[] b = new int[y-x];
Instead.

counting cosecutive numbers in arrays

Problem H [Longest Natural Successors]
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors. Example:
Input
7 2 3 5 6 7 9 10 Output 3
here is my code so far can anyone help me plz
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int[] array= new int[x];
for(int i=0;i<array.length;i++)
array[i]=scan.nextInt();
System.out.println(array(array));
}
public static int array(int[] array){
int count=0,temp=0;
for(int i=0;i<array.length;i++){
count=0;
for(int j=i,k=i+1;j<array.length-1;j++,k++)
if(array[j]-array[k]==1)
count++;
else{if(temp<count)
temp=count;
break;}
}
return temp+1;
}
}
Try this
ArrayList<Integer> outList = new ArrayList<Integer>()
int lastNum = array[0];
for(int i = 1; i < array.length; i++;)
if((lastNum + 1) == array[i])
outList.add(array[i]);
I think the line i=counter; should be i += counter. otherwise, you're always resetting the loop-counter i to zero, and so it never progresses.
You don't need the inner for loop, as this can be done with one single scan through the array:
public static int consecutive(int[]array) {
int tempCounter = 1; //there will always be a count of one
int longestCounter = 1; //always be a count of one
int prevCell = array[0];
for(int i=1;i<array.length;i++) {
if( array[i] == (prevCell + 1)) {
tempCounter++; //consecutive count increases
} else {
tempCount =1; //reset to 1
}
if(tempCounter > longestCounter) {
longestCounter = tempCounter; //update longest Counter
}
prevCell = array[i];
}
return longestCounter;
}
int sequenceStart = 0;
int sequenceLength = 0;
int longestSequenceLength = 0;
for (int item: array) {
if (item == sequenceStart + sequenceLength) {
sequenceLength++;
} else {
sequenceStart = item;
sequenceLength = 1;
}
longestSequenceLength = Math.max(longestSequenceLength, sequenceLength);
}

How do I call my methods to my main method?

Basically I need to call my "sum" and "sumOfEvens" methods into the main method. The "sum" method is for when the array contains the lucky numbers as seen in the "isLucky" method. The "sumOfEvens" method adds of the even numbers if the array doesn't contain a lucky number.
So "sum" = true
and "sumOfEvens" = false
So here is my code...
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
luckyNumber1 = 7;
luckyNumber2 = 13;
luckyNumber3 = 18;
int[] a=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
}
public static int sum(int [ ] value)
{
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{
if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
boolean b = isLucky(a);
int result;
if(b)
result = sum(a);
else
result = sumOfEvens(a);
You can do it in one line:
int result = isLucky(a) ? sum(a) : sumOfEvens(a);

Categories