2

I'm new to Dynamic Programming so I tried to create a file and write it onto Array.txt in the download section. The logic is:

If the Array is longer than the current array: Extend the array and copy to old array onto the new one

I, however, can't find a way to actually copy the section of the old array onto the new one. The way that I am using right now is

System.arraycopy()

Here is the code: (Remember to swap out YOURUSERNAME with your current username on the computer to avoid getting an error)

import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Fibonacci {

    static void createFile() {
        try {
            File Array = new File("C:\\Users\\YOURUSERNAME\\Downloads\\Array.txt");
            if (Array.createNewFile()) {
                System.out.println("File created: " + Array.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }

    static void fileWrite(int[] array, int num) {
        try {
            FileWriter myWriter = new FileWriter("C:\\Users\\YOURUSERNAME\\Downloads\\Array.txt");
            if (num <= array.length) {
                int[] newA = new int[array.length];
                System.arraycopy(array, 0, newA, 0, array.length);
                myWriter.write(Arrays.toString(newA));
                myWriter.close();
            }
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }


    static int[] fileRead(int[] Array1) {
        try {
            StringBuilder dataTotal = new StringBuilder();
            File Array = new File("C:\\Users\\YOURUSERNAME\\Downloads\\Array.txt");
            Scanner myReader = new Scanner(Array);
            while (myReader.hasNextLine()) {
                String data = myReader.nextLine();
                dataTotal.append(data);
            }
            myReader.close();
            System.out.println(dataTotal);
            dataTotal.deleteCharAt(0);
            dataTotal.deleteCharAt(dataTotal.length() - 1);
            String[] array1 = dataTotal.toString().split(", ");
            int[] array = new int[array1.length];
            for (int i = 0; i < array1.length; i++) {
                array[i] = Integer.parseInt(array1[i]);
            }
            return array;
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
            return null;
        }
    }

    static int[] arrayCreator(int num) {
        return new int[num];
    }

    static int fib(int num, int[] array1) {
        int[] array = fileRead(array1);
        if (num == 1 || num == 2) {
            return 1;
        }
        else {
            assert array != null;
            if(array[num - 1] > 0) {
                return array[num - 1];
            } else {
                array[num - 1] = fib(num - 1, array1) + fib (num - 2, array1);
                fileWrite(array, num);
            }
        }
        return array[num - 1];
    }
    public static void main(String[] args) {
        int num = 10;


        int[] array = arrayCreator(num);
        createFile();
        fileWrite(array, num);
        System.out.println(fib(num, array));
    }
}
5
  • 2
    The fileWrite() method should only be responsible for writing an array to file, it should not be doing any array copying. Your code should be building the array in memory, and only calling fileWrite() once at the end. Take a step back and re-think what you're doing. Commented Apr 11, 2020 at 15:22
  • I think using fileWrite() to copy the array then write it in the text file is the most logical thing to do because it saves a lot of time to complile as I don't need to add a new function just to use it once. Commented Apr 11, 2020 at 16:53
  • Writing to a file takes time, so by writing entire content to the file repeated, rather than waiting until the end, will certainly not "save a lot of time", it will unnecessarily slow down the program (a lot). --- Also, the programming guideline of "separation of concern" means that a method called writeFile should do just that, white the content of an array to file. It shouldn't be responsible for copying values from one array to another. Commented Apr 11, 2020 at 16:56
  • Ok, so I should make another function? Commented Apr 11, 2020 at 17:06
  • I don't know. Why would you make another function. Where is it that you need the array to be bigger than it currently is? Why wouldn't you extend the array length at that point in the code? Commented Apr 11, 2020 at 17:12

1 Answer 1

2

To extend an array by one element, you have two choices:

  • Using System.arraycopy()

    int[] newArray = new int[array.length + 1];
    System.arraycopy(array, 0, newArray, 0, array.length);
    array = newArray;
    
  • Using Arrays.copyOf()

    array = Arrays.copyOf(array, array.length + 1);
    
Sign up to request clarification or add additional context in comments.

6 Comments

I didn't want to extend the array by one element, I wanted it to copy over the results that exist to the new array that's not limited to 1 more element only
@MaxPan That is an example. Specify whatever new size you want the new array to have.
Ok, but isn't that what I have done in the code? System.arraycopy(arrayO, 0, array, 0, arrayO.length);
@MaxPan Where are you doing that? The only arraycopy() that I can see is in the fileWrite() method, where it certainly doesn't belong, and you always call it with same array as both parameters, so where are you doing the "extend the array and copy old array onto the new one" as instructed?
Ok, instead of that, I made it so the parameter is "int num, int[] array" where num is the number of elements and array is the array to be updated. You can see the new fileWrite() in the post again.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.