Как определить палиндром в середине файла массива и распечатать только палиндром в новом файле - PullRequest
0 голосов
/ 31 октября 2019

Я пытаюсь создать код, который будет читать файл и идентифицировать палиндром, который находится в середине массива целых чисел (то есть 5 8 6 11 22 33 44 33 22 11 6 7). Я застрял в том, как это сделать, и исследование, которое я проводил в Интернете, имеет только решения для массивов, которые полностью палиндромны от начала до конца (то есть 11 22 33 44 33 22 11).

А также распечатать только палиндром в новом файле.

исследования, которые я проводил в Интернете, имеют только решения для массивов, которые полностью палиндромны от начала до конца (т.е. 11 22 33 44 33 22 11).

Вот файл с кодомв случае неправильной распечатки:

https://docs.google.com/document/d/1m8VzecxiRYheNTvnvW8i00t9I26cayaj3evteXXDaeQ/edit?usp=sharing

   import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Program_11_1
{
// ITP_120-002N; LEE Program_11_1
public static void main(String[] args)
{
    String file_name;
    String outputFileName = null;
    String done_string = "done";
    boolean done = false; 

    while (!done)   
    {
        file_name = JOptionPane.showInputDialog("Enter a file 
name"

   + " or done to exit: ");

        if (file_name.equals(done_string))
        {
            done = true;
            JOptionPane.showMessageDialog(null, 
"EXITING");
        }
        else        
        {
            Scanner input = get_Scanner(file_name);

            Scanner input_counter = 
get_Scanner(file_name);
            //JOptionPane.showMessageDialog(null, "File " 
+ file_name + " found ");

                outputFileName = 
JOptionPane.showInputDialog(null, "Enter the output file name: ");
            PrintWriter output_writer = 
get_Writer(outputFileName);
            //JOptionPane.showMessageDialog(null, "created 
output file: " + out_file_name);

            if ((input != null && output_writer != null && 
input_counter != null))
                {
                     //********TASK 
CODE**************

                        int num_ints = 
   size(input_counter);

                        int[] int_array = 
   return_Array(num_ints);                   

                        fill_Array(int_array, 
input);              

                        int palin_drome[] = 
   palin_Drome(int_array);                   


   print_Array(ordered_array, output_writer);
                    //*******END TASK CODE************
                 }

                input.close();
                input_counter.close();
                output_writer.close();  
            }
        }
    }


public static Scanner get_Scanner(String file_name) {
    try
    {
        File file_in = new File(file_name);
        Scanner input = new Scanner(file_in);
        return input;
    }
    catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(null, "File " + 
file_name +  " not found");
        return null;
    }
}

public static PrintWriter get_Writer(String out_file_name) {
    try 
    {
        PrintWriter output_writer = new 
PrintWriter(out_file_name);
        return output_writer;
    }
    catch (FileNotFoundException e) 
    {
        JOptionPane.showMessageDialog(null, "output file 
FAILED");
        return null;
    }
}


public static int size (Scanner input_file) {
    int counter = 0;
    while (input_file.hasNext()) {
        input_file.nextInt();
        counter++;
    }
    return counter;
}

public static int[] return_Array(int count) {
    int[] hold_ints = new int [count];
    return hold_ints;
}

public static void fill_Array(int[] int_array, Scanner input) {
    int index = 0; 
    for (int val : int_array) {
        int_array[index] = input.nextInt();
        index++;
        }
}

public static int[] palin_Drome(int[] un_ordered) {

            }
        }
    }
    return un_ordered;
}


public static void print_Array(int[] ordered, PrintWriter 
output_writer) {
    for(int i = 0; i < ordered.length; i++) {
        output_writer.print(ordered[i]);
        output_writer.print(" ");
    }
}

}

1 Ответ

0 голосов
/ 01 ноября 2019

Вот код Java, который вы можете включить в свой код Swing. Он обнаруживает первый самый длинный палиндром, затем останавливается.

import java.util.Arrays;

public class Palindrome {
    public static void main(String[] args){
        int[] arr = {5, 8, 6, 11, 22, 33, 44, 33, 22, 11, 6, 7};
        int[] arr2 = {1,0,2};
        int[] arr3 = {2};
        int[] arr4 = {};

        System.out.println(Arrays.toString(findPalindrome(arr)));
        System.out.println(Arrays.toString(findPalindrome(arr2)));
        System.out.println(Arrays.toString(findPalindrome(arr3)));
        System.out.println(Arrays.toString(findPalindrome(arr4)));
    }

    public static int[] findPalindrome(int[] arr) {
        if (arr == null) return null;
        int start = 0;
        int end = arr.length;
        if (end <= 1) {  // no need to check just return as it is
            return arr;
        }
        for (int offset = 0; offset < arr.length; offset++) {
            for (int j = 0; j <= offset; j++) {
                if (isPalindrome(arr, start + j, end - offset + j)) {
                    return Arrays.copyOfRange(arr, start + j, end - offset + j);
                }
            }
        }
        return null;
    }
    public static boolean isPalindrome(int[] arr, int start, int end){
        end = end - 1;
        if (start == end) {
            return false;  // when reduced to a single element return false
        }
        int endPoint = (end - start + 1)/2;
        for (int i = 0; i < endPoint; i++){
            if (arr[start + i] != arr[end - i]) {
                return false;
            }
        }
        return true;
    }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...