insert a word into an alphabetical array and shift elements over - java

I have a really simple task but I'm a beginner and have no idea how do do it. I have to make a method that will take two parameters: an array of Strings, and a word. We are assuming that the array contains a group of words that are already alphabetized in order. I need to take the word and insert it into the array in the correct alphabetical position, and shift all the previous array elements over accordingly. Here is my code so far but I think it's completely wrong...
public static void insertWordIntoArray(String[] arr, String word){
int i = 0;
while(arr[i].compareTo(word) > 0){i++;}
String temp = ""; String tempV = "";
temp = arr[i];
arr[i] = word;
for (String ind : arr){
i++;
if(i<9)tempV = arr[i+1];
if(i<9)arr[i+1] = temp;
temp = tempV;
}
}

what do you mean by 9? is it the size of the arr? if it is the size, then this will only work if the elements in the array is less then the array size... I think you will find yourself with array out of bound error if elements is same as array size...
array is dynamic...
i think best not to use number such as 9, because this will make the method is not portable...
Can I increase the size of a statically allocated array?
http://en.wikipedia.org/wiki/Dynamic_array

yeah, that's an insertion sort.
You may be better off using a
LinkedList<String>
, you can insert into it without the need to move the elements.

Related

Arraylist - Using switch statement to add string

I am new to programming and my professor has given an assignment that requires us to:
"declare on arraylist with the size of 5. Use switch statement to add string values to your arraylist. Retrieve the contents of your arraylist. Check the size of each element. If the element length is less than 8 rerun the program, otherwise count the consonants of each element."
I've done some research to understand some factors of an ArrayList;
to start off, I did this:
import java.util.ArrayList;
public class izeOfArrayList {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
int totalElements = arrayList.size();
System.out.println("ArrayList contains...");
for(int index=0; index < totalElements; index++)
System.out.println(arrayList.get(index));
}
}
This code just gets the number of elements currently stored in my ArrayList, and prints out each element.
I have three questions:
How can I add String values using switch statement?
How can I retrieve the contents of my ArrayList?
How can I check the size of each element in my ArrayList?
"declare on arraylist with the size of 5. Use switch statement to add string values to your arraylist. Retrieve the contents of your arraylist. Check the size of each element. If the element length is less than 8 rerun the program, otherwise count the consonants of each element."
Let's decode line by line:
declare on arraylist with the size of 5.
ArrayList<String> myList = new ArrayList<>(5);
Our ArrayList needs to be defined as a list of Strings, so we put those in the angle brackets. The constructor takes a starting size, which is specified as 5.
Use switch statement to add string values to your arraylist.
Completely unintelligible. switch statements are used in flow of control; we can decide to add string values based on some condition, but we cannot generate input with switch statements, and no conditions are specified. This following code is (seemingly) valid for this instruction:
String values = "values";
switch (values) {
case "values":
default:
myList.add(values);
}
Retrieve the contents of your arraylist.
This you have already (mostly) written up:
int totalElements = myList.size();
for(int index = 0; index < totalElements; index++)
String tempElem = myList.get(index); //get access to the individual elem
//here we're going to do something with the current string (probably)
}
Check the size of each element.
I'm assuming that by the 'size of each element', your professor is looking for the length of each String.
int tempElemLength = tempElem.length();
String objects have a length method, it returns an int.
If the element length is less than 8 rerun the program, otherwise count the consonants of each element.
This, while at first glace seems reasonable, is again unintelligible. Here's a possible interpretation of this line:
if (tempElemLength < 8) {
main(null);
} else {
int tempElemNumConsonants = countConsonants(tempElem);
//consonants are counted and now what?
}
Here is a complete response to your assignment as it is currently defined:
import java.util.ArrayList;
public class SizeOfArrayList {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<>(5);
String values = "values";
switch (values) {
case "values":
default:
myList.add(values);
}
int totalElements = myList.size();
for (int index = 0; index < totalElements; index++)
String tempElem = myList.get(index);
int tempElemLength = tempElem.length();
if (tempElemLength < 8) {
main(null);
} else {
int tempElemNumConsonants = countConsonants(tempElem);
//consonants are counted and now what?
//guess print them out?
System.out.println('Item ' + index + ': ' + tempElem + ' -> number of consonants: ' + tempElemNumConsonants);
}
}
}
}
This is a solution to your problem as it has been provided; I will bet money that this is not the solution to your homework problem.
In another school of thought, if the focus of the assignment is basic use and understanding of ArrayLists and I was your professor, the assignment that I would have intended to give my students would be as follows:
Declare and ArrayList with the size of 5. Prompt the user for values until they enter 'quit'; use a switch statement to add all String values into the ArrayList that aren't just a number from [0-9]. Loop over each element in the ArrayList; if the length of any String element is less than 8, alert the user then restart the program. If all of the lengths are valid, sum up the consonants of each element. Print out each word and the consonant count, along with a final tally of the number of words along with the total number of consonants.
While I do know that this does not help you with the initial question, I hope it might be able to help you understand what your professor is trying to ask of you.

What is the time complexity and space complexity of this algorithm to find Anagrams?

I am working on an interview question from Amazon Software
The question is "Design an algorithm to take a list of strings as well as a single input string, and return the indices of the list which are anagrams of the input string, disregarding special characters."
I was able to design the algorithm fine, what I did in psuedo code was
1.Create an array character count of the single input string
2.For each string the list, construct the an array character count
3.Compare the character count of each string in list to single output string
4.If same, add it to a list that holds all the indexes of anagrams.
5.Return that list of indices.
Here is my implementation in Java(it works, tested it)
public static List<Integer> indicesOfAnag(List<String> li, String comp){
List<Integer> allAnas = new ArrayList<Integer>();
int[] charCounts = generateCharCounts(comp);
int listLength = li.size();
for(int c=0;c<listLength; c++ ){
int[] charCountComp = generateCharCounts(li.get(c));
if(isEqualCounts(charCounts, charCountComp))
allAnas.add(c);
}
return allAnas;
}
private static boolean isEqualCounts(int[] counts1, int[] counts2){
for(int c=0;c<counts1.length;c++) {
if(counts1[c]!=counts2[c])
return false;
}
return true;
}
private static int[] generateCharCounts(String comp) {
int[] charCounts = new int[26];
int length = comp.length();
for(int c=0;c<length;c++) {
charCounts[Character.toLowerCase(comp.charAt(c)) - 'a'] ++;
}
return charCounts;
}
What I am having trouble with is analyzing the space and time complexity of this algorithm because of both of the sizes of the list and of each string. Would the time complexity algorithm just be O(N) where N is the size of the list(processing each String once) or do I have to take into account the composite complexity of the length of each String, in that case, O(N * n) where n is the length of the string? I did N * n because you ware processing n N times. And would space complexity be O(N) because I am creating N copies of the 26 length array?
And would space complexity be O(N) because I am creating N copies of the 26 length array?
Yes.
Would the time complexity algorithm just be O(N) where N is the size of the list
No. Time depends on size of input strings, it'll be O(comp.length+sum_of_li_lengths).

How to delete an entry from an array in Java so that the other entries remain in order

Forgive the clunky title
I want to write a method that removes a specific entry from an array, but doesn't leave a null gap in the array. For example if a String array contained
|aa,bb,cc,dd,ee|
the user would be prompted to enter which number they wanted removed, the method would find the index of that entry, remove that index, then move the null entry to the last slot.
So if the user entered cc, the array's contents would be
|aa,bb,dd,ee,null|
EDIT: I realized I left out some information here. the entry I'm looking to remove will be passed from another method. I will then use a for loop to find the index of the entry (If not found nothing is done). However I'm stuck on how to do the deletion.
First of all: I strongly suggest to use an ArrayList where you can easily remove and add items without having to change the rest of the collection (it also has a toArray() method).
That being said, tihs would be a sample solution to do it with just arrays:
public static void main(String[] args) {
String[] arr = new String[5];
arr[0] = "aa";
arr[1] = "bb";
arr[2] = "cc";
arr[3] = "dd";
arr[4] = "ee";
System.out.println(Arrays.toString(arr));
int deleteIndex = 2;
System.arraycopy(arr, deleteIndex + 1, arr, deleteIndex, arr.length - deleteIndex - 1);
arr[4] = null;
System.out.println(Arrays.toString(arr));
}
Output:
[aa, bb, cc, dd, ee]
[aa, bb, dd, ee, null]
The idea is to to shift the elements one place ahead starting from the index to delete + 1. Afterwards you set the latest item manually to null or it will duplicate the last entry.
I would do it like this maybe:
for (int i = index; i < array.length -1; i++) {
array[i] = array[i+1];
}
array[array.length - 1] = null;
To keep the contents in order as you remove you need to shift elements to the left of the array.
The most naive and wasteful way would be to initialize another array with 1 size less than the current.
Then copy all the elements in a loop from your array but not the one that the user wants to remove (jumping that index)
You have the gist of it in your description
the user would be prompted to enter which number they wanted removed, the method would find the index of that entry, remove that index, then move the null entry to the last slot.
with not writing the actual code, since this seems like a school assignment, I'll just add what happens to the indexes of the rest of the entries after the deleted index?
One option would be to make the array into a List, remove the entry then make it into an array again.
ArrayList<String> aList = new ArrayList<String>(Arrays.asList(yourArray));
aList.remove(yourIndex);
return aList.toArray(new String[yourArray.length]);
As a Test example
public static void main(String[] args) {
String[] yourArray = new String[]{"FF","AA","BB"};
for(String s : yourArray)
System.out.println(s);
System.out.println("");
ArrayList<String> aList = new ArrayList<String>(Arrays.asList(yourArray));
aList.remove(1);
String[] r = aList.toArray(new String[yourArray.length]);
for(String s : r)
System.out.println(s);
}
Output
FF
AA
BB
FF
BB
null

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

Array of linked lists of arrays for hash table

So I am creating a Hash Table that uses an Array of Linked Lists of Arrays. Let me take a second to explain why this is.
So I have previously implemented Hash Tables by creating an Array, and each element of the array is a Linked List. This way I could quickly look up a LL of 450,000 elements by searching for the hash value first in the array, and searching the elements of this LL. I should add that this is a project for school and I cannot just use the Hash Tables that comes with java.
Now I want to do something similar... but I massive have a LL of Arrays that I need to search. Here each element of the LL is line of a text file, which represented by a 4 element array, where each of the 4 elements is a different string that was tab delimited in the input file. I need to be able to quickly access the 2nd, 3rd, and 4th string that was located in each line, and that is now an element of this array.
So What I want is to be able to create an Array of LL of Arrays... first I will find the sum of the ascii values of the second element of an array. Then I will hash the entire array using this value into by Hash Table. Then when I later need to find this element, I will go to the corresponding element of the array, where I have a list of arrays. I will the search for the 2nd value of each array in the list. If i find the one I want, then I return that array, and use the 3rd and 4th element of this array.
As I said, I have this working fine for an Array of LL, but adding the extra dimension of Arrays inside has thrown me off completely. I think it is mostly just figuring out syntax, since I have successfully initialized a Array of LL of Arrays (public static LinkedList[] RdHashLL) so it appears that Java is okay with this in principal. However, I have no idea how to put elements into the Hash Table, and how to read them out.
Below is my code for a ARRAY OF LINKED LISTS that works FINE. I just need help getting it to work for an ARRAY OF LL OF ARRAYS!
public class TableOfHash{
public static LinkedList<String>[] HashLL;
//HASH FUNCTION - Finds sum of ascii values for string
public static int charSum(String s){
int hashVal = 0;
int size = 1019; //Prime Number around size of 8 char of 'z', (8 chars is amoung largest consistantly in dictionary)
for(int i = 0; i < s.length(); i++){
hashVal += s.charAt(i);
}
return hashVal % size;
}
//CREATE EMPTY HASH TABLE - Creates an array of LL
public static void makeHash(){
HashLL = new LinkedList[1019];
for(int i=0; i<HashLL.length; i++){
HashLL[i] = new LinkedList<String>();
}
}
//HASH VALUES INTO TABLE!
public static void dictionary2Hash(LinkedList<String> Dict){
for(String s : Dict){
HashLL[charSum(s)].add(s);
//Finds sum of char vales of dictionary element i,
//and then word at i to the HashLL at point defined
//by the char sum.
}
//Print out part of Hash Table (for testing! for SCIENCE!)
//System.out.println("HASH TABLE::");
//printHashTab();
}
//SEARCH HashTable for input word, return true if found
public boolean isWord(String s){
if(HashLL[charSum(s)].contains(s)){
wordsfound++;
return true;
}
return false;
}
}
I have made some attempts to change this, but for things like if(HashLL[charSum(s)].contains(s)) which searches the LL at the element returned by charsum(s)... I have no idea how to get it to work when it is a LL of Arrays and not of Strings. I have tired HashLL[charSum(s)].[1].contains(s)), and HashLL[charSum(s)][1].contains(s)), and various other things.
The fact that a Google search for "Array of Linked Lists of Arrays" (with quotes) turns up empty has not helped.
Last bit. I realize there might be another data structure that would do what I want, but unless you believe that a Array of LL of Arrays is a totally hopeless cause, I'd like to get it to work as is.
if you have
LinkedList<String[]>[] hashLL;
you can read a specific String like this (one of many ways)
String str = hashLL[outerArrayIndex].get(listIndex)[innerArrayIndex];
To write into the fields, this is possible (assuming everything is initialized correctly).
String[] arr = hashLL[outerArrayIndex].get(listIndex);
arr[index] = "value";

Categories