automated J unit software test in java - java

I have wrote but I don't know what is wrong, it should return sum of the values of arrays if the array is not-empty but if array is empty it should return zero.
public class Calculation {
int findSum(int A[], int N) {
if (N <= 0)
return 0;
return (findSum(A, N - 1) + A[N - 1]);
}
int main() {
int A[] = {1, 2, 3, 4, 5};
int N = sizeof(A) / sizeof(A[0]);
System.out.print("Sum = " + findSum(A, N));
return 0;
}
}

You are using C/C++ code in Java. This is working for Java
public class Calculation {
static int findSum(int[] A, int N) {
if(N<=0) {
return 0;
}
int sum = 0;
for(int i:A) {
sum+=i;
}
return sum;
}
public static void main(String args[]) {
int[] A = {1,2,3,4,5};
int N = A.length;
System.out.println("Sum of x+y = " + findSum(A, N));
}
}

public class ArrayUtils {
static int sumOfArray(int[] arr) {
if(arr.length<=0) {
return 0;
}
int sumOfArray = 0;
for(int i:arr) {
sumOfArray+=i;
}
return sumOfArray;
}
public static void main(String args[]) {
int[] arr = {1,2,3,4,5};
System.out.println("Sum of all array elements = " + sumOfArray(arr));
}
}

Related

Quick Sort Recursion Java

I'm trying to code Quick Sort using recursion but I am getting a stack overflow error. this the second recursive function is giving that continuous error. I'm just unable to figure it out.
public class QuickSortRec {
public static void quicksort(int input[],int a,int b)
{
if(a<b)
{
int pivotpos=partition(input,a,b);
quicksort(input, a,pivotpos-1);
quicksort(input, pivotpos+1,b);
}
}
private static int partition(int input[],int a,int b)
{
int pivot=input[a];
int count=0;
for(int i=a+1;i< input.length;i++)
{
if(input[i]<pivot)
{
count++;
}
}
int temp=input[a];
input[a]=input[count];
input[count]=temp;
for(int i=0;i<count;i++)
{
if(input[i]>pivot)
{
for(int j=input.length-1;j>pivot;j--)
{
if(input[j]<pivot)
{
temp=input[i];
input[i]=input[j];
input[j]=temp;
}
}
}
}
return count;
}
public static void main(String[]args)
{
int arr[]={6,2,10,8,15,3,4};
int a=0;
int b=arr.length-1;
quicksort(arr,a,b);
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
You have some mistakes. For example you never used b in your pivot function.
You must change your partition function same as below:
public class QuickSortRec {
public static void quicksort(int input[],int a,int b)
{
if(a<b)
{
int pivotpos=partition(input, a,b);
quicksort(input, a,pivotpos-1);
quicksort(input, pivotpos+1,b);
}
}
private static int partition(int arr[],int low,int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
public static void main(String[]args)
{
int arr[]={6,2,10,8,15,3,4};
int a=0;
int b=arr.length-1;
quicksort(arr,a,b);
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
I tried to debug your programm, but didnt realy find a solution for the problem so I decided to try to write my own solution because the task seems very interesting to me.
So my goal was to avoid loops completly and only use recursion:
public static void main(String[] args)
{
int array[] = { 6, 2, 10, 8, 15, 3, 4 };
int[] sortedArray = quicksort(array);
for (int currentNumber : sortedArray)
{
System.out.print(currentNumber + " ");
}
}
static int index = 0;
static int tempIndex;
private static int[] quicksort(int[] inputArray)
{
tempIndex = index;
int totalArrayLength = inputArray.length;
if (index != totalArrayLength - 1)
{
if (inputArray[index] > inputArray[index + 1])
{
int temporary = inputArray[index + 1];
inputArray[index + 1] = inputArray[index];
inputArray[index] = temporary;
quickSort2(inputArray);
}
index++;
quicksort(inputArray);
}
return inputArray;
}
private static void quickSort2(int[] inputArray)
{
if (tempIndex != 0 && inputArray[tempIndex] < inputArray[tempIndex - 1])
{
if (tempIndex != 0)
{
int temporary2 = inputArray[tempIndex];
inputArray[tempIndex] = inputArray[tempIndex - 1];
inputArray[tempIndex - 1] = temporary2;
tempIndex--;
quickSort2(inputArray);
}
}
}

How to sum up Array values

having issues with arrays sum and return. Algorithm is also having issues with a single value array. Idea is to sum up numbers and form a new array until there's only one value left. For example Array [1,2,3,2] turns into [3,5,5], [8,10] and finally [18]. What is the best way to sum up array values and return it?
public class Arraytest {
int count(int[] t) {
if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++) {
tt[i] += t[i] + t[i + 1];
System.out.println(tt[i]);
}
count(tt);
}
return 0;
}
}
public class Main {
public static void main(String[] args) {
Arraytest at = new Arraytest();
System.out.println(t.count(new int[] {1,2,3,4,5})); // 48
System.out.println(t.count(new int[] {2})); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})); // 2538
}}
static int count(int[] t) {
if(t.length == 1)
return t[0];
else if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++)
tt[i] += t[i] + t[i + 1];
return count(tt);
}
return 0;
}
At the end you always returned zero instead of returning the last int in the array
Working Code:
public class Main {
public static void main(String[] args) {
Main t = new Main();
System.out.println(t.count(new int[] {1,2,3,4,5})[0]); // 48
System.out.println(t.count(new int[] {2})[0]); // 2
System.out.println(t.count(new int[] {7,1,1,3,8,2,9,5,4,2})[0]); // 323
}
static int[] count(int[] t) {
if(t.length == 1)
return t;
else if (t.length > 1) {
int[] tt = new int[t.length - 1];
for (int i = 0; i < t.length - 1; i++) {
tt[i] += t[i] + t[i + 1];
}
return count(tt);
}
return null;
}
}

How to get my array to sort properly? Recursive Sorting

After many times to try to solve this issue, I can't seem to solve my dilemma. When trying to run my program, the unsorted array will not sort when printing "Sorted Array". Is there something that I'm doing wrong?
public class RecursiveSorter {
private int[] sortedArray;
private int[] array;
public RecursiveSorter() {
array = new int[1];
}
public RecursiveSorter(int[] a) {
array = a;
}
public void setArray(int[] a) {
array = a;
}
public int[] getSortedArray() {
return sortedArray;
}
public int[] getOriginalArray() {
return array;
}
public int[] sort() {
sortedArray = array;
recursiveSort(sortedArray.length - 1);
return sortedArray;
}
public int[] recursiveSort(int endIndex) {
if (endIndex > 0) {
int m = getMaxIndex(endIndex, sortedArray);
swap(m, endIndex, sortedArray);
recursiveSort(endIndex-1);
}
return sortedArray;
}
public int getMaxIndex(int endIndex, int[] a) {
int max = a[0];
int maxIndex = 0;
for (int i = 1; i < endIndex; i++) {
if (a[i] < max) {
max = a[i];
maxIndex = i;
}
}
return maxIndex;
}
//Changed it to make sure that it is swapping the elements correctly
public void swap(int src, int dest, int[] a) {
if(dest <= src)
{
int temp = a[dest];
a[dest] = a[src];
a[src] = temp;
dest++;
src++;
}
}
public String toString() {
return "Original: " + prettyPrint(getOriginalArray()) + "\n" +
"Sorted: " + prettyPrint(getSortedArray());
}
private String prettyPrint(int[] a) {
String s = "";
for (int i : a)
s += i + " ";
return s;
}
public static void main(String[] args) {
// Automate running, but not testing
int[] array = {5, 67, 12, 20};
RecursiveSorter s = new RecursiveSorter(array);
s.sort();
System.out.println(s); // uses Sorter.toString
}
}
You have 3 problems. 2 are in getMaxIndex(): you were not including the last element in the test for the max, and the test for max is not the right. You are computing the min.
public int getMaxIndex(int endIndex, int[] a) {
int max = a[0];
int maxIndex = 0;
for (int i = 1; i <= endIndex; i++) { // use <= instead of <
if (a[i] > max) { // change < in >
max = a[i];
maxIndex = i;
}
}
return maxIndex;
}
And one problem in swap()
public void swap(int src, int dest, int[] a) {
if(src <= dest) // reverse src and dest
{
int temp = a[dest];
a[dest] = a[src];
a[src] = temp;
dest++; // no use, dest is local
src++; // idem
}
}
Then you will have:
Original: 5 12 20 67
Sorted: 5 12 20 67
Actually the orginal array is modified because array and sortedArray reference the same array of int. There is no copy in Java. When you do
public int[] sort() {
sortedArray = array;
recursiveSort(sortedArray.length - 1);
return sortedArray;
}
sortedArray points to the same int[] as array. If you want to keep the orginal one, you need to explicitly do a copy, for instance with System.arrayCopy(...).
I traced the problem down to two points:
first, you have an unnecessary if in swap(...):
public void swap(int src, int dest, int[] a)
{
// if(dest <= src)
// {
int temp = a[dest];
a[dest] = a[src];
a[src] = temp;
// dest++;
// src++;
// }
}
Second, you have a little bug in the for loop of getMaxIndex(...):
public int getMaxIndex(int endIndex, int[] a)
{
int max = a[0];
int maxIndex = 0;
for (int i = 1; i <= endIndex; i++) // substituted < with <=
{
if (a[i] < max)
{
max = a[i];
maxIndex = i;
}
}
return maxIndex;
}
With these changes (and mentionded System.arraycopy), the algorithm should work as intended.
Why you are not sing
// sorting array in #java.util.Arrays;
Arrays.sort(array);
And dont need to recusive call and all
If you need to write your own code, then Choose any sorting algorthim, implement that one by your own.
private static void sort(int[] array){
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}

How to remove a user entered value from an array?

The user enters a value, and it is told that we are to remove the value, and print the newly created array.
How do i write that code? It is supposed to be in that method removeValue.
Can you also explain how it works.
import java.util.*;
public class ArrayHandler {
public static void main(String[]args)
{
int[] array= new int[5]; // populates Array with 5 numbers
for(int i=0;i<array.length;i++) // creates the 5 random numbers
array[i]=(int)(Math.random()*5000);
printList(array); // prints Array
System.out.println("");
System.out.println("Sum: " + calculateSum(array));
System.out.println("Max: " + findMax(array));
System.out.println("Minimum: " + findMin(array));
System.out.println("Value: " + search(array));
}
public static void printList(int[] nums)
{
for(int i=0; i<nums.length;i++) {
System.out.print(nums[i] + " ");
}
}
public static int calculateSum(int[] nums)
{
int sum = 0;
for(int i=0;i<nums.length;i++)
{
sum = sum + nums[i];
}
return sum;
}
public static int findMin(int[] nums)
{
int min = nums[0];
for(int i=0;i<nums.length;i++)
{
if(nums[i] < min)
min=nums[i];
}
return min;
}
public static int findMax(int[] nums)
{
int max=nums[0];
for(int i=0;i<nums.length;i++)
{
if(nums[i] > max)
max=nums[i];
}
return max;
}
public static int search(int[] nums)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What value do you want?");
int value = keyboard.nextInt();
for(int i=0;i<nums.length;i++)
{
if(nums[i] == value)
return i;
}
return -1;
}
public static int removeValue (int[] nums)
{
int[] array = new array[array.charAt(value) - array.charAt(value)];
if(nums[i] == i)
return array;
else
return -1;
}
}
This has been answered: Removing an element from an Array (Java)
If you want to use only arrays, view this answer: Removing an element from an Array (Java)
public static String removeValue (int[] nums)
{
int i = search(nums);
nums[i] = nums[i] - nums [i];
if(nums[i] == 0)
{
return Arrays.toString(nums);
}
else return "invalid";
}
This will work and instead of calling the search method in your main, call the removeValue method and pass it the array.

Grid walking algorithm code correction

Grid Walking (Score 50 points):
You are situated in an N dimensional grid at position (x_1,x2,...,x_N). The dimensions of the grid are (D_1,D_2,...D_N). In one step, you can walk one step ahead or behind in any one of the N dimensions. (So there are always 2N possible different moves). In how many ways can you take M steps such that you do not leave the grid at any point? You leave the grid if you for any x_i, either x_i <= 0 or x_i > D_i.
Input:
The first line contains the number of test cases T. T test cases follow. For each test case, the first line contains N and M, the second line contains x_1,x_2...,x_N and the 3rd line contains D_1,D_2,...,D_N.
So, in the above solution I'm trying to take one dimensional array.
The website claims 38753340 to be the answer, but I'm not getting it.
public class GridWalking {
/**
* #param args
*/
public static void main(String[] args) {
try {
long arr[] = new long[78];
long pos = 44;
long totake = 287;
/*
* Double arr[] = new Double[3]; Double pos = 0; Double totake = 5;
*/
Double val = calculate(arr, pos, totake);
System.out.println(val % 1000000007);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
public static HashMap<String, Double> calculated = new HashMap<String, Double>();
private static Double calculate(long[] arr, long pos, long totake) {
if (calculated.containsKey(pos + "" + totake)) {
return calculated.get(pos + "" + totake);
}
if (0 == totake) {
calculated.put(pos + "" + totake, new Double(1));
return new Double(1);
}
if (pos == arr.length - 1) {
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
if (pos == 0) {
Double b = calculate(arr, pos + 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
Double a = calculate(arr, pos + 1, totake - 1);
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = (a + b);
calculated.put(pos + "" + totake, ret);
return ret;
}
}
You need to change key values as for pos + "_" + totake.
I have rewritten it but I'm not sure it working or not. It takes too much time to complete if ever.
public class GridWalking {
static long arr_length = 78;
static long pos = 44;
static long totake = 287;
static long count = 0;
/**
* #param args
*/
public static void main(String[] args) {
try {
calculate(pos, totake);
System.out.println(count % 1000000007);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
private static void calculate(long pos, long totake) {
if (pos < 0 || pos > arr_length - 1)
return;
if (0 == totake) {
count++;
return;
}
calculate(pos + 1, totake - 1);
calculate(pos - 1, totake - 1);
}
}
I have tried solving that Grid walking problem in Hackerrank. this is the code that had worked(in ecclipse atleast). but i donno why it does not match with given answers. Nut i think you can get the idea from it. Since it does not use recursion, no problem with execution time..
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int count=0;
public static void main(String[] args) throws FileNotFoundException {
String filename = "src/testcases.txt";//testcases is just a file containing input
File file = new File(filename);
Scanner in = new Scanner(file);
//in.useDelimiter("[^0-9]+");
//-----------------------------------------------------------------
int T=in.nextInt();
for(int t=0;t<1;t++){
int N=in.nextInt();
int M=in.nextInt();System.out.println("M="+M);
int[] X=new int[N];
long max=1000000007;
int[] D=new int[N];
for(int i=0;i<N;i++) X[i]=in.nextInt();
for(int i=0;i<N;i++) D[i]=in.nextInt();
int Dmax=D[0];
int Dtotal=1;
for(int i=0;i<N;i++) if(Dmax<D[i]) Dmax=D[i];
for(int i=0;i<N;i++) X[i]--;
for(int i=0;i<N;i++) Dtotal*=D[i];//total number of fields
long[] mainarray= new long[Dtotal];
long[] mainarraynext=new long[Dtotal];
int[][] ways=new int[N][Dmax];
set( X, mainarray,D, 1);
int temp[]=new int[N];
for(int h=0;h<10;h++){
for(int j=0;j<Dtotal;j++){
mainarraynext[j]=getsum(inverse(j,D),mainarray, D );
}
for(int j=0;j<Dtotal;j++){
mainarray[j]=mainarraynext[j];
mainarray[j]%=max;
}
System.out.println(Arrays.toString(mainarray));
}
long finalsum=0;
for(int j=0;j<Dtotal;j++){
finalsum+=mainarray[j];
//System.out.println(finalsum);
}
System.out.println(finalsum);
//System.out.println(Arrays.toString(inverse(44,D)));
}
}
public static long get(int[] x, long[] mainarray, int[] D){
for(int i=0;i<x.length;i++){
if(x[i]>=D[i]) return 0;
if(x[i]<0) return 0;
}
int index=0;
for(int i=0;i<D.length;i++){
index=(index*D[i])+x[i];
}
return mainarray[index];
}
public static int[] inverse(int index,int[] D){
int[] temp=new int[D.length];
for(int i=D.length-1;i>=0;i--){
temp[i]=index%D[i];
index=index/D[i];
}
return temp;
}
public static void set(int[] x, long[] mainarray, int[] D, int value){
int index=0;
for(int i=0;i<D.length;i++){
index=(index*D[i])+x[i];
}
mainarray[index]=value;
}
public static long getsum(int[] x,long[] mainarray, int[] D ){
int[] temp=new int[x.length];
long sum=0;
//for 2n different sides
for(int j=0;j<x.length;j++){//sum in each side
temp[j]=x[j];
}
for(int j=0;j<x.length;j++){//sum in each side
temp[j]--;
sum+=get(temp, mainarray, D);
temp[j]+=2;
sum+=get(temp, mainarray, D);
temp[j]--;
}
return sum;
}
}
Here's a Java solution I've built for the original hackerrank problem. For big grids runs forever. Probably some smart math is needed.
long compute(int N, int M, int[] positions, int[] dimensions) {
if (M == 0) {
return 1;
}
long sum = 0;
for (int i = 0; i < N; i++) {
if (positions[i] < dimensions[i]) {
positions[i]++;
sum += compute(N, M - 1, positions, dimensions);
positions[i]--;
}
if (positions[i] > 1) {
positions[i]--;
sum += compute(N, M - 1, positions, dimensions);
positions[i]++;
}
}
return sum % 1000000007;
}

Categories