compare list and array - java

I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,

Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.

You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)

How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}

Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}

Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose

Related

Get largest Group of anagrams in an array

For an assignment I have been asked to find the largest group of anagrams in a list. I believe I would have to have an accumulation loop inside of another loop that keeps track of the largest number of items. The problem is that I don't know how to count how many of each anagram I have. I have been able to sort the array into groups based on their anagrams. So from the index 1-3 is one anagram, 4-10 is another, etc. How do I search through and count how many of each anagram I have? Then compare each one to the previous count.
Sample of the code:
public static String[] getLargestAnagramGroup(String[] inputArray) {
ArrayList<String> largestGroupArrayList = new ArrayList<String>();
if (inputArray.length == 0 || inputArray == null) {
return new String[0];
}
insertionSort(inputArray, new AnagramComparator());
String[] largestGroupArray = new String[largestGroupArrayList.size()];
largestGroupArrayList.toArray(inputArray);
System.out.println(largestGroupArray);
return largestGroupArray;
}
UPDATE: This is how we solved it. Is there a more efficient way?
public static String[] getLargestAnagramGroup(String[] inputArray) {
int numberOfAnagrams = 0;
int temporary = 1;
int position = -1;
int index = 0;
if (inputArray == null) {
return new String[0];
}
insertionSort(inputArray, new AnagramComparator());
for (index = 0; index < inputArray.length - 1; index++) {
if (areAnagrams(inputArray[index], inputArray[index + 1])) {
temporary++;
} else {
if (temporary > numberOfAnagrams) {
numberOfAnagrams = temporary;
position = index;
temporary = 1;
} else if (temporary < numberOfAnagrams) {
temporary = 1;
}
}
}
if (temporary > numberOfAnagrams) {
position = index;
numberOfAnagrams = temporary;
}
String[] largestArray = new String[numberOfAnagrams];
for (int startIndex = position - numberOfAnagrams + 1, i = 0; startIndex <= position; startIndex++, i++) {
largestArray[i] = inputArray[startIndex];
}
return largestArray;
}
Here is a piece of code to help you out.
public class AnagramTest {
public static void main(String[] args) {
String[] input = {"test", "ttes", "abcd", "dcba", "dbac"};
for (String string : getLargestAnagramGroup(input)) {
System.out.println(string);
}
}
/**
* Gives an array of Strings which are anagrams and has the highest occurrence.
*
* #param inputArray
* #return
*/
public static String[] getLargestAnagramGroup(String[] inputArray) {
// Creating a linked hash map to maintain the order
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
for (String string : inputArray) {
char[] charArray = string.toCharArray();
Arrays.sort(charArray);
String sortedStr = new String(charArray);
List<String> anagrams = map.get(sortedStr);
if (anagrams == null) {
anagrams = new ArrayList<String>();
}
anagrams.add(string);
map.put(sortedStr, anagrams);
}
Set<Entry<String, List<String>>> entrySet = map.entrySet();
List<String> l = new ArrayList<String>();
int highestAnagrams = -1;
for (Entry<String, List<String>> entry : entrySet) {
List<String> value = entry.getValue();
if (value.size() > highestAnagrams) {
highestAnagrams = value.size();
l = value;
}
}
return l.toArray(new String[l.size()]);
}
}
The idea is to first find the anangrams. I am doing that using a sorting the string's character array and using the LinkedhashMap.
Then I am storing the original string in the list which can be used to print or reuse as a result.
You have to keep counting the number of times the an anagram occurs and that value can be used solve your problem
This is my solution in C#.
public static string[] LargestAnagramsSet(string[] words)
{
var maxSize = 0;
var maxKey = string.Empty;
Dictionary<string, List<string>> set = new Dictionary<string, List<string>>();
for (int i = 0; i < words.Length; i++)
{
char[] temp = words[i].ToCharArray();
Array.Sort(temp);
var key = new string(temp);
if (set.ContainsKey(key))
{
set[key].Add(words[i]);
}
else
{
var anagrams = new List<string>
{
words[i]
};
set.Add(key, anagrams);
}
if (set[key].Count() > maxSize)
{
maxSize = set[key].Count();
maxKey = key;
}
}
return string.IsNullOrEmpty(maxKey) ? words : set[maxKey].ToArray();
}

Remove null from unused space of StringArray when converting to a string in Java

I was working on a Java coding problem and encountered the following issue.
Input: A String -> "Code"
Output Expected: A string -> CCoCodCode
My Code snippet: (Note: In comments I have written what I expect upon passing the string)
public String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
int size = 0;
for (int i = n; i >= 1; i--) {
size = size + n; // 4+3+2+1=10
}
String[] result = new String[size];
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
Output I am getting:
CCoCodCodenullnullnullnullnullnullnullnullnullnullnullnull
Why is null getting stored although I have reduced the size and how can I remove it?
NOTE: I need to solve this using arrays. I know it is much easier using List.
If you want to keep the current structure of your code, get rid of the first for loop.
And create String[] array = new String[n]
public static String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
String[] result = new String[n]; //you want your String array to contain 4 strings
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
public class Answer {
public static String answer(String input){
StringBuilder sb = new StringBuilder(((input.length() + 1) * input.length()) / 2);
for (int i = 1; i <= input.length(); i++) {
sb.append(input.substring(0, i));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(answer("Code"));
}
}
Below statements are not required:
int size = 0;
for (int i = n; i >= 1; i--) {
size = size + n; // 4+3+2+1=10
}
You just need to change the array size from
String[] result = new String[size];
to
String[] result = new String[n];
for your program to give the expected output.
If I understand ur problem correctly to print the pattern then u can use below code,
public String printPattern(String input){
//Holds the iteration value by index
int previous=0;
//It holds the result characters
String result=null;
StringBuilder strBuilder=new StringBuilder();
//first loop to iterate only till input string length
for(int i=0;i<input.length();i++){
//checking iteration lenght with input string length
if(previous<input.length()){
//incrementing iteration for reading characters from input string
previous++;
//main loop for previous iteration value check and iterate
for(int j=0;j<previous;j++){
//converting string to Character array
char a []=input.toCharArray();
//using string builder to build the string from characters
strBuilder.append((a[j]));
//setting the value to stringbuilder by converting it in string
result=strBuilder.toString();
}
}
}
return result;
}
Size should be the length of string. Code's length is 4. Code will produce {C, Co, Cod, Code}.
public String stringSplosion(String str) { // string Say 'Code'
String join = "", values = "";
String gotIt = "";
int n = str.length(); // 4
String[] result = new String[n];
for (int i = 0; i < str.length(); i++) {
values = str.substring(i, i + 1);
join = join + values;
result[i] = join;
}
System.out.println(Arrays.toString(result));
for (String s : result) {
gotIt = gotIt + s;
}
return gotIt; // Expected output: CCoCodCode
}
String input = "Code";
String output[] = IntStream.range(0, input.length()+1)
.mapToObj(i -> input.substring(0, i))
.toArray(String[]::new);

I need to randomly remove half of the words in a string in java

Ok so I'm working on this code to blend humanities and STEM. I know very basic java code and so I'm currently trying to stick to String methods. I know using arrays may be easier but I'm not well learned in how to use them. So so far I've made code that counts the words in the string in order to determine how many words to remove (half of them). Next I need to figure out a way to randomly remove half of the words and return a new string, possibly with spaces replacing the removed letters.
Here is my code so far:
public class wordcount
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
System.out.println("Word count is = " + wordCount);
int wordCount2 = wordCount/2;
}
}
I copied the array to an arrayList to then iterate through the list and delete random elements. I hope this is the type of answer you are looking for.
public static void main(String[] args) {
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(wordArray));
int wordCount = wordList.size();
int halfWordCount = wordCount/2;
int tracker = 0; //counter for iterations in while loop
Random random = new Random();
while(tracker < halfWordCount){
int randomIndex = random.nextInt(wordList.size());
wordList.remove(randomIndex);
tracker++;
}
System.out.println(wordList.toString());
}
import java.util.Arrays;
import java.util.* ;
public class wordcount
{
public ArrayList<Integer> test(Integer[] array)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public ArrayList<String> testS(String[] array)
{
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public static void main (String[] args)
{
System.out.println("Removing random words in a Poem Program");
String str1 = "Sample Poem by Noah Eli Gordon: Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
//System.out.println("Word count is = " + wordCount);
//System.out.println(wordArray);
//String[] ret = wordArray;
//for(String str : ret)
// System.out.print(str);
int wordCount2 = wordCount/2;
Integer[] myIntArray = new Integer[wordCount];
//for(int i = 0; i<wordCount;i++)
// myIntArray[i] = i;
//for(int str : myIntArray)
//System.out.print(str);
wordcount w = new wordcount();
String[] wordArray2 = new String[wordCount2];
for(int i = 0; i <= wordCount2; i++)
{
int rand = (int)(Math.random()*(myIntArray.length-1));
ArrayList<Integer> list = w.test(myIntArray);
list.remove(rand);
myIntArray = list.toArray(myIntArray);
ArrayList<String> listS = w.testS(wordArray);
listS.remove(rand);
wordArray2 = listS.toArray(wordArray);
}
List<String> list = new ArrayList<String>();
for(String s : wordArray2)
{
if(s != null && s.length() > 0)
{
list.add(s);
}
}
wordArray2 = list.toArray(new String[list.size()]);
//for(int str : myIntArray)
//System.out.println(str);
System.out.println();
String[] ret2 = wordArray2;
for(String str : ret2)
System.out.print(str + " ");
}
}

Removing duplicates from an Array that contains multiple String elements

I want to remove duplicate String values inside my String[], but I am not sure quite how to do that.
Heres an example:
public static void main(String[] args){
String[] listofWords = new String [5];
listofWords[0] = "BMW";
listofWords[1] = "Audi";
listofWords[2] = "Mercedes";
listofWords[3] = "Audi";
listofWords[4] = "BMW";
for(int i = 0; i<listofWords.length-1; i++){
system.out.println(listofWords[i]);
}
}
How would I got about deleting the duplicates in this array and only have one of each make?
You can convert your String[] to Set:
String [] listofWords = new String [5];
listofWords [0] = "BMW";
listofWords [1] = "Audi";
listofWords [2] = "Mercedes";
listofWords [3] = "Audi";
listofWords [4] = "BMW";
Set<String> set = new HashSet<String>(Arrays.asList(listofWords));
System.out.println(set); //prints [Audi, Mercedes, BMW]
You can convert the Set back to String[] like this:
listofWords = set.toArray(new String[set.size()]);
I would recommend this solution using Java 8 streams
String[] result = Arrays.stream(listofWords).distinct().toArray(s -> new String[s]);
This also addresses the memory concerns you have expressed in the comments. It will just create an array with enough size to store distinct values and store the result there.
As a side note you could have initialized listofWords more easily like this
String[] listofWords = {"BMW", "Audi", "Mercedes", "Audi", "BMW"};
If memory is not a concern, convert to a set and back to array, like:
Set<String> mySet = new HashSet<String>(Arrays.asList(listofWords));
listofWords = mySet.toArray(new String[mySet.size()]);
If you have memory limits then you should sort the array:
Arrays.sort(listofWords);
Then remove the duplicates, like this:
public static int removeDuplicates(String[] A) {
int length=A.length;
if(length==0 || length==1) return length;
int i=1;
for(int j=1; j<length; j++){
if(!A[j].equals(A[j-1])){
A[i]=A[j];
i++;
}
}
if(i<length) A[i]=null;
return i;
}
This method will remove the duplicates and return the new array size.
Eg.
public static void main(String[] args) {
String[] listofWords = new String [5];
listofWords[0] = "BMW";
listofWords[1] = "Audi";
listofWords[2] = "Mercedes";
listofWords[3] = "Audi";
listofWords[4] = "BMW";
Arrays.sort(listofWords);
int n=removeDuplicates(listofWords);
for(int i = 0; i<n; i++){
System.out.println(listofWords[i]);
}
}
//JAVA-8 - Remove Duplicates
List li1 = new ArrayList<>(Arrays.asList(10, 22, 10, 20, 11, 22));
System.out.println("Duplicate elements: " + li1);
// Create new list from elements of original list
List li2 = (List) li1.stream().distinct().collect(Collectors.toList());
// ArrayList with duplicates removed
System.out.println("Non-duplicate elements: " + li2);
It is straightforward to do in-place if you don't need to preserve the order of appearance in the array: sort the array first and use two pointers to iterate through the array:
Arrays.sort(listofWords);
int i = 0, j = 0;
while (j < listofWords.length) {
// Copy the element from the j-th position to the i-th position.
listofWords[i] = listofWords[j];
// Increment j while the word at position j equals the word at position i.
while (j < listofWords.length && listofWords[j].equals(listofWords[i])) {
++j;
}
// Increment i, to be the next unique element index.
++i;
}
// i currently points to the element after the last non-duplicate element, so
// ideally we would throw away elements [i..listofWords.length)
// However, you can't resize an array in Java.
// This loop just nulls out the remaining elements, since their contents are all
// already in the array.
while (i < listofWords.length) {
listofWords[i++] = null;
}
You can try the below solution :
public static void main(String[] args) {
String strArray[] = new String[]{"bmw","audi","bmw","honda","Yamaha","Yamaha","maruti","hyundai","hyundai"};
HashSet setOfStrings= new HashSet<String>();
for(int i=0;i<strArray.length;i++){
boolean result=setOfStrings.add(strArray[i]);
if(!result){
System.out.println("duplicate elements include...."+strArray[i]);
}
}
Object[] newString= new Object[strArray.length];
newString=setOfStrings.toArray();
System.out.println("Array without Duplicates......."+Arrays.toString(newString));
}
import java.util.Arrays;
/**
* #author Kishore Diyyana
* Simple Bruteforce approach
*/
public class RemoveDupilcates {
public static void main(String[] args) {
RemoveDupilcates removeDups = new RemoveDupilcates();
removeDups.removeDups();
}
public void removeDups() {
int[] numbers = new int[] {10, 22, 10, 20, 11, 22};
int[] temp = new int [numbers.length];
int count = -1;
for (int i=0; i<numbers.length;i++) {
boolean hasFound = false;
for (int j = i+1; j< numbers.length; j++) {
if (numbers[i] == numbers[j]) {
hasFound = true;
break;
}
}
if (!hasFound) {
count++;
System.out.println(numbers[i]);
temp[count] = numbers[i];
}
}
int[] outpout = null;
if (count < numbers.length) {
outpout = new int [count];
System.arraycopy(temp, 0, outpout, 0, count);
}
System.out.println(Arrays.toString(outpout));
}
}

Generating String Tokens in Java

I want to generate possible tokens using forward traversal in Java. For example if I have a string "This is my car". I need to generate tokens
"This is my car"
"This is my"
"This is"
"This"
"is my car"
"is my"
"is"
"my car"
"my"
"car"
What is the best way to do this? Any examples? Thanks.
Here is another solution with split and nested loops:
public static void main(String[] args) {
String original = "this is my car";
String[] singleWords = original.split(" "); // split the String to get the single words
ArrayList<String> results = new ArrayList<String>(); // a container for all the possible sentences
for (int startWord = 0; startWord < singleWords.length; startWord++) { // starWords start with 0 and increment just until they reach the last word
for (int lastWord = singleWords.length; lastWord > startWord; lastWord--) { // last words start at the end and decrement just until they reached the first word
String next = "";
for (int i = startWord; i != lastWord; i++) { // put all words in one String (starting with the startWord and ending with the lastWord)
next += singleWords[i] + " ";
}
results.add(next); // add the next result to your result list
}
}
// this is just to check the results. All your sentences are now stored in the ArrayList results
for (String string : results) {
System.out.println("" + string);
}
}
and this was my result when I tested the method:
this is my car
this is my
this is
this
is my car
is my
is
my car
my
car
Use Guava:
String yourOriginalString = "This is my car";
final Set<String> originalWords =
Sets.newLinkedHashSet(
Splitter.on(CharMatcher.WHITESPACE).trimResults().split(yourOriginalString));
final Set<Set<String>> variations = Sets.powerSet(originalWords);
for (Set<String> variation : variations) {
System.out.println(Joiner.on(' ').join(variation));
}
Output:
This
is
This is
my
This my
is my
This is my
car
This car
is car
This is car
my car
This my car
is my car
This is my car
Here is a possible way:
//Just a method that seperates your String into an array of words based on the spaces
//I'll leave that for you to figure out how to make
String[] array = getSeperatedWords(<yourword>);
List<StringBuffer> bufferArray = new ArrayList<StringBuffer>();
for(int i = 0; i < array.length; i++){
StringBuffer nowWord = array[i];
for(int j = i; j < array.length; j++{
nowWord.append(array[j]);
}
bufferArray.add(nowWord);
}
for(int i = 0; i < bufferArray.length; i++){
System.out.print(bufferArray.get(i));
}
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String var = "This is my car";
permute(var);
}
public static void permute(String var) {
if(var.isEmpty())
return;
String[] arr = var.split(" ");
while(arr.length > 0) {
for(String str : arr) {
System.out.print(str + " ");
}
arr = (String[]) Arrays.copyOfRange(arr, 0, arr.length - 1);
System.out.println();
}
String[] original = var.split(" ");
permute(implodeArray((String[]) Arrays.copyOfRange(original, 1, original.length), " "));
}
public static String implodeArray(String[] inputArray, String glueString) {
String output = "";
if (inputArray.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append(inputArray[0]);
for (int i=1; i<inputArray.length; i++) {
sb.append(glueString);
sb.append(inputArray[i]);
}
output = sb.toString();
}
return output;
}
}
Read this book, you will be a master on recursion: http://mitpress.mit.edu/sicp/

Categories

Resources