Rewrite recursive function to iterative one - java

A short flight of stairs will be called a construction of cubes in which each next level consists of a strictly larger number of cubes than the previous level, if we count the levels from top to bottom. You need to count the number of ladders that can be built exactly from n cubes.
My solution to this task doesn't pass the time test. To fix this, I decided to try to rewrite the recursive function to the usual one, but so far it has not worked out very well.
public class main {
int n;
public static int counts(int prev_level, int n) {
if (n == 0){
return 1;
}
int count = 0;
for (int level =1; level<prev_level; level++){
if((n-level)<0)
break;
count += counts(level,n-level);
}
return count;
}
public static void main(String[] args) {
int n;
int res = 0;
int count = 0;
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
n = Integer.parseInt(sc.nextLine());
res = counts(n+1,n);
}
} catch(IOException e) { System.out.println("Input error"); }
try{
FileOutputStream writer = new FileOutputStream("output.txt");
PrintStream p = new PrintStream(writer);
p.println(res);
writer.close();
} catch(IOException e) { System.out.println("Output error"); }
}
}

Related

Can't write number with FileWriter [duplicate]

This question already has answers here:
Write int to text file using Writer
(8 answers)
Closed 5 years ago.
This is my code and I want b[i] will be write to the file name test.txt but it is not working. It's just write something like symbols. Thanks for helping.
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;
System.out.println(b[c]);
c++;
}
}
}
});
threadA.start();
try(FileWriter fw = new FileWriter("test.txt")){
for(int i =0; i<y; i++)
{
fw.write(b[i]);
}
}
catch(IOException exc) {
System.out.println("EROR! " + exc);
}
}
}
This is my display console
And this is file "test.txt"
I don't know why FileWriter writes symbols in file text.txt. I want it's number of array b[i].
FileWriter.write(int) writes a single character.
You likely want FileWriter.write(String)as in:
fw.write(Integer.toString(b[i]));

Change from finding max number to find words in array

I have a function that is searching for max number in the array. I want to make the function to search for more than one word that is entered from console.
As example I enter two words(car,ride) they're added to array and then "surasti" function is comparing them if they're in the array.
I have tried to do it on my own, but I'm a started and it seems too hard :(
Function that is searching:
public static produktas[] surasti (produktas G[], int n){
produktas A[] = new produktas[1];
produktas max = G[0];
for (int i=1; i<n; i++)
if (max.gautiSvori()<G[i].gautiSvori()) max = G[i];
A[0]=max;
return A;
}
The code that is calling that function (A is the array that you have to search in.):
case 5:
B = surasti(A, n);
System.out.println("Sunkiausias gyvunas yra:");
spausdinti_sar_ekrane(B, B.length);
break;
The produktas class:
class produktas {
private String pavadinimas;
private String salis;
private Double svoris;
private Double kaina;
produktas() {}
produktas(String pav, String salis, double svoris, double kaina){
pavadinimas = pav;
this.salis = salis;
this.svoris = svoris;
this.kaina = kaina;
}
public String gautiPav (){
return pavadinimas;
}
public String gautiSali (){
return salis;
}
public double gautiSvori (){
return svoris;
}
public double gautiKaina (){
return kaina;
}
}
When I try to change the function to this (don't know if its working fine, can't test it):
public static produktas[] surasti (produktas G[], int n){
try{
BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
produktas A[] = new produktas[5];
for (int j=0; j<5; j++){
System.out.println("Kokio produkto ieskosime?");
String found = in.readLine();
for (int i=1; i<n; i++){
if (found.equals(G[i].gautiPav())){
A[j] = G[i];
}
}
}
return A;
} catch(IOException ie){
ie.printStackTrace();
}
}
When I try this code I get this error at public static produktas[] surasti (produktas G[], int n){ line:
This method must return a result of type produktas[]
For the correctly complied code update your method to have a return in catch block as well.
public static produktas[] surasti(produktas G[], int n) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
produktas A[] = new produktas[5];
for (int j = 0; j < 5; j++) {
System.out.println("Kokio produkto ieskosime?");
String found = in.readLine();
for (int i = 1; i < n; i++) {
if (found.equals(G[i].gautiPav())) {
A[j] = G[i];
}
}
}
return A;
} catch (IOException ie) {
ie.printStackTrace();
return null; // Expected return from catch block
}
}
To understand the issue properly start using IDE like eclipse rather than simply using a notepad and compiling code through java/javac
A more suitable code would be like as below. Type q in console when u want to exit from the program.
public static produktas[] surasti(produktas G[], int n) {
BufferedReader consoleReader = null;
produktas produktasFound[] = new produktas[5]; // Initalize array to store the produkt found
try {
consoleReader = new BufferedReader(new InputStreamReader(System.in));
boolean exit = false;
produktas produktasFound[] = new produktas[5];
int j = 0;//current produktFound index
while (!exit) {
System.out.println("Kokio produkto ieskosime?");
String produktPav = in.readLine();
if ("q".equals(produktPav)) {
exit = true;
} else {
for (int i=1; i<n; i++){
if (found.equals(G[i].gautiPav())){
A[j] = G[i];
j++;
}
}
}
if(j == 5)
exit = true;
}
return produktasFound; // return all the 5 produktas found
} catch (IOException e) {
e.printStackTrace();
} finally {
if (consoleReader != null) {
try {
consoleReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return produktasFound; //If no produkt is found from the array returned is blank
}
Your comparison operator is not correct. Try the following code :
public static produktas surasti(produktas G[]) {
produktas max = G[0];
for (int i = 0; i < G.length; i++) {
if (max.gautiSvori() < G[i].gautiSvori()) {
max = G[i];
}
}
return max;
}
You need to pass the array and set the first element of the array as the maximum as by default first. Next iterate through the array and check whether there is a produktas with a higher value of svoris. If so, change the max to point to this new produktas. At the end of the for loop, you will now have the max set to the produktas with the highest value of svoris.
There are few things in the code that you can fix for better quality code.
You don't need to pass the array size to the surasti method. We can just do a G.length (in the code above I have done that).
Best practice is to user Camel case for Java classes. Therefore instead of produktas, use Produktas
Use meaningful names for variables instead of A, G, etc

Sequential Search of an Array

i am in desperate need of more help this week. My professor is sub par and makes no effort to clear things up.
The Problem:
import a file and search for a specific piece of data that is requested by a user.
The output must return something similar to:
Sequential found ID number 77470, and its price is $49.55.
or
Sequential did not find ID number 77777.
I have no idea where to go from here, or even if this is correct....
public class MainClass
{
public static void main(String[] args)
{
Payroll acmePay = new Payroll();
Scanner myScanner = new Scanner(System.in);
int target;
acmePay.loadEmpNums();
System.out.println("Enter the product number you would like to search: ");
target = myScanner.nextInt();
System.out.print(acmePay.seqSearch(target));
myScanner.close();
}//END main
}//END class MainClass
Payroll Class:
public class Payroll
{
private int[] empNums = new int[1000];
private int empCount = 0;
Payroll(){} //Currently nothing done in constructor
public void loadEmpNums()
{
String name;
double salary;
empCount = 0; //Just to make sure!
try
{
String filename = "employees.dat";
Scanner infile = new Scanner (new FileInputStream(filename));
while (infile.hasNext())
{
//Read a complete record
empNums[empCount] = infile.nextInt();
name = infile.nextLine();
salary = infile.nextDouble();
//Increment the count of elements
++empCount;
}
infile.close();
}
catch (IOException ex)
{
//If file has problems, set the count to -1
empCount = -1;
ex.printStackTrace();
}
}//END loadEmpNums
public int seqSearch (int target)
{
int ind = 0;
int found = -1;
while (ind < empCount) {
if(target==empNums[ind])
{
found = ind;
ind = empCount;
}
else
{
++ind;
}
}
return found;
}
}//END class Payroll
Are you reading in from a txt file or are they entering the data in when you run the program?

Making a Program that Reads and Writes Data - Then Computes Min, Max, Average

I'm making a program that reads some data from a text file and then takes that data and finds the minimum, maximum, and average of the numbers. For some reason I'm getting a lot of ridiculous errors I've never seen before. Here is my code:
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
public class Lab1 {
static int count = 0;
static int[] newData2 = new int[count];
// Method for reading the data and putting it into different arrays
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
}
static int min(int[] newData2) {
int min = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] < min) {
min = newData2[i];
}
}
return min;
}
static int max(int[] newData2) {
int max = newData2[0];
for (int i = 0; i < newData2.length; i++) {
if (newData2[i] > max) {
max = newData2[i];
}
}
return max;
}
static double average(int[] newData2) {
double average = 0;
int sum = 0;
for (int i = 0; i < newData2.length; i++) {
sum = newData2[i];
}
average = sum / newData2.length;
return average;
}
/*
* static int stddev(int[] newData2) { int[] avgDif = new
* int[newData2.length]; for(int i = 0; i < newData2.length; i++) {
* avgDif[i] = (int) (average(newData2) - newData2[i]); }
*
* }
*/
void write(String newdata, int min, int max, double average, int stddev) {
try {
File file = new File("stats.txt");
file.createNewFile();
FileWriter writer = new FileWriter("stats.txt");
writer.write("Minimum: " + min + "Maximum: " + max + "Average: " + average);
writer.close();
}catch(Exception e) {
System.out.println("Unable to write to the file.");
}
public static void main(String[] args) {
}
}
}
I have an error in my readData method, and it tells me that:
This method must return a result type of int[].
I'm literally returning an int array so I don't understand what the problem here is.
Then in my main method it says void is an invalid type for the variable main.
Here are some pointers:
each exit point of a method returning something must return something, if the line new Scanner(f); throws an exception, the first return is not reached, so you need a default one, like this:
private int[] readData() {
File f = new File("data.txt");
int count = 0;
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt(); // maybe you should handle the case where your input is too large for the array "newData"
}
return Arrays.copyOf(newData, count);
} catch (Exception e) {
System.out.println("Could not read the file.");
}
return null;
}
To reduce the size of an array, you should use Arrays.copyOf (see below)
You should avoid static fields (and in your case none are required)
Your method min and max are assuming there are elements in the array (at least one), you should not do that (or test it with an if):
private int min(int[] data) {
int min = Integer.MAX_VALUE; // handy constant :)
for (int i = 0; i < data.length; i++) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
private int max(int[] data) {
int max = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
In your average method there are a few mistakes:
private double average(int[] data) {
int sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i]; // here if you want a sum it's += not =
}
return (1.0 * sum) / data.length; // you want a double division, local "average" was useless
}
arrays are iterables so you can use "new style" for loops:
for (int value : newData) {
// use value
}
Some reading:
Java Integer division: How do you produce a double?
“Missing return statement” within if / for / while
static int[] readData() {
File f = new File("data.txt");
int[] newData = new int[100];
try {
Scanner s = new Scanner(f);
while (s.hasNext()) {
newData[count++] = s.nextInt();
}
for (int i = 0; i < newData2.length; i++) {
newData[i] = newData2[i];
return newData2;
}
} catch (Exception e) {
System.out.println("Could not read the file.");
}
//TODO: return something here if there is some kind of error
}
Because of the try-catch block you need to account for every possibility that could occur. When you return the array when the program succeeds you are expecting a return, but when there is an exception the program still expects a return value, but you did not provide one.

IndexOutOfBoundsException while accessing List

I'm working on a project for a class, and I think I've got it mostly figured out, but it keeps giving me different Exception errors and now I'm stumped.
The instructions can be found here: http://www.cse.ohio-state.edu/cse1223/currentsem/projects/CSE1223Project11.html
Here is the code I have thus far, currently giving me and IndexOutOfBounds exception in the getMaximum method.
Any help would be much appreciated.
import java.io.*;
import java.util.*;
public class Project11a {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an input file name: ");
String fileName = keyboard.nextLine();
Scanner in = new Scanner(new File(fileName));
System.out.print("Enter an output file name: ");
String outFile = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(outFile);
while (in.hasNextLine()) {
String name = in.nextLine();
List<Integer> series = readNextSeries(in);
int mean = getAverage(series);
int median = getMedian(series);
int max = getMaximum(series);
int min = getMinimum(series);
outputFile.printf("%-22s%6d%n", name, mean, median, max, min);
}
in.close();
outputFile.close();
}
// Given a Scanner as input read in a list of integers one at a time until a
// negative
// value is read from the Scanner. Store these integers in an
// ArrayList<Integer> and
// return the ArrayList<Integer> to the calling program.
private static List<Integer> readNextSeries(Scanner inScanner) {
List<Integer> nextSeries = new ArrayList<Integer>();
while (inScanner.hasNextInt()) {
int currentLine = inScanner.nextInt();
if (currentLine != -1) {
nextSeries.add(currentLine);
} else {
break;
}
}
return nextSeries;
}
// Given a List<Integer> of integers, compute the median of the list and
// return it to
// the calling program.
private static int getMedian(List<Integer> inList) {
Collections.sort(inList);
int middle = inList.size() / 2;
int median = -1;
if (inList.size() % 2 == 1) {
median = inList.get(middle);
} else {
try {
median = (inList.get(middle - 1) + inList.get(middle)) / 2;
} catch (Exception e) {
}
}
return median;
}
// Given a List<Integer> of integers, compute the average of the list and
// return it to
// the calling program.
private static int getAverage(List<Integer> inList) {
int average = 0;
if (inList.size() == 0) {
return 0;
}
for (int i = 0; i < inList.size(); i++) {
average += inList.get(i);
}
return (average / inList.size());
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMaximum(List<Integer> inList) {
int max = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) > max) {
max = inList.get(i);
}
}
return max;
}
// Given a List<Integer> of integers, compute the maximum of the list and
// return it to
// the calling program.
private static int getMinimum(List<Integer> inList) {
int min = inList.get(0);
for (int i = 1; i < inList.size(); i++) {
if (inList.get(i) < min) {
min = inList.get(i);
}
}
return min;
}
}
Seemed like that your list is empty.
What can triggered the exception is the statement:
int max = inList.get(0);
So your inList do not have the value in the first index,which means the inList is empty.

Categories