The file that my program is reading contains space separated numbers such "59 23 2 84 83", if i am sure that the # "84" occur only 36 times but bitset.cardinality() report 293 times.. please help
static int line_counter = 0;
static TreeMap<String, BitSet> ItemsArray = new TreeMap<String, BitSet>();
public static void main(String[] args) throws IOException {
String[] line;
BufferedReader br = new BufferedReader(new FileReader("abc.txt"));
while (br.ready()) {
line = br.readLine().split(" ");
Arrays.sort(line);
ItemsArray(line);
line_counter++;
}
System.out.println("ItemsArray cardinality = " + ItemsArray.get("84").cardinality() + "\n");
}
private static void ItemsArray(String[] line) {
BitSet temp_bitset = new BitSet();
for (String item : line) {
temp_bitset.clear();
if (ItemsArray.get(item) == null) {
temp_bitset.set(line_counter);
ItemsArray.put(item, temp_bitset);
} else {
temp_bitset = (BitSet) ItemsArray.get(item).clone();
temp_bitset.set(line_counter);
ItemsArray.put(item, temp_bitset);
}
}
}
Your problem is that there is only one BitSet for each line. You then confuse matters by replacing it with one from the map if the number repeats in several lines which therefore may actually be from a different line. You then seem to clear it for no real reason. You then seem to think clone is the solution to all of the above problems.
Here's an idea:
static int line_counter = 0;
static TreeMap<String, BitSet> allBits = new TreeMap<String, BitSet>();
public static void main(String[] args) throws IOException {
String[] line;
BufferedReader br = new BufferedReader(new FileReader("abc.txt"));
while (br.ready()) {
line = br.readLine().split(" ");
Arrays.sort(line);
consumeItems(line);
line_counter++;
}
System.out.println("ItemsArray cardinality = " + allBits.get("84").cardinality() + "\n");
}
private static void consumeItems(String[] line) {
for (String item : line) {
BitSet temp = allBits.get(item);
if (temp == null) {
temp = new BitSet();
allBits.put(item, temp);
}
// Use a bit in the BitSet to indicate that this number appeared in tat line.
temp.set(line_counter);
}
}
Not sure it's what you need but it demonstrates the normal technique for creating/updating map entries.
Related
I have a problem.It seems like if I have an input like this:
"Thanks Thanks Thanks car car"
The output will be "thanks". If my word starts with an uppercase letter it will print that word with a lowercase letter.
What can I add to my solution to solve that problem?
public class Main {
public static void main(String[] args) throws IOException {
String line;
String[] words = new String[100];
Map < String, Integer > frequency = new HashMap < > ();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((line = reader.readLine()) != null) {
line = line.trim();
if (!line.isEmpty()) {
words = line.split("\\W+");
for (String word: words) {
String processed = word.toLowerCase();
processed = processed.replace(",", "");
if (frequency.containsKey(processed)) {
frequency.put(processed,
frequency.get(processed) + 1);
} else {
frequency.put(processed, 1);
}
}
}
}
int mostFrequentlyUsed = 0;
String theWord = null;
for (String word: frequency.keySet()) {
Integer theVal = frequency.get(word);
if (theVal > mostFrequentlyUsed) {
mostFrequentlyUsed = theVal;
theWord = word;
} else if (theVal == mostFrequentlyUsed && word.length() <
theWord.length()) {
theWord = word;
mostFrequentlyUsed = theVal;
}
}
System.out.printf(theWord);
}
To let the code print the most frequent word in the format it was entered and not in lowercase, You can change below line of code.
String processed = word.toLowerCase();
Change it to :
String processed = word;
But then be aware then containsKey() method is case-sensitive and won't consider "Thanks" and 'thanks" as the same word.
Please find the below program which print both upper and lower case based on input.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] strArr=reader.readLine().split(" ");
String result=null;
int maxCount=0;
Map<String, Integer> strMap=new HashMap<String, Integer>();
int count=0;
for(String s:strArr){
count=0;
if(strMap.containsKey(s)){
count=strMap.get(s);
strMap.put(s,++count);
}else{
strMap.put(s, ++count);
}
}
//find Maximum
for(Map.Entry<String, Integer> itr: strMap.entrySet()){
if(maxCount==0){
maxCount=itr.getValue();
result=itr.getKey();
}else{
if(maxCount < itr.getValue()){
maxCount=itr.getValue();
result=itr.getKey();
}
}
}
// No of occurences with count
System.out.println("word"+ result+"count"+ maxCount);
printInLowerOrUpperCare(result);
}
public static void printInLowerOrUpperCare(String result){
if(result.charAt(0) >='a' && result.charAt(0) >= 'z' ){
System.out.println(result.toUpperCase());
}else{
System.out.println(result.toLowerCase());
}
}
}
hi i am trying to use ngrams on this data set ( number of attacks) but i am confused to how to merge the 2 methods together so that the n-grams can spot the frequency on how many times they appear. i am just trying to data process but i am confused. any help would be appreciated thank you.
This is what i have done so far. as you can see the main method holds the dataset but how can i merge all methods together so that the Ngrams runs on the data. thank you
public class MainProcess {
public static void main(String args[]) throws IOException
{
FileReader readhandle = new
FileReader("/Users/muhammad/Desktop/ADFA-
LD/Attack_Data_Master/Adduser_1/UAD-Adduser-1-=1.txt");
BufferedReader br = new BufferedReader(readhandle);
String line = null;
while((line = br.readLine()) != null)
{
System.out.println(line);
}
br.close();
readhandle.close();
}
public class Ngrams {
ArrayList<String> nGrams = new ArrayList<String>();
public void generateNGrams(String str, int n) {
if (str.length() == n ) {
int counter = 0;
while (counter < n) {
nGrams.add(str.substring(counter));
counter++;
}
return;
}
int counter = 0;
String gram = "";
while (counter < n) {
gram += str.charAt(counter);
counter++;
}
nGrams.add(gram);
generateNGrams(str.substring(1), n);
}
public void printNGrams() {
for (String str : nGrams) {
System.out.println(str);
}
}}
}
I have a file reader that reads the text
(a,b) (b,c) (c,d) (f,g) (c,g) (c,t) (h,i) (j,y)
and displays
a,b
b,c ....
is there a way to use these indexes as arguments for a method I call right after i'm done reading it? so far I seem to only effect the string split while i'm inside my While loop, is there a way to take value a and use it for method like
add.edge("argument0","argument1") where 0 is a, and 1 is b?
Code:
import java.io.*;
class reader{
public static void main(String[] args)throws Exception{
File file = new File("test.txt");
BufferedReader fi = new BufferedReader(new FileReader(file));
String num;
int count = 0;
while ((num = fi.readLine()) !=null) {
String [] add = num.split(" ");
for(int i=0; i<add.length;i++){
String [] add2 =add[i].split("[)(]+");
for (String val: add2){
System.out.println(val);
}
}
}
}
}
i think you are trying to achieve some thing like following :D
i changed your code a little bit i used sub string instead of regular expression
import java.io.*;
class reader{
public static void main(String[] args)throws Exception{
File file = new File("test.txt");
BufferedReader fi = new BufferedReader(new FileReader(file));
String num;
int count = 0;
while ((num = fi.readLine()) !=null) {
String [] add = num.split(" ");
for(int i=0; i<add.length;i++){
String pair = add[i].substring(1, 4);
someFunction(pair.split(","));
}
}
}
public static void someFunction(String[] args)
{
if(args.length > 0)
System.out.println(args[0] + " and " + args[1]);
}
}
If you want to use the result of the split function outside the while loop you need to save the results to a variable that is defined before the while loop. This is because currently the scope of the add2 variable in inside the for loop and thus you will only be able to use it inside the for loop. If you want to save pairs of Strings then I suggest creating a helper class Pair:
class Pair {
private String el1;
private String el2;
public Pair(String el1, String el2) {
this.el1 = el1;
this.el2 = el2;
}
// getters
}
and make a list of pairs defined before the while loop:
List<Pair> pairs = new ArrayList<>();
and in your for loop, add new pairs to the list:
pairs.add(new Pair(add2[0], add[1])));
Then you can access the list elements outside the while loop like so:
for (Pair pair : pairs) {
add.edge(pair.getEl1(), pair.getEl2());
}
I read a text file that looks like this:
operationName1 Value
There is a variable number of lines, with different operations and corresponding value. I can read the file and get a 2D String array as the output. This is my code.
try{
Path path = Paths.get("./myFile.txt");
String[][] array = Files.lines(path)
.map(s -> s.split("\\s+", 2))
.map(a -> new String[]{a[0], a[1]})
.toArray(String[][]::new);
}catch(IOException e){
}
Question: How could I change my code to get a 2d int array instead, where operationName1 would be "0" and operationName2 would be "1" (there is only two possible operation, each defined by a specific string)?
This text file:
operationOne 5
OtherOp 999
operationOne 8
operationOne 2
Would become that 2d int array:
[[0,5],[1,999],[0,8],[0,2]]
The index is important too. So the 1st line of the text file is the 1st line of my array.
PS: If there is a better syntax (a more recent one), I am open to suggestion.
Thank you very much.
If you need parallelism? ... this could be one approach
AtomicInteger atomicInteger = new AtomicInteger(0);
Map<String, Integer> known = new ConcurrentHashMap<>();
Path path = Paths.get("./myFile.txt");
int[][] array = Files.lines(path)
.map(s -> s.split("\\s+", 2))
.map(a -> new int[]{
known.computeIfAbsent(a[0],
k -> atomicInteger.getAndIncrement()),
Integer.parseInt(a[1])
})
.toArray(int[][]::new);
I normally use the Scanner class for read text files
ArrayList<String[]> array = new ArrayList();
Scanner scan= new Scanner(new File("./myFile.txt"));
String str;
String auxiliary= new String[2];
while(scan.hasNextLine()){
str= scan.readLine();
auxiliary=str.split(" "); // you can use also the \\s
for(int i=0; i<array.size();i++){
if(array.get(i)[0].equals(auxiliary[0])){
String aux2[]={i,auxiliary[1]};
break;
}
}
String aux2[]={array.size,auxiliary[1]};
}
I hope it helped.
# EDIT: Corrected some issues
It is a bit long, but it allows you to go operationName1...operationNameN
I always try to keep the code clean, so if you have any questions just ask
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
ArrayList<String> operations = new ArrayList<String>();
ArrayList<Point> points = new ArrayList<Point>();
String line;
String[] array;
int index;
while((line = bufferedReader.readLine()) != null)
{
array = line.split(" ");
if((index = hasOperation(array[0], operations)) == -1)
{
operations.add(array[0]);
index = operations.size()-1;
points.add(new Point(index, Integer.parseInt(array[1])));
}
else
{
points.add(new Point(index, Integer.parseInt(array[1])));
}
}
System.out.print("[");
for(int i = 0; i < points.size()-1; i++)
{
System.out.print(points.get(i).toString() + ",");
}
System.out.println(points.get(points.size()-1).toString()+"]");
}
public static int hasOperation(String operation, ArrayList<String> operations ){
for(int index = 0; index < operations.size(); index++)
{
if(operation.equalsIgnoreCase(operations.get(index)))
return index;
}
return -1;
}
}
public class Point {
public int x;
public int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
#Override
public String toString()
{
return "[" + x + "," + y + "]";
}
}
i have heavy .txt file. it contains a format Like this:
0 1 2 3 4 5 6 7 ... n
0 A, B, c, D, E, F, G, H,
1 AA, BB, CC, DD, EE, FF, GG, HH,
2
3
.
.
n
i want to save each row in Map.
for example in first row: map<0,A> . map<1,B>, Map<2,C>,...
then i want to save this maps in List. for example i want to save 100 rows in List.
for example if i write this function: "" list.get(1).get(4); "" i recived "EE"
it means first i have to go in 1 row, then i go to 4 and recive "EE".
could you please guidance me how to solve this problem?
i read some article about "spring batch" .and it related what i want
could you please help me how can i fix this problem?
public class spliter {
static int w=0;
private static HashMap<Integer,String> map = new HashMap<Integer,String>();
private static List<Map<Integer, String>> list=new ArrayList<Map<Integer,String>>();
public static void main(String[] args) throws IOException{
String string = null;
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\test.txt"));
while( (string = reader.readLine()) != null ) {
String[] parts = string.split(",");
int i=parts.length;
for(int j=0; j<i; j++){
map.put(j, parts[j]);
}
list.add(map);
w++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Something this simple can be solved using a Scanner to read each line and then String.split(...) to split each line. Something like:
while line exists
read line into String using Scanner
split String using String#split(...)
use array from split to create a list
add above list to master list
end while
Note that you can contain this in a list of lists, without the need of a Map, at all. List<List<String>> should do it for you.
I think that it would be more instructive to you for us to give you general advice like this, and then to see what you can do with it.
I have made into a Community Wiki, so all might contribute easily to this answer and so no-one will get reputation for up-votes.
I needed the same, i did it with yours in mind
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Spliter {
private static List<Map<String, Object>> list = new ArrayList<> ();
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\829784\\Desktop\\Repo\\Documentacion Repositorio\\test.txt"));
String line = "";
String firstline = reader.readLine();
while ((line = reader.readLine()) != null) {
Map < String, Object > map = new TreeMap < > ();
String[] partsfirstline = firstline.split(";");
String[] parts = line.split(";");
int i = parts.length;
for (int j = 0; j < i; j++) {
map.put(partsfirstline[j], parts[j]);
}
list.add(map);
}
System.out.println(list.get(0).values());
System.out.println(list.get(1).values());
}
}
you could us something like this
public class ArrayReader {
public static void main(String[] args) {
List<List<String >> array = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"));){
String line;
while ((line=br.readLine())!=null)
array.add(Arrays.asList(line.split(",")));
} catch (IOException e) {
e.printStackTrace();
}
}
}