Compare 2d array to 1d in Java - java

Guys I'm a bit new in using java and i'm trying to write a program that will check the 2d array if it contains the value of 1d array.The second array is like a list of numbers and it will check the first array if they match.
array1[6]= {"a","b","c","d","e","f"}
array2[1][4]={{"a","b","c","d"}{"d","e","f","g"}}
array2[0]= rowcomplete ; // because it contain all the value a,b,c,d
array2[1]= incomplete; // because it only match d,e,f but not g
This is my code:
String array1[] = {"a","b","c","d","e","f"};
String array2[][] = {{"a","b","c","d"}, {"d","e","f","g"}};
for (int 2row = 0; 2row < array2.length; 2row++) {
for (int 2column = 0;2column< array2[2row].length;2column++) {
for(int 1row=0; 1row < array1[1row].length();1row++) {
if (array2[2row][2column].equals(array1[1row])) {
System.out.println("complete");
}
else{
}
}
}
}

An easy way to do that would be to use the Arrays class to transform your arrays into a List and the use the containsAll method, like this:
String array1 []={"a","b","c","d","e","f"};
String array2 [][] ={{"a","b","c","d"},{"d","e","f","g"}};
List<String> array1AsList = Arrays.asList(array1);
for (int i = 0; i < array2.length; i++) {
List<String> array2rowAsList = Arrays.asList(array2[i]);
if(array1AsList.containsAll(array2rowAsList)){
System.out.println("row " + i + " is complete");
}
}

Just to clarify what Banthar's comment above implies:
Java variable names can NOT start with a digit. They can only start with an _underscore, letter or a dollar sign $. After the first letter, you can use digits.

This would be easier if you use an array list for array1 because you can use the arrayList.contains() to determine if the value is in the list.
Using an array list and declaring/initializing array2 as you did before, try this:
ArrayList array1 = new ArrayList();
Collections.addAll(array1, "a", "b", "c", "d", "e", "f");
boolean matchFlag;
for(int i = 0;i< array2.length; i++){
matchFlag = true;
for(int j=0;j<array2[i].length; j++){
if(array1.contains(array2[i][j]) == false){
//found string that did not match
//
matchFlag = false;
}
}
if(matchFlag){
//complete array
}
}
Hope this helps!

You can also use Arrays.equals
String array1[] = {"a","b","c","d","e","f"};
String array2[][] = {{"a","b","c","d"}, {"d","e","f","g"}};
for (int i = 0; i < array2.length; i++) {
if(java.util.Arrays.equals(array1, array2[i]) {
...
}
}

Related

Sorting an array of strings [duplicate]

This question already has an answer here:
Remove a common word from each string value in an array
(1 answer)
Closed 6 years ago.
I have an array of Strings that contains: Extra Water, Juice, and Extra Milk, so I am wondering how would I get rid of the extras and use the only second word in the string so that the expected output is Water, Juice, and Milk.
If all you want to do is remove a specific substring then:
String[] array = {"Extra Water", "Juice", "Extra Milk"};
array = Arrays.stream(array).map(s-> s.replaceAll("Extra", "")).toArray();
This uses Java 8 streams but you could do it just as simply with iteration.
Use String.split(' ') to split the string by a space, then check the result to see if the string length == 2. If so, then take the second element of the array, otherwise the first.
for( int i = 0; i < array.length; i++ ) {
String[] parts = array[i].split(' ');
if( parts.length == 2 ) {
array[i] = parts[1];
}
}
EDIT: If you want to remove all duplicate words, you could do the following using two passes over the array:
// Pass 1 -- find all duplicate words
Set<String> wordSet = new HashSet<>();
Set<String> duplicateSet = new HashSet<>();
for (int i = 0; i < array.length; i++) {
String[] parts = array[i].split(" ");
for (String part : parts) {
if (!wordSet.contains(part)) {
// Haven't seen this word before
wordSet.add(part);
} else {
// This word is a duplicate word
if (!duplicateSet.contains(part)) {
duplicateSet.add(part);
}
}
}
}
// Pass 2 -- remove all words that are in the duplicate set
for (int i = 0; i < array.length; i++) {
String[] parts = array[i].split(" ");
String dedupedString = "";
for (String part : parts) {
if (!duplicateSet.contains(part)) {
dedupedString += part + " ";
}
}
array[i] = dedupedString;
}
Simply you need to iterate over each element of the array and replace the "Extra" in each element of the array and then trim the white spaces.
String[] array = {"Extra Water", "Juice", "Extra Milk"};
for (int i = 0; i < array.length; i++) {
array[i] = array[i].replace("Extra", "").trim();
}
for (String each : array) {
System.out.println(each);
}

Extract words from an array of Strings in java based on conditions

I am trying to do an assignment that works with Arrays and Strings. The code is almost complete, but I've run into a hitch. Every time the code runs, it replaces the value in the index of the output array instead of putting the new value in a different index. For example, if I was trying to search for the words containing a prefix "b" in the array of strings, the intended output is "bat" and "brewers" but instead, the output comes out as "brewers" and "brewers". Any suggestions? (ps. The static main method is there for testing purposes.)
--
public static void main(String[] args) {
String[] words = {"aardvark", "bat", "brewers", "cadmium", "wolf", "dastardly", "enigmatic", "frenetic",
"sycophant", "rattle", "zinc", "alloy", "tunnel", "nitrate", "sample", "yellow", "mauve", "abbey",
"thinker", "junk"};
String prefix = "b";
String[] output = new String[wordsStartingWith(words, prefix).length];
output = wordsStartingWith(words, prefix);
for (int i = 0; i < output.length; i++) {
System.out.println("Words: " + i + " " + output[i]);
}
}
public static String[] wordsStartingWith(String[] words, String prefix) {
// method that finds and returns all strings that start with the prefix
String[] returnWords;
int countWords = 0;
for (int i = 0; i < words.length; i++) {
// loop to count the number of words that actually have the prefix
if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
countWords++;
}
}
// assign length of array based on number of words containing prefix
returnWords = new String[countWords];
for (int i = 0; i < words.length; i++) {
// loop to put strings containing prefix into new array
for (int j = 0; j < returnWords.length; j++) {
if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
returnWords[j] = words[i];
}
}
}
return returnWords;
}
--
Thank You
Soul
Don't reinvent the wheel. Your code can be replaced by this single, easy to read, bug free, line:
String[] output = Arrays.stream(words)
.filter(w -> w.startsWith(prefix))
.toArray(String[]::new);
Or if you just want to print the matching words:
Arrays.stream(words)
.filter(w -> w.startsWith(prefix))
.forEach(System.out::println);
Its because of the code you have written. If you would have thought it properly you would have realized your mistake.
The culprit code
for (int j = 0; j < returnWords.length; j++) {
if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
returnWords[j] = words[i];
}
}
When you get a matching word you set whole of your output array to that word. This would mean the last word found as satisfying the condition will replace all the previous words in the array.
All elements of array returnWords gets first initialized to "bat" and then each element gets replaced by "brewers"
corrected code will be like this
int j = 0;
for (int i = 0; i < words.length; i++) {
if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
returnWords[j] = words[i];
j++;
}
}
Also you are doing multiple iterations which is not exactly needed.
For example this statement
String[] output = new String[wordsStartingWith(words, prefix).length];
output = wordsStartingWith(words, prefix);
can be rectified to a simpler statement
String[] output = wordsStartingWith(words, prefix);
The way you're doing this is looping through the same array multiple times.
You only need to check the values once:
public static void main(String[] args) {
String[] words = {"aardvark", "bat", "brewers", "cadmium", "wolf", "dastardly", "enigmatic", "frenetic",
"sycophant", "rattle", "zinc", "alloy", "tunnel", "nitrate", "sample", "yellow", "mauve", "abbey",
"thinker", "junk"};
String prefix = "b";
for (int i = 0; i < words.length; i++) {
if (words[i].toLowerCase().startsWith(prefix.toLowerCase())) {
System.out.println("Words: " + i + " " + words[i]);
}
}
}
Instead of doing two separate loops, try just having one:
String[] returnWords;
int[] foundWords = new int[words.length];
int countWords = 0;
for (int i = 0; i < words.length; i++) {
// loop to count the number of words that actually have the prefix
if (words[i].substring(0, prefix.length()).equalsIgnoreCase(prefix)) {
foundWords[index] = words[i];
countWords++;
}
}
// assign length of array based on number of words containing prefix
returnWords = new String[countWords];
for (int i = 0; i < countWords; i++) {
returnWords[i] = foundWords[i];
}
My method has another array (foundWords) for all the words that you found during the first loop which has the size of words in case every single word starts with the prefix. And index keeps track of where to place the found word in foundWords. And lastly, you just have to go through the countWords and assign each element to your returnWords.
Not only will this fix your code but it will optimize it so that it will run faster (very slightly; the bigger the word bank is, the greater fast it will search through).

How to combine arrays into one array in while loop in Java

I have a stream of strings from a csv file. These strings are converted to arrays and must be put in an Object's setter and the Object in a hashMap as a value. How do i concatenate all comming Arrays into one and only then use the Set method? Is there any better solution than concatenating the arrays before the set method?
Here is my code:
HashMap<Integer, Publication> innerMap = new HashMap<>();
try {
CsvReader csv = new CsvReader(filename);
csv.readHeaders();
while (csv.readRecord()) {
int id = Integer.parseInt(csv.get("ID"));
Publication pub = new Publication();
String names = csv.get("Names");
String[] namesArr = names.split(",");
if (!innerMap.containsKey(id)) {
innerMap.put(id, new Publication());
}
String[] merged = ????
pub.setNames(merged);
innerMap.put(au.getIdx(), pub);
}
csv.close();
} catch (IOException e) {
System.out.println("Exception : " + e);
}
Store them in a List first:
List<String[]> list = new ArrayList<>;
...
list.add(namesArr);
Then, once you've finished reading:
int size = 0;
for (String[] arr : list) {
size += arr.length;
}
List<String> all = new ArrayList<>(size);
for (String[] arr : list) {
all.addAll(Arrays.asList(arr));
}
The first loop helps to allocate the necessary memory to hold all of the data (otherwise there may be lots of reallocations and array copying in the ArrayList internally while you are adding elements to it in the second loop).
this has already been answered using Apache commons - How can I concatenate two arrays in Java?
Here's a pure java 8 way
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "e", "f", "g" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
String[] arr = Stream.concat(stream1, stream2).toArray(String[]::new);
It looks like that if the map key exists, you want to extract the values, append additional values and then put it back in.
I would use a getter, then run this concat function which returns a new array. Since an Array is capped by its size, you cant grow it unless you make a new array and copy everything over.
to concat 2 string arrays where A comes first:
String[] concat( String[] a, String[] b){
String[] out = new String[a.length + b.length]();
int i = 0;
for (int j = 0; j < a.length; j++){
out[i] = a[j]
i++;
}
for (int j = 0; j < b.length; j++){
out[i] = b[j];
i++;
}
return out;
}

Look for duplicate values in a String[] without using Sets, Lists, ArrayLists?

Lets say we have this array: String[] arr1 = {"a", "b", "c", "a"};
What I'm trying to do is remove duplicate String (In this case "a") and add its value to another String[] called duplicates. When the duplicate is added to the "duplicates" array, the amount of times it occured wrongfully in the array arr1 is concatenated next to it. (recurredValue + amount) so in this example it would be a 1. I have searched for this before and all of them included usage of Lists, ArrayLists, or Sets. Please do not use any of them.
Use below code:-
public static String[] removeDuplicates(String[] numbersWithDuplicates) {
// Sorting array to bring duplicates together
Arrays.sort(numbersWithDuplicates);
String[] result = new String[numbersWithDuplicates.length];
String[] duplicate = new String[numbersWithDuplicates.length];
String previous = numbersWithDuplicates[0];
result[0] = previous;
int counter=1;
int duplicateCounter=0;
for (int i = 1; i < numbersWithDuplicates.length; i++) {
String ch = numbersWithDuplicates[i];
if (previous != ch) {
result[counter++] = ch;
}
else
{
duplicate[duplicateCounter++]=ch;
}
previous = ch;
}
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
System.out.println("Duplicate Values are ---");
for (int i = 0; i < duplicate.length; i++) {
System.out.println(duplicate[i]);
}
return result;
}
maybe something like this you can use
public static void main(String[] args) {
String[] arr1 = {"a", "b", "c", "a", "a"};
String[] duplicates = new String[arr1.length];
boolean d = false;
int count = 0;
String dup = "";
for(int i = 0;i < arr1.length;i++){
count = 0;
dup = "";
d = false;
for(int j = 0;j < arr1.length;j++){
if(i != j){
if(arr1[i].equals(arr1[j]) && !arr1[i].equals("")){
arr1[j] = "";
d = true;
count++;
dup = arr1[i];
}
}
}
if(d){
duplicates[i] = dup + count;
d = false;}
}
for(int k = 0;k < duplicates.length;k++)
System.out.println(duplicates[k]);
}
Well, one solution is to create 2 arrays and have one hold the unique strings and the other its integer counter. As you index through your sample string array, add the unique strings and increment the incidents. This is not a very elegant or efficient solution but it should work.

Java-Array Splitting

I have array of string {"All-Inclusive,All Inclusive","Luxury,Luxury","Spa-And-Relaxation,Spa & Relaxation"}
I want to split them based on "," with two arrays, first array {"All-Inclusive","Luxury","Spa-And-Relaxation"} and a second array {"All Inclusive","Luxury","Spa & Relaxation"}.
Can you kindly suggest how can it be done?
You could iterate your array of String(s). For each element, call String.split(String) and that will produce a temporary array. Make sure you got two String(s) from the array and then assign it to your output first and second like
public static void main(String[] args) {
String[] arr = { "All-Inclusive,All Inclusive", "Luxury,Luxury",
"Spa-And-Relaxation,Spa & Relaxation" };
String[] first = new String[arr.length];
String[] second = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
String[] t = arr[i].split("\\s*,\\s*");
if (t.length == 2) {
first[i] = t[0];
second[i] = t[1];
}
}
System.out.printf("First = %s%n", Arrays.toString(first));
System.out.printf("Second = %s%n", Arrays.toString(second));
}
Output is
First = [All-Inclusive, Luxury, Spa-And-Relaxation]
Second = [All Inclusive, Luxury, Spa & Relaxation]

Categories

Resources