PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

[FIXED] How to change input String entry format from txt file reading

 August 18, 2022     file, input, java, output, string     No comments   

Issue

I have this input:

["joe","oej","rat","tar","art","atb","tab"]

Using this code:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        Map<String, List> ans = new HashMap<String, List>();
        for (String s : strs) {
            char[] ca = s.toCharArray();
            Arrays.sort(ca);
            String key = String.valueOf(ca);
            if (!ans.containsKey(key)) ans.put(key, new ArrayList());
            ans.get(key).add(s);
        }
        return new ArrayList(ans.values());
    }
}

It correctly gives me this output:

[["rat","tar","art"],["atb","tab"],["joe","oej"]]

However, the format of the input and output is not exactly how I'd like it.

I would prefer for the input file to be a txt file called input.txt and within it show as;

joe
oej
rat
tar
art
atb
tab

and for the output to be stored in a new txt file called output.txt like this;

atb tab
joe oej
art rat tar

What I have attempted to do to read the input txt file is within my main:

File file = new File(args[0]);
Scanner scan = new Scanner(file);

and to write my output file:

FileWriter writer = new FileWriter("output.txt");
writer.write(fileContent);
writer.close();

My question is: can the second letter segments be simply implemented into the class Solution?


Solution

If I understood correctly you would like to read the input from a file and write the output to a file directly in the Solution class. To do that you can create a new method in Solution and add that logic before and after calling groupAnagrams.

class Solution {
    public void fromFile(String inputFilename){
        // Open the file inputFilename here
        // Read the lines into a string array
        List<List<String>> groupAnagrams(strs);
        // Create the output file
        // Write the result in the file
    }
    public List<List<String>> groupAnagrams(String[] strs) {
        //...
    }
}

In this way you don't need to change the method groupAnagram.



Answered By - Marc
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing