How can I do this recursive search in java? - java

import java.util.*;
import java.io.*;
import java.io.CharArrayReader;
public class Program2 {
public static void main(String[] args) {
try {
String filename = args[0]; //reads command line argument 1 as filename
Scanner File = new Scanner(new File(filename)); //reads filename into program,and opens it for analysis
File.useDelimiter(System.getProperty("line.seperator"));
ArrayList<String> list = new ArrayList<>(); //creates an array list to store chars to transfer for reading from the file
while (File.hasNext()){
list.add(File.next());
}
File.close();
char[][] array1 = new char[10][20];
for (int i =0; i < list.size(); i++){
array1[i] = list.get(i).toCharArray();
}
} catch (FileNotFoundException e){
System.out.println("File is not found: " + e.getMessage() );//catches and sends out an error message
}
}
static int CharSearch(char[][] array1, char a, char b, char c){
for (int i =0 ; i < array1.length; i++){
for (int j =0; j < array1.length; j++){
while (a == 'A'){
return 1;
Hi all, so I have to make a program that reads in a file that is a 10x20 grid. The grid has letters A, B, C. All chars, in random order. What I need to do, is find a searching algorithm that checks for "groupings" of these letters.
Much like this much smaller version:
AABBACCA
CCABACBA
CCAAAABB
AAAACCCC
So see how there are 3 C groups, 2 B groups, and 3 A groups? (the groups can only be touching horizontally or vertically, not diagonally.)
I have to count that. I tried it, as can be seen on the bottom.
Also, I wanted to also make sure that the rest of my code makes sense and won't just pfft on me.
Thank you :)

Related

How do i access each character individually in a string array?

In this i need to take in a user imputed sentence and print it out in pig-latin.
(also i have several imports that aren't needed but I left them in when i copied the class and main lines from another program)
import static java.lang.System.*;
import java.util.*;
import java.lang.Math;
public class Pig_latin
{
public static void main(String[]args)
{
String sentence;
out.print("Enter a complete sentence: ");
Scanner sc = new Scanner(System.in);
sentence=sc.nextLine();
Here i am creating the string array and splitting at the spaces.
The only problem with this is that now each word is in its own object.
String s1[]=sentence.split(" ");
Because I've separated the words I don't know of a way to access each character to move them to the end or add "ay".
for(int x=0;x<s1.length;x++)
{
}
}
}
Heres a simple way of how you can get each character in a string in java. String.charAt(index) gets the current character at the index specified.
public static void main(String[] args) {
String getMyCharacters = "Hello World";
for(int i = 0; i < getMyCharacters.length();i++)
{
System.out.print(getMyCharacters.charAt(i));
}
}
output: Hello World
And this is one way of how you get the characters when you split each word into its own string.
String[] splitted = getMyCharacters.split(" ");
for(int j = 0; j < splitted.length; j++)
{
System.out.println("\nCurrent word:" + splitted[j]);
for(int y = 0; y < splitted[j].length(); y++)
{
System.out.println(splitted[j].charAt(y));
}
}
output:
Current word:Hello
H
e
l
l
o
Current word:World
W
o
r
l
d
You can refer each element of the array with s1[x], x is the index of the array s1, thereby saying you are looking up the xth element of the array.
for(int x=0;x<s1.length;x++)
{
System.out.println(s1[x]);
}

How to separate an array list into individual letters in Java

I am working on an assignment that wants me to create a program that accepts a text file with words in it, goes through every word, and then outputs the word with the most amount of double letters. So if a text file had 2 words, (past and progressive for example), it would output progressive. My problem is getting the program to compare each letter in a word. Specifically I cant seem to figure out how to split each word into its letters. Here is what I have so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Doubles {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
///Prompts the user to give a file.
System.out.println("Enter the location of your file...");
String location = keyboard.next();
Scanner file = null;
List<String> list = new ArrayList<String>();
///If the the file location is wrong, give an error.
try {
file = new Scanner(new File(location));
} catch (FileNotFoundException e) {
System.out.println("Error: File not found");
System.exit(1);
}
while(file.hasNext()){
String word = file.nextLine();
list.add(word);
}
///System.out.println(list);
keyboard.close();
doublefinder(list);
}
private static void doublefinder(List<String> list) {
///Code to separate and compare letters.
}
}
I have tried many different approaches but I can't seem to find a solution. Any help would be much appreciated.
You can use the .toCharArray method to create a char array where each element is a letter of the word.
http://crunchify.com/java-simple-way-to-convert-string-to-char-array/
An example implementation is as follows:
public static boolean isDoubleword(String str){
char[] letters = str.toCharArray();
for(int i = 0; i< letters.length-1; i++){
if(letters[i] == letters[i+1])return true;
}
return false;
}
The above function takes a string and returns if the string is a double word.
The method could look like that
private String doubleFinder(List<String> list){
int maxDoubleLetters = 0;
int maxDoubleLettersID = 0; // the position of the word in your list
for(int n = 0; n < list.size(); n++){ // cycle throught each word
String word = list.get(n); // get a word from the list
char[] letters = word.toCharArray(); // split the word into letters
int doubleLetters = 0;
for(int i = 1; i < letters.length; i++){ // search for all double letters
if(letters[i] == letters[i-1]) doubleLetters++;
}
if(doubleLetters > maxDoubleLetters){
maxDoubleLetters = doubleLetters;
maxDoubleLettersID = n;
}
}
if(maxDoubleLetters > 0)
return list.get(maxDoubleLetters);
else
return null;
}
The method shown above will return the word with the highest number of double letters. If the file does not contain any words with double letters the method will return null.
Note: This will not work for words containing triple letters.
If you have any more questions fell free to ask in the comment section.
Arem,
The approach that I would use is to make a method that takes in a string and returns the number of double letters. This can be accomplished using the String.toCharArray(); function. You can then iterate through that array to compare the letters to see how many double letters there are in a string.
e.g.
public static int numDoubles(String str) {
int numDoubles = 0;
char[] blah = str.toCharArray()
for(int i = 0; i < str.length(); i++ {
//if the character == nextChar
numDoubles++;
}
return numDoubles;
}
Use that return value to compare your strings.

Trying to insert text from file to 2D array. Java. Text is different formats

So I have a text file containing ints, doubles, strings that I need to read into a 2D array. there Array should have 6 columns but the rows are not known until you read the entire file. I'm guessing it is some 700 rows This is what I have so far. If I eliminate the array it prints fine but with the array I keep getting errors.
I have searched many questions like this but they usually only work with ints/doubles. Also please don't recommend arrayList as that has not been taught in our course.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class TitanicApp {
public static void main(String[] args) throws FileNotFoundException {
String[][] array=null;
int i=0, j=0;
String fileLine;
String s;
Scanner scannerIn=null;
BufferedReader inputStream=null;
try{
inputStream = new BufferedReader(new FileReader("titanic.txt"));
scannerIn = new Scanner(inputStream);
while ((fileLine = inputStream.readLine()) != null){
for (j=0;j<6;j++){
array [i][j]=scannerIn.next();
System.out.println(array[i][j]);
i++;
}
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
Sample text in file :
1 1 Allen, Miss. Elisabeth Walton female 29 211.3375
1 1 Allison, Master. Hudson Trevor male 0.9167 151.5500
And the output should be :
[ [1, 1, Allen, Miss. Elisabeth Walton, female, 29, 211.3375]
[1, 1, Allison, Master. Hudson Trevor, male, 0.9167, 151.5500]
]
I have a txt file containing the above info (and more lines) and I need to put it into a 2D array. I had to remove more than half of it since there was a limit.
So you want to do it using array only. You can consider below example as reference -
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TitanicApp {
int size = 10;
int colCount = 6;
String[][] array = null;
public static void main(String[] args) {
TitanicApp app = new TitanicApp();
app.startExec();
}
public void startExec() {
array = new String[size][colCount];
String fileLine;
int i=0;
try
{
BufferedReader inputStream = new BufferedReader(new FileReader("C:/titanic.txt"));
while ((fileLine = inputStream.readLine()) != null) {
addTo2DArray(fileLine.split("\\t"), ++i);
}
inputStream.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
// Now you have the desired array : array;
}
public void addTo2DArray(String[] tmpArray, int minCapacity) {
if((minCapacity > size)) {
size = (size * 3)/2 + 1;
String[][] newArray = new String[size][colCount];
for(int i=0; i<array.length; i++) {
for(int j=0; j<array[i].length; j++) {
newArray[i][j]=array[i][j];
}
}
array = newArray;
}
array[minCapacity-1] = tmpArray;
}
}
Another Solution :
String content = new Scanner(new File("/titanic.txt")).useDelimiter("\\Z").next();
String[] rows = content.split("\n");
String[][] finalArray = new String[rows.length][];
for(int i=0; i<rows.length; i++)
{
finalArray[i] = rows[i].split("\\t");
}
//Your desired array is : finalArray;
From what it looks like, you are incrementing both array locations, (i and j), at the same time. If you want the input to go in sequential order in the array increment j until array.size and then increment i. An example would be a nested for loop.
for(int i = 0; i < array.size; i++){
for(int j = 0; j < array.size; j++){
array[i][j] = scanner.next();
System.out.println(array[i][j]);
}
}
or in your case, stop incrementing the values until i and j get to 6 instead of array.size
I think you need declare a size for your String[][], otherwise you will get a NullPointerException. ArrayLists are the only way to dynamically generate the list as you move on as far as my knowledge goes.

read an input text file and strore the tokens in 2 different arrays in java

I am very new to java so please ignore if there are obvious mistakes. If my question seems redundant then please guide me towards the correct link. However, I have surfed enough in order to find the answer.
I am reading an input file and storing the elements of it in a 2D array. What I want to do is split that array in 2 separate arrays. 1st array would contain all the characters which is "firstDimension" in my code. Now, i want another array which stores all the integers in an array. I just have to print those arrays. This array should be created as soon as the special character '>' is observed.
This can be done in 2 ways:
Read the strings in the file and store all of the elements in a 2D array and then divide the array into 1 double and one 2D char array
Read only chars from the file and store it in char array and then read only double values from the file and store it in different array.
my input file has text:
a A b u>0.0001
b b X g>0.0005
Y z N H>0.0003
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Delimiter {
public static void main(String[] args)
{
try {
Scanner scanner = new Scanner(new File("hello.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
list.add(scanner.next());
}
scanner.close();
// finally convert the arraylist to a char[][]
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i = 0; i < firstDimension.length; i++)
{
for (int j = 0; j < firstDimension[i].length; j++)
{
//System.out.println(firstDimension[i][j]);
System.out.print(" "+firstDimension[i][j]);
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I don't know if there are any methods that do this for you, but you could say
if(var == 0 || 1 || 2 || 3 || 4 || 5 ) //all the way until you reach 9
{
//is a number and needs to be put in the double array
}
else //is a string
EDIT
Since you're storing the data in an array, you may have to use the BinarySearch method.

sorting strings using bubblesort in java

I tried sorting strings using bubblesort, but I dont know whether it makes any sense but can someone just help me figure out how to sort strings and let me know if my logic is correct? i have converted the strings to character just to check if they are in alphabetical order..eg app ban acc will be sorted to acc app and ban..can anyone give the logic to this problem.
import java.io.*;
import java.util.*;
class sort
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the strings");
String str=br.readLine();
StringTokenizer st=new StringTokenizer(str,",");
String s1=st.nextToken();
String s2=st.nextToken();
String s3=st.nextToken();
char ch1[]=s1.toCharArray();
char ch2[]=s2.toCharArray();
char ch3[]=s3.toCharArray();
if ((ch1[0]<ch2[0])&&(ch1[0]<ch3[0])&&(ch2[0]<ch3[0]))
for(int i=0;i<4;i++)
{
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
System.out.println(+ch3[i]);
}
else if((ch2[0]<ch1[0]&&ch2[0]<ch3[0]&&ch1[0]<ch3[0]) )
for(int i=0;i<4;i++)
{
System.out.println(+ch2[i]);
System.out.println(+ch1[i]);
System.out.println(+ch3[i]);
}
else if((ch3[0]<ch1[0])&&(ch3[0]<ch2[0])&&ch1[0]<ch2[0])
for(int i=0;i<4;i++)
{
System.out.println(+ch3[i]);
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
}
}
}
Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better. Wikipedia
The following is the sort-cut way to do so.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");//your sentence will be split into words.
Arrays.sort(strArr);
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
If you wish, you can apply your own logic as follows.
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");
String temp;
for(int i = 0; i<strArr.length - 1; i++)
{
for(int j = 0; j<strArr.length - 1; j++)
{
if(strArr[j].compareTo(strArr[j+1]) > 0)
{
temp = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = temp;
}
}
}
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
In both the cases, I have assumed spaces as word separator and not commas , that you're using in your example.
First you need to choose how do you want to sort strings ?
is it by length ? is it by alpha order ?
After you choose the appropriated method, you just need to sync it for the existing sorting method of bubblesort.
public static int[] bubble(String[] str_arr) {
for (int i = 0, temp; i < str_arr.length-1; i++) {
for(int j = 0; j < str_arr.length-1; j++) {
if (str_arr[j] < str_arr[j+1]) {
temp = str_arr[j];
str_arr[j] = str_arr[j+1];
str_arr[j+1] = temp;
}
}
}
return str_arr;
}
As i mentions theres couple of ways of comparing strings:
Length - length of a string
Lexicographically - explanation here
If we want to use one of the two method mentioned above, we should change the line:
if (str_arr[j] < str_arr[j+1])
to
if (str_arr[j].length < str_arr[j+1].length)
Or for the lexicographically order we will use:
if (str_arr[j].compareTo(str_arr[j+1].length) < 0)
compareTo is a java String method that checking lexicog.. order.
it returnes:
0 - strings are identical.
positive number - first string is bigger then second string.
negative number - first string is smaller then second string.
String implements interface Comparable (so overrides compareTo() method), thus you can compare two strings (>,<,>=,<=). That's why you don't have to compare every char element by element. Not worth trying even.
The solution: put Strings into array:
String[] stringArray = new String[]{"element1","element2"};
and then use default bubble-sort algorithm:
for (int x = 1; x < stringArray.length; x++) {
for (int y = 0; y < stringArray.length - x; y++) {
if (stringArray[y].compareTo(stringArray[y + 1]) > 0) {
temp = stringArray[y];
stringArray[y] = stringArray[y + 1];
stringArray[y + 1] = temp;
}
}
}
and you should receive sorted array.

Categories

Resources