Reading data from Csv File - java
How to find sequence of missing number from a CSV file using java Program?
I was using Arraylist taking some numbers into consideration.
I want to read entire CSV file Data And find the missing sequences on numbers.I have near about 1,00,000 records in the file.
Program:-
public class MissingNumber {
public static long count = 0;
public static int position = 0;
public static boolean flag = false;
public static void main(String[] args) {
long a[] = {1054023,1054024,1054025,1054026,1054027,1054028,1054029,1054030,1054031,1054032,1054748,1054749,1054750,1054751,
1054752,1054753,1054754,1054755,1054756,1054757,1054758,1055297,1055298,1055299,1055300,1055301,1055302,1055303,1055304,
1055305,1055306,1055307,1055308,1055309,1056868,1057170,1057461,1057563,1057627,1057628,1057629,1057630,1057631,1057632,
1057633,1057634,1057635,1057636,1057637,1057652,1057653,1057654,1057656,1057657,1057661,1057662,1057663,1057664,1057665,
1057672,1057673,1057674,1057675,1057678,1057682,1057683,1057685,1057686,1057687,1057690,1057691,1057692,1057695,1057696,
1057697,1057698,1057699,1057701,1057702,1057705,1057706,1057707,1057708,1057710,1057712,1057718,1057722,1057729,1057730,
1057731,1057732,1057733,1057734,1057735,1057736,1057738,1057739,1057740,1057741,1057742,1057743,1057744,1057745,1057746,
1057747,1057748,1057749,1057750,1057751,1057752,1057753,1057754,1057755,1057756,1057757,1057758,1057759,1057762,1057763,
1057764,1057765,1057766,1057767,1057768,1057769,1057773,1057774,1057778,1057779,1057780,1057781,1057782,1057783,1057784,
1057785,1057786,1057787,1057788,1057789,1057790,1057791,1057792,1057793,1057794,1057795,1057796,1057797,1057798,1057799,
1057800,1057801,1057802,1057803,1057804,1057805,1057806,1057807,1057808,1057809,1057810,1057811,1057825,1057826,1057827,
1057829,1057838,1057843,1057857,1057858,1057859,1057860,1057861,1057862,1057863,1057864,1057865,1057866,1057867,1057868,
1057869,1057870,1057871,1057872,1057873,1057874,1057875,1057876,1057884,1057885,1057886,1057887,1057888,1057889,1057890,
1057891,1057892,1057893,1057894,1057895,1057896,1057897,1057898,1057899,1057900,1057901,1057902,1057903,1057905,1057906,
1057907,1057908,1057909,1057910,1057911,1057912,1057913,1057914,1057915,1057916,1057917,1057918,1057919,1057920,1057921};
findMissingNumbers(a, position);
}
private static void findMissingNumbers(long a[], int position) {
if (position == a.length - 1)
return;
for (; position < a[a.length - 1]; position++) {
if ((a[position] - count) != position)
{
System.out.println("position"+position);
System.out.println("Missing Number: " + (position + count));
flag = true;
count++;
break;
}
}
if (flag) {
flag = false;
findMissingNumbers(a, position);
}
}
}
I assume your array is already sorted. If so itreate through and find the missing nrs like you were doing it manually; compare two neighbors and if the difference is more than one print the numbers missing. something like this:
public class MissingNumber {
public static void main(String[] args) {
long a[] = {1,2,3,5,9,11,23,24,25,26,27,28,39}; //try first on small arrays
findMissingNumbers(a);
}
private static void findMissingNumbers(long a[]) {
for(int i = 0; i<a.length-1; i++){
if(a[i+1]- a[i] > 1){
System.out.println("missing nr at index: " + (i+1));
System.out.println("missing nrs");
for (int j = 1;j<a[i+1]-a[i];j++){ // for ex. if a[i] = 13 and a[i+1]= 17 difference is 4 and there are 3 missing nrs.
System.out.println(a[i]+j);
}
}
}
}
}
And to easily read from csv file i recomend opencsv
Related
How to count steps for complete the linear Search
I have an array,I Search one element using linear Search.But I want to count after how many steps I got the result. But I am not able to count the steps ,I am able to only search the element from the array,But not able to find the steps. LinearSearhc.java public class ArrayRotation { public static int linearSearch(int []arr,int x){ int n = arr.length-1; for (int i=0;i<=n;i++){ if (arr[i]== x) return i; } return -1; } public static void main(String[] args) { ArrayRotation arrRotation = new ArrayRotation(); int arr[]={4,56,44,152,54,845}; int x = 26; int result = linearSearch(arr,x); if (result == -1) System.out.println("searching element not Present in this array"); else System.out.println("Searching element present at the index position" +result); } }
Since we cannot return 2 values in a method in Java, we can instead return a Array with 2 values, one being if the linear search found the element and other being the amount of steps. Change the linearSearch Method to public static int[] linearSearch(int []arr,int x){ int steps = 0; int[] result = {-1,0}; int n = arr.length-1; for (int i=0;i<=n;i++){ steps++; if (arr[i]== x) { result[0] = i; break; } } result[1] = steps; return result; } Then change the code in the Main Method to take in a array as result and the first index will be the Integer if found and the second will be the amount of steps. Example public static void main(String[] args) throws IOException { int arr[]={4,56,44,152,54,845}; int[]result = linearSearch(arr,54); if (result[0] == -1) System.out.println("searching element not Present in this array"); else System.out.println("Searching element present at the index position " +result[0]+" in "+result[1]+" steps"); }
Since is a linear search it will search all the elements to say -1 or stop when it finds it you can count the steps adding a counter inside the for loop class Playground { public static void main(String[] args) { ArrayRotation arrRotation = new ArrayRotation(); int arr[]={4,56,44,152,54,845}; int x = 26; int result = arrRotation.linearSearch(arr,x); if (result == -1) System.out.println("searching element not Present in this array"); else System.out.println("Searching element present at the index position " +result); } } public class ArrayRotation { public static int linearSearch(int []arr, int x){ int n = arr.length-1; int counter = 0; int position = -1; for (int i=0; i <= n; i++) { counter++; if (arr[i] == x) { position = i; break; } } System.out.println("searching element stop after counting " + counter); return position; } }
how to count many times a character occurs in a string without using s loop
the code below is meant to count each time character 'x' occurs in a string but it only counts once .. I do not want to use a loop. public class recursionJava { public static void main(String args[]) { String names = "xxhixx"; int result = number(names); System.out.println("number of x: " + result); } public static int number (String name) { int index = 0, result = 0; if(name.charAt(index) == 'x') { result++; } else { result = result; } index++; if (name.trim().length() != 0) { number(name); } return result; } }
You could do a replacement/removal of the character and then compare the length of the resulting string: String names = "xxhixx"; int numX = names.length() - names.replace("x", "").length(); // numX == 4
If you don't want to use a loop, you can use recursion: public static int number (String name) { if (name.length () == 0) return 0; int count = name.charAt(0)=='x' ? 1 : 0; return count + number(name.substring(1)); }
As of Java 8 you can use streams: "xxhixx".chars().filter(c -> ((char)c)=='x').count()
Previous recursive answer (from Eran) is correct, although it has quadratic complexity in new java versions (substring copies string internally). It can be linear one: public static int number(String names, int position) { if (position >= names.length()) { return 0; } int count = number(names, position + 1); if ('x' == names.charAt(position)) { count++; } return count; }
Your code does not work because of two things: Every time you're calling your recursive method number(), you're setting your variables index and result back to zero. So, the program will always be stuck on the first letter and also reset the record of the number of x's it has found so far. Also, name.trim() is pretty much useless here, because this method only removes whitespace characters such as space, tab etc. You can solve both of these problems by making index and result global variables and using index to check whether or not you have reached the end of the String. So in the end, a slightly modified (and working) Version of your code would look like this: public class recursionJava { private static int index = 0; private static int result = 0; public static void main(String[] args) { String names = "xxhixx"; int result = number(names); System.out.println("number of x: " + result); } public static int number (String name){ if(name.charAt(index) == 'x') result++; index++; if(name.length() - index > 0) number(name); return result; } }
You can use StringUtils.countMatches StringUtils.countMatches(name, "x");
Need help converting iterative process to recursive
I am trying to convert the following iterative code: int rows = 3; for (int i = 0; i <= rows; i++) { for (int j = 0; j < i; j++) { System.out.print("*"); } for (int j = 0; j < rows-i; j++) { System.out.print("-"); } System.out.println(); } with the output: --- *-- **- *** to recursive code. This is for an assignment. I created the iterative code in hopes of being able to figure out how to directly convert it to recursive. Here's my effort of that: public void stringY(int star, int count){ if (star > 0){ System.out.print("*"); stringY(star - 1, count); } } public void stringX(int dash,int count){ if (dash == -1) { return; }else if (dash < count){ System.out.print("-"); stringX(dash - 1, count); } else if (dash == count){ stringX(dash - 1, count); } } public void printPattern(int n) { if (n == -1){ return; } else { printPattern(n-1); stringY(n, n); stringX(n, n); System.out.println(); } } My issue here is that while I get the output I am looking for with regard to the "*" part of the pattern, I have absolutely no clue how to get the "-" part of the pattern. Now being that this is an assignment I don't want any solutions, but any pointers in the right direction are absolutely welcome. I should note that my two requirements are: 1) I have to complete my assignment entirely without using loops and 2) I can use as many helper methods as I need, but the main calling method (printPattern) must stay public void and must continue to only accept integers. Further clarification: The other two methods in the recursive code block are helper methods I created.
First let m = number of '*' to print and let n = number of '-' to print For each recursion, increment m by 1 and decrement n by 1. public static void main(String[] args) { printPattern(3); } public static void printPattern(int n) { printing(n, n); } //Variable size basically represent the number of columns public static void printing(int n, int size) { //stop condition if(n == -1) return; //m is the number of * to print int m = size - n; printAsterisk(m); //n is the number of - to print printHyphen(n); System.out.println(); printing(n - 1, size); } public static void printAsterisk(int m) { if(m == 0) return; System.out.print('*'); printAsterisk(m - 1); } public static void printHyphen(int n) { if(n == 0) return; System.out.print('-'); printHyphen(n - 1); }
Think of it this way, they are all just loops doing some work. All you need is theoretically one recursive function that calls itself till the passed value. void loop(int i, int till, Worker doThis) { if (i>=till) return; doThis.work(i); loop(i+1, till, doThis); } Worker is just an interface, public interface Worker { void work(int index); } Now we need to pass the work that needs to be done. There are three loops, hence three calls to the loop function. final int rows = 3; // outer loop loop(0, rows+1, new Worker() { public void work(int index) { // Stars loop(0, index, new Worker() { public void work(int index) { System.out.print("*"); } }); // Dashes loop(0, rows-index, new Worker() { public void work(int index) { System.out.print("-"); } }); System.out.println(); } });
I would start by extracting then STAR and DASH, private static final String DASH = "-"; private static final String STAR = "*"; Next, I would write a method to repeat a String a given number of times. Also, I would use a StringBuilder (here I've done it recursively) private static StringBuilder repeat(StringBuilder sb, String str, int n) { if (n > 0) { sb.append(str); repeat(sb, str, n - 1); } return sb; } Next, a private recursive method to print the pattern based on StringBuilder private static void printPattern(StringBuilder sb, int s) { System.out.println(sb); int p = sb.indexOf(DASH, s); if (p > -1) { sb.replace(p, p + DASH.length(), STAR); printPattern(sb, s + STAR.length()); } } And finally the public method public static void printPattern(int n) { printPattern(repeat(new StringBuilder(), DASH, n), 0); }
Searching through Objects Issue
The program is to find all of the words in a text file and count how many times each word is found. Our definition of a "word" will be relatively crude and will be done by splitting the line based on characters that are not alphabetic. I know there are easier ways to go about this but we were required to use a class and a search method like the one I attempted. I can't figure out why it's not incrementing word's that are already in wordList. I believe it's either completely skipping over my if (foundAt >=0, or it's not incrementing it correctly, I'm leaning toward my search method being wrong, but I can't figure out the problem. Any and all help is much appreciated, thanks for your time. public class Hmwk { public static void main(String[] args) throws FileNotFoundException { int n=0; WordCount[] wordList= new WordCount[10000]; Scanner words = new Scanner(new File("input.txt")); while (words.hasNextLine() && n < 10000) { String line = words.nextLine(); String[] tokens = line.split("[^\\p{Alpha}]"); for (int i=0;i<tokens.length;i++) { if (tokens[i].length()>0) { WordCount word = new WordCount(tokens[i]); int foundAt = search(wordList, word, n); if (foundAt >= 0) { wordList[foundAt].increment(); } else { wordList[n]=word; n++; } } } } //Arrays.sort(wordList); String alphabeticFileName = "alphabetic.txt"; String frequencyFilename = "frequency.txt"; PrintWriter output = new PrintWriter(alphabeticFileName); for (int i=0; i<n;i++) { output.println(wordList[i].toString()); } output.close(); //Sort on frequency somehow PrintWriter output2 = new PrintWriter(frequencyFilename); for (int i=0; i < n; i++) { output2.println(wordList[i].toString()); } output2.close(); } public static int search(WordCount[] list,WordCount word, int n) { int result = -1; int i=0; while (result < 0 && i < n) { if (word.equals(list[i])) { result = i; } i++; } return result; } } class WordCount { String word; int count; static boolean compareByWord; public WordCount(String aWord) { setWord(aWord); count = 1; } private void setWord(String theWord) { word=theWord; } public void increment() { count=+1; } public static void sortByWord() { compareByWord = true; } public static void sortByCount() { compareByWord = false; } public String toString() { String result = String.format("%s (%d)",word, count); return result; } } Output: Peter (1) Piper (1) picked (1) a (1) peck (1) of (1) pickled (1) peppers (1) A (1) peck (1) of (1) pickled (1) peppers (1)
Your increment function is wrong. You've written: count =+1; Which only sets the count to one. To increment count by one you put: count += 1;
How to print the maximum valued path in a 2D array in Java?
I guess you all know the "strawberry" problem that some give you in job interviews, where you need to calculate the path between 2 corners of a 2D array that you can only move up or to the right and you have the calculate the maximum valued path. I have a perfectly working code that does it in Recursion, but it's complexity is to high. i also solved the problem in the "for loop" solution that does it in O(n^2) complexity. but in this solution i just couldn't figure out a way to print the route like i did in the recursion solution. This is my code (it is quite long to read here so i guess you should copy,compile and run). look at the results of the recursion solution, BTW - The path needs to be from the left bottom corner to the right upper corner I want to print the route the same way in the better solution: public class Alg { public static void main(String args[]) { String[] route = new String[100]; int[][]array = {{4,-2,3,6} ,{9,10,-4,1} ,{-1,2,1,4} ,{0,3,7,-3}}; String[][] route2 = new String[array.length][array[0].length]; int max = recursionAlg(array,array.length-1,0,route); int max2 = loopAlg(array,array.length-1,0,route2); System.out.println("The max food in the recursion solution is: "+max); System.out.println("and the route is: "); printRouteArray(route); System.out.println("The max food in the loop solution: "+max2); System.out.println("The route is: "); //SHOULD PRINT HERE THE ROUTE } public static int loopAlg(int [][] arr,int x, int y, String[][] route) { int n=0; int[][]count = new int[arr.length][arr[0].length]; for(int i = x; i>=0 ; i--) { for(int j = 0; j<arr[0].length; j++) { if (i==x && j==0) {count[i][j]=arr[i][j];} else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j];} else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; } else{ if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];} else { count[i][j]= count[i+1][j]+arr[i][j];} } } } return count[0][arr[0].length-1]; } public static int recursionAlg(int [][] arr, int x, int y,String[] route) { return recursionAlg(arr,0,x,y,arr[0].length-1,route,0); } public static int recursionAlg(int[][]arr,int count,int x, int y, int max_y, String[] route, int i) { if (x == 0 && y == max_y) {return count;} else if (x == 0) { route[i]="Right"; return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1); } else if (y==max_y){ route[i]="Up"; return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1); } else if (recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1)>recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1)) { route[i]="Up"; return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1); } else { route[i]="Right"; return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1); } } public static void printRouteArray(String[] arr) { int i=0; while (i<arr.length && (arr[i]=="Up" || arr[i]=="Right")) { System.out.print(arr[i]+"-->"); i++; } System.out.println("End"); } } Hope you can help, thanks!
You need another 2-dimensional array inside loopAlg that memorizes which step to take to come to this next entry for every entry in your initial 2-dim array. See the following code and https://ideone.com/kM8BAZ for a demo: public static void main(String args[]) { String[] route = new String[100]; int[][]array = {{4,-2,3,6} ,{9,10,-4,1} ,{-1,2,1,4} ,{0,3,7,-3}}; String[] route2 = new String[100]; int max = recursionAlg(array,array.length-1,0,route); int max2 = loopAlg(array,array.length-1,0,route2); System.out.println("The max food in the recursion solution is: "+max); System.out.println("and the route is: "); printRouteArray(route); System.out.println("The max food in the loop solution: "+max2); System.out.println("The route is: "); printRouteArray(route2); } public enum Dirs {START, FROM_LEFT, FROM_DOWN}; public static int loopAlg(int [][] arr,int x, int y, String[] route) { int n=0; int[][]count = new int[arr.length][arr[0].length]; Dirs[][] directions = new Dirs[arr.length][arr[0].length]; List<String> path = new ArrayList<String>(); for(int i = x; i>=0 ; i--) { for(int j = 0; j<arr[0].length; j++) { if (i==x && j==0) {count[i][j]=arr[i][j]; directions[i][j] = Dirs.START;} else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j]; directions[i][j] = Dirs.FROM_LEFT;} else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; directions[i][j] = Dirs.FROM_DOWN;} else{ if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];directions[i][j] = Dirs.FROM_LEFT;} else { count[i][j]= count[i+1][j]+arr[i][j];directions[i][j] = Dirs.FROM_DOWN;} } } } int i=0, j=arr[0].length-1; while(directions[i][j]!= Dirs.START) { if(directions[i][j] == Dirs.FROM_LEFT) { path.add("Right"); j--; } else { path.add("Up"); i++; } } Collections.reverse(path); i=0; for(String part:path) { route[i] = part; i++; } return count[0][arr[0].length-1]; }