I wrote the following code for Pascal's triangle on https://leetcode.com/ and I got the error as follows:
Line 10: error: incompatible types: int cannot be converted to
List<List<Integer>>.
public class Solution {
public List<List<Integer>> generate(int numRows) {
List list;
int temp;
for(int i=0;i<numRows;i++) {
temp = (int) Math.pow(11,i);
list.add(Arrays.asList(temp));
}
return temp;
}
public static void main(String s[]) {
Solution solution = new Solution();
java.util.Scanner scan = new java.util.Scanner();
System.out.println("Enter the no.of Rows");
int numRows = scan.nextInt();
solution.generate(numRows);
}
}
Help me to find the solution.
You have almost right answer. Just few mistypes. Here is good one:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> generate(int numRows) {
List<Integer> list=new ArrayList<Integer>();
int temp;
for (int i = 0; i < numRows; i++) {
temp = (int) Math.pow(11, i);
list.add(temp);
}
return list;
}
public static void main(String s[]) {
Solution solution = new Solution();
java.util.Scanner scan = new java.util.Scanner(System.in);
System.out.println("Enter the no.of Rows");
int numRows = scan.nextInt();
Object answer=solution.generate(numRows);
System.out.println(answer);
}
}
Your method is defined as returning a List<List<Integer>> (a list of lists of integers) but you are trying to return an integer.
You have created the List in the method, so you should return that, and not the integer temp.
public List<Integer> generate(int numRows) {
List list;
int temp;
for(int i=0;i<numRows;i++) {
temp = (int) Math.pow(11,i);
list.add(Arrays.asList(temp));
}
return list;
Why are returning int value for List return type. please change it to list. It will compile properly.
Related
Our assignment says we should "write the source code and test code for a function named sumArray that accepts an array of ints and returns the sum of all elements from the array".
I think I've got SumArray.java to return sum OK, but I'm struggling to apply my method to the test input. Any help please? TIA.
SumArray.java
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
SumArrayTest.java
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
/**
* Test of main method, of class SumArray.
*/
#Test
public void testMain() {
System.out.println("main");
String[] args = null;
SumArray.main(args);
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
// int testResult = sumArray({2, 3, 4});
int testResult = SumArray sumArray(intArray);
assertEquals(expectedResult, testResult);
// fail("The test case is a prototype.");
}
}
Edit: I've tried to implement what's been suggested so far with some changes; really not sure of any of this is right; a lot of it is guesswork TBH.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray;
public static int sumArray(int[] arr) {
return sum;
}
public static SumArray input() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return new SumArray();
}
public static void main(String[] args) {
SumArray result = input();
System.out.println(result.sumArray(SumArray));
}
}
package sumarray;
import org.junit.Test;
import static org.junit.Assert.*;
public class SumArrayTest {
public SumArrayTest() {
}
#Test
public void testSumArray() {
System.out.println("main");
String[] args = null;
int[] intArray = new int[]{2, 3, 4};
int expectedResult = 9;
assertEquals(expectedResult, SumArray.sumArray(intArray));
// fail("The test case is a prototype.");
}
}
The only error I'm seeing currently is 'cannot find symbol' for SumArray in main.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray();
}
}
The above is the original code you posted. Now, you say you get the correct output. Yes, here you do:
package sumarray;
import java.util.Scanner;
public class SumArray {
private static int n, sum = 0;
public static int sumArray() {
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements. (Press [return] after each one)");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:" + sum);
return sum;
}
public static void main(String[] args) {
sumArray(); // this one will return the correct answer
sumArray(); // this one will not
}
}
The second one will return wrong data, because you don't reset the value of sum.
You should split the tasks: sumArray should receive an array, and should return the sum of the elements. Either you should change the name of the method, or change the implementation, that is what Mahmoud told you.
package sumarray;
import java.util.Scanner;
public class SumArray {
private static Scanner scan = new Scanner(System.in); // create this on class level, not every execution of your method
public static int[] buildArray(int elements) {
int[] arr = new int[elements];
for ( int i = 0; i < elements; i++ ) {
System.out.println("Enter element nr: " + (i+1));
arr[i] = scan.nextInt();
}
return arr;
}
public static int sumArray(int[] input) {
int sum = 0; // don't use a class level one. especially not a static one, it's value could be altered by another thread
for ( int in : input ) { // iterate over the array and add the values
sum += in; // this should be in -> each iteration we add the value of in (the element of the array) to sum
}
return sum;
}
public static void main(String[] args) {
System.out.println("Provide the size of the array: ");
int param = scan.nextInt();
int[] array = buildArray(param);
int result = sumArray(array);
System.out.println("The sum of the array is: " + result);
}
}
This approach will land you with far lesser issues. It also doesn't have static variables like n and sum in your class that might lead to wrong results.
The main() method is the entry point into the application, you shouldn't test the main() method. Instead, you should test the sumArray() method and compare the expected Vs. the actual returned value from the method.
As a side note, you can better pass the input array to the sumArray() method as a parameter instead of reading it from System.in within the method body.
So your method signature can look like this:
public static int sumArray(int[] arr). The client code which uses this method, which is the main method in your case (or the unit test) can pass the array without bothering the method how this input array was got.
Memoization is giving me wrong answers. Please can some one help me out here. Without memorization, I am getting the right answers as in function targetBestR, but in the memoized function targetBestM, I am getting the wrong values being stored in the array list for the respective keys.
import java.util.ArrayList;
import java.util.HashMap;
public class TargetSumBest {
public static ArrayList<Integer> targetBestR(int n, int arr[]){
if(n==0) return new ArrayList<Integer>();
if(n<0) return null;
ArrayList<Integer> shortestCombo=null;
for(int i=0;i<arr.length;i++) {
//System.out.println(i);
//System.out.println(arr[i]);
int rem=n-arr[i];
//System.out.println(n+"-"+i+"="+rem);
ArrayList<Integer> tar=targetBestR(rem, arr);
if(tar!=null) {
tar.add(arr[i]);
if(shortestCombo==null||tar.size()<shortestCombo.size()) {
shortestCombo=tar;
}
}
}
//System.out.println(n+"value"+shortestCombo);
return shortestCombo;
}
public static ArrayList<Integer> targetBestM(int n, int arr[], HashMap<Integer, ArrayList<Integer>> memo){
if(n==0) return new ArrayList<Integer>();
if(n<0) return null;
if(memo.containsKey(n)) return memo.get(n);
ArrayList<Integer> shortestCombo=null;
for(int i=0;i<arr.length;i++) {
//System.out.println(i);
//System.out.println(arr[i]);
int rem=n-arr[i];
//System.out.println(n+"-"+i+"="+rem);
ArrayList<Integer> tar=targetBestM(rem, arr,memo);
if(tar!=null) {
tar.add(arr[i]);
if(shortestCombo==null||tar.size()<shortestCombo.size()) {
shortestCombo=tar;
}
}
}
//System.out.println(n+"value"+shortestCombo);
memo.put(n, shortestCombo);
return shortestCombo;
}
public static void main(String[] args) {
int n=8; int arr[]= {1,4,2};
System.out.println(targetBestM(n, arr, new HashMap<Integer, ArrayList<Integer>>()));
System.out.println(targetBestR(n, arr));
}
}//error
Was able to find the problem. The array passed into the HashMap keeps getting used and added to. Was able to fix it by creating new ArrayLists when reading and writing from the HashMap.
when reading...
if (memo.containsKey(n)) {
System.out.println(indent + n + " memo.get(n) = " + memo.get(n));
return new ArrayList<>(memo.get(n));
}
when writing...
memo.put(n, new ArrayList<>(shortestCombo));
I am writing a program that takes in the number of ingredients. The prog
This is my code:
import java.util.Scanner;
public class Restaurant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
}
Change this sortCalories function to the one below. Also you need to pass price array as second parameter like this sortCalories(calories,price, ingredientName);:
public static void sortCalories(double[] calories,double[] price, String[] ingredientName) {
double temp;
String temp1;
for (int p=0; p<calories.length; p++) {
for (int j=p+1; j<calories.length; j++) {
if(calories[p]/price[p]>calories[j]/price[j]) {
temp = calories[p];
calories[p] = calories[j];
calories[j] = temp;
temp = price[p];
price[p] = price[j];
price[j] = temp;
temp1 = ingredientName[p];
ingredientName[p] = ingredientName[j];
ingredientName[j] = temp1;
}
}
}
}
Below is the problem statement from hackerrank
Mark and Jane are very happy after having their first child. Their son loves toys, so Mark wants to buy some. There are a number of different toys lying in front of him, tagged with their prices. Mark has only a certain amount to spend, and he wants to maximize the number of toys he buys with this money.
Given a list of prices and an amount to spend, what is the maximum number of toys Mark can buy? For example, if prices = [1,2,3,4] and Mark has k=7 to spend, he can buy items [1,2,3] for 6, or [3,4] for 7 units of currency. He would choose the first group of 3 items.
Below is code I wrote for this problem which involves backtracking technique
import java.util.ArrayList;
import java.util.Collections;
public class MarkAndToys {
static ArrayList<Integer> possibleSolutions = new ArrayList<>();
static boolean findSolution(int[] prices,int amount,int left,int length,int items){
// Base case: if whole array was iterated and amount is >=0 then we got a solution
if(left >= length){
if(amount>=0){
possibleSolutions.add(items);
return true;
}
return false;
}
// Key idea: prices[left] is chosen or it is not.
// Deal with prices[left], letting recursion
// deal with all the rest of the array.
// Recursive call trying the case that prices[left] is chosen --
// subtract it from amount in the call.
if (findSolution(prices,amount-prices[left],left+1,length,items+1)) return true;
// Recursive call trying the case that prices[left] is not chosen.
if (findSolution(prices,amount,left+1,length,items)) return true;
// If neither of the above worked, it's not possible.
return false;
}
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
if(findSolution(prices,k,0,prices.length,0)){
//if solutions are found then return maximum of them
return Collections.max(possibleSolutions);
}
return 0;
}
public static void main(String[] args) {
System.out.println(maximumToys(new int[]{1,12,5,111,200,1000,10}, 50));
}
}
This seems to be working fine:
// Complete the maximumToys function below.
static int maximumToys(int[] prices, int k) {
Arrays.sort(prices);
int sum = 0;
int index = 0;
for(int i = 0; i < prices.length; i++) {
sum+=prices[i];
index = i;
if(sum > k) {
break;
}
}
return index;
}
package Scanarios;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Toys {
public static void main(String[] args) {
Toys t=new Toys();
int[] a = {3,6,2,1,4,5};
int q=1;
int n=6;
ArrayList<Integer> queries[]=new ArrayList[n];
ArrayList<Integer> result=new ArrayList();
for (int i = 0; i < n; i++) {
queries[i] = new ArrayList<Integer>();
}
queries[0].add(10);
queries[0].add(2);
queries[0].add(2);
queries[0].add(5);
result=t.maximumToys(n,a,q,queries);
System.out.println(result);
}
public ArrayList<Integer> maximumToys(int n, int a[], int q, ArrayList<Integer> queries[]) {
ArrayList<Integer> arrlist=new ArrayList();
for(int z=0;z<q;z++) {
int[] arr=queries[z].stream().mapToInt(i -> i).toArray();
int cost=arr[0];
int k=arr[1];
int count=0;
int[] proxyarr=new int[n-1];
proxyarr =removeBrokenPrice(a,arr,k);
Arrays.sort(proxyarr);
for(int i=0;i< proxyarr.length;i++) {
cost -=proxyarr[i];
if(cost > 0) {
count++; }else {
break;
}
}
arrlist.add(count);
}
return arrlist;
}
int[] removeBrokenPrice (int a[],int b[],int k){
int count=0;
for(int i=k;i <= b.length-1;i++) {
for(int j=0;j<a.length;j++) {
if(j==b[i]-1) {
a[j]=-1;
count++;
}
}
}
int[] proxyarr=new int[a.length-count];
for(int i=0,j=0;i< a.length;i++)
{
if(a[i]==-1) {
continue;
}else {
proxyarr[j++]=a[i];
}
}
return proxyarr;
}
}
I have a class called ThreeSorts.java
The aim is to generate a random arraylist of size n - this works.
Then display the array - this works.
Then I have to prove that these sorting algorithms work, however when I pass the random generated array into one of the sorts like SortA(a);
and then display the array it does not get sorted the output is the same:
Generated ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
SortA ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
ThreeSorts.java:
import java.util.*;
public class ThreeSorts
{
private static ArrayList<Integer> CopyArray(ArrayList<Integer> a)
{
ArrayList<Integer> resa = new ArrayList<Integer>(a.size());
for(int i=0;i<a.size();++i) resa.add(a.get(i));
return(resa);
}
public static ArrayList<Integer> SortA(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
int n = a.size(),i;
boolean noswaps = false;
while (noswaps == false)
{
noswaps = true;
for(i=0;i<n-1;++i)
{
if (array.get(i) < array.get(i+1))
{
Integer temp = array.get(i);
array.set(i,array.get(i+1));
array.set(i+1,temp);
noswaps = false;
}
}
}
return(array);
}
public static ArrayList<Integer> SortB(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
Integer[] zero = new Integer[a.size()];
Integer[] one = new Integer[a.size()];
int i,b;
Integer x,p;
//Change from 8 to 32 for whole integers - will run 4 times slower
for(b=0;b<8;++b)
{
int zc = 0;
int oc = 0;
for(i=0;i<array.size();++i)
{
x = array.get(i);
p = 1 << b;
if ((x & p) == 0)
{
zero[zc++] = array.get(i);
}
else
{
one[oc++] = array.get(i);
}
}
for(i=0;i<oc;++i) array.set(i,one[i]);
for(i=0;i<zc;++i) array.set(i+oc,zero[i]);
}
return(array);
}
public static ArrayList<Integer> SortC(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
SortC(array,0,array.size()-1);
return(array);
}
public static void SortC(ArrayList<Integer> array,int first,int last)
{
if (first < last)
{
int pivot = PivotList(array,first,last);
SortC(array,first,pivot-1);
SortC(array,pivot+1,last);
}
}
private static void Swap(ArrayList<Integer> array,int a,int b)
{
Integer temp = array.get(a);
array.set(a,array.get(b));
array.set(b,temp);
}
private static int PivotList(ArrayList<Integer> array,int first,int last)
{
Integer PivotValue = array.get(first);
int PivotPoint = first;
for(int index=first+1;index<=last;++index)
{
if (array.get(index) > PivotValue)
{
PivotPoint = PivotPoint+1;
Swap(array,PivotPoint,index);
}
}
Swap(array,first,PivotPoint);
return(PivotPoint);
}
/////////////My Code////////////////
public static ArrayList<Integer> randomArrayList(int n)
{
ArrayList<Integer> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(255));
}
return list;
}
private static void showArray(ArrayList<Integer> a) {
for (Iterator<Integer> iter = a.iterator(); iter.hasNext();)
{
Integer x = (Integer)iter.next();
System.out.print(("("+x + ")"));
System.out.print(",");
//System.out.print(GetAge());
//System.out.print(") ");
}
System.out.println();
}
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
SortA(a);
showArray(a);
}
}
Test is called in main like this ThreeSorts.test(10);
Why is it not getting sorted even tho the random array is passed and there are no errors?
In your sample code you are only testing SortA which reads:
ArrayList<Integer> array = CopyArray(a);
...
return(array);
so actually it is taking a copy of your array, sorting it, and then returning you the sorted array.
So when you test it, instead of using:
SortA(a);
you need to use
a = SortA(a);
The type of data your function SortA returns is ArrayList<Integer>, which means it returns an array list of integers. You need to change the line SortA(a); to a = SortA(a);: this way a variable will receive the results of this function's work.
You have to set the returned value, otherwise a will not be sorted in test method. Change the way you call SortA(a) to:
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
a = SortA(a);
showArray(a);
}
instead of the method SortA(a); just use Collections.sort(a); inside static block. Like
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
Collections.sort(a);
showArray(a);
Thats it.