Related
I want to built in ten arrays of size n and place in the first stings of length one, in the second strings of length two and so forth where the tenth array has strings of length ten.
Array String = { a, b, the , c , no, yes, and, or, ...}
Array length_string = [ 1 , 1, 3, 1 , 2, 3, 3 , 2 , ....}
I don't understand how to do this, place string with same length into block:
[a,b,c] //every string length =1
[no,or] // every string length =2
[the,yes,and] // every string length =3
and so on
Edit:
I found hash Map work with my code
`final Map<Integer, List> lengthToWords = new TreeMap<>(
Arrays.stream(words).collect(Collectors.groupingBy(String::length)));
But how can control block size
I meaning want each block = 256
1 [ a , b ,c ,...] number element =256 , not more that
2 [ aa, bb, cc ,..] number element =256
and so on until ten block
I have ten block by using loop , Now i need limit number element inside block
Hi if your solution doesn't need to be efficient or your array size is limit you can do it with nested loops.
for(int i =1;i<=n;i++){
for(int j = 0;j<stringArray.length;j++){
if(i == stringArray[j].length){
resultArray[i-1] = stringArray[j];
break;
}
else
continue;
}
}
Be careful to check arrayIndexOutOfBound exception
String[] arr= { "a", "b", "the" , "c" , "no", "yes", "and", "or"};
String length1="[";
String length2="[";
String length3 ="[";
for (int i = 0; i < arr.length; i++)
{
switch(arr[i].length())
{
case 1:
length1=length1+ arr[i]+",";
break;
case 2:
length2=length2+ arr[i]+",";
break;
case 3:
length3=length3+ arr[i]+",";
break;
}
}
if (length1.endsWith(",")) {
length1 = length1.substring(0, length1.length()-1);
}
if (length2.endsWith(",")) {
length2 = length2.substring(0, length2.length()-1);
}
if (length3.endsWith(",")) {
length3 = length3.substring(0, length3.length()-1);
}
length1=length1+"]";
length2=length2+"]";
length3=length3+"]";
System.out.println(length1);
System.out.println(length2);
System.out.println(length3);
output :
[a,b,c]
[no,or]
[the,yes,and]
Below is the complete Java code with example input. The createBlockList does the following: 1) Create a list of lists to store the result. 2)Iterate through the string array and place the string in the right lists.
import java.util.*;
public class MyClass {
public static void createBlockList(String[] strArr, int[] strLenArr) {
List<List<String>>resList = new ArrayList<>();
for(int i=0; i<3; i++) {
resList.add(new ArrayList());
}
for(int i=0; i<strArr.length; i++) {
int strLen = strLenArr[i];
resList.get(strLen-1).add(strArr[i]);
}
}
public static void main(String []args){
String str[] = {"a","b","in","on","the","and"};
int len[] = {1,1,2,2,3,3};
createBlockList(str, len);
}
}
The problem is
how to get the maximum repeated String in an array using only operations on the arrays in java?
so i got into this question in a test and couldn't figure it out.
lets suppose we have an array of string.
str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }
in str1 abbey was maximum repeated, so abbey should be returned and
in str2 abbey and caley both have same number of repetitions and hence we take maximum alphabet as the winner and is returned(caley here).
c > a
so i tried till
import java.util.*;
public class test {
static String highestRepeated(String[] str) {
int n = str.length, num = 0;
String temp;
String str2[] = new String[n / 2];
for (int k = 0;k < n; k++) { // outer comparision
for (int l = k + 1; l < n; l++) { // inner comparision
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
}
// I'm stuck here
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter how many votes");
int n = sc.nextInt();
String[] str = new String[n];
for (int i = 0; i < n; i++) {
Str[i] = sc.nextLine();
}
String res = highestRepeated(str);
System.out.println(res + " is the winner");
}
}
so, how should i take the count of occurrence of each string with and attach it with the string itself.
All this, without using a map and any hashing but just by using arrays?
Here is a (unpolished) solution:
static String highestRepeated(String[] str) {
String[] sorted = Arrays.copyOf(str, str.length);
Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
String currentString = sorted[0];
String bestString = sorted[0];
int maxCount = 1;
int currentCount = 1;
for (int i = 1 ; i < sorted.length ; i++) {
if (currentString.equals(sorted[i])) {
currentCount++;
} else {
if (maxCount < currentCount) {
maxCount = currentCount;
bestString = currentString;
}
currentString = sorted[i];
currentCount = 1;
}
}
if (currentCount > maxCount) {
return currentString;
}
return bestString;
}
Explanation:
Sort the array from highest to lowest lexicographically. That's what Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder()); does. we sort in this order because you want the largest string if there are multiple strings with the same number of repeats.
Now we can just count the strings by looping through the array. We don't need a hash map or anything because we know that there will be no more of a string in the rest of the array when we encounter a different string.
currentString is the string that we are currently counting the number of repeats of, using currentCount. maxCount is the number of occurrence of the most repeated string - bestString - that we have currently counted.
The if statement is pretty self-explanatory: if it is the same string, count it, otherwise see if the previous string we counted (currentCount) appears more times than the current max.
At the end, I check if the last string being counted is more than max. If the last string in the array happens to be the most repeated one, bestString won't be assigned to it because bestString is only assigned when a different string is encountered.
Note that this algorithm does not handle edge cases like empty arrays or only one element arrays. I'm sure you will figure that out yourself.
another version
static String lastMostFrequent(String ... strs) {
if (strs.length == 0) return null;
Arrays.sort(strs);
String str = strs[0];
for (int longest=0, l=1, i=1; i<strs.length; i++) {
if (!strs[i-1].equals(strs[i])) { l=1; continue; }
if (++l < longest) continue;
longest = l;
str = strs[i];
}
return str;
}
change in
if (++l <= longest) continue;
for firstMostFrequent
you can't use == to check if two strings are the same.
try using this instead:
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
I have two String Lists just like below:
List1 (Generated by sql resultset)
10001
10100
10001
List2 (Generated by sql resultset)
10000
10000
10000
Button Action;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
createList1();
createList2();
difference();
} catch (Exception ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
difference void;
public void difference (){
int minLen = Math.min(List1.get(0).length(), List2.get(0).length());
for (int i = -1 ; i != minLen ; i++) {
char chA = List1.get(0).charAt(i);
char chB = List2.get(0).charAt(i);
if (chA != chB) {
System.out.println(chA);
}
}
}
I want to find which index numbers are different in List1 for index 0.
Thanks in advance.
Make a loop that iterates the index i from zero the length of the shorter of the two strings, and compare characters one by one, using the == operator:
int minLen = Math.min(a.length(), b.length());
for (int i = 0 ; i != minLen ; i++) {
char chA = a.charAt(i);
char chB = b.charAt(i);
if (chA != chB) {
...
}
}
Before starting the comparison you need to check that a and b are not null. Otherwise, getting the length is going to trigger a null reference exception.
Try this:
public List<Integer> findDiffIndexes(String s1, String s2 ) {
List<Integer> indexes = new ArrayList<Integer>();
for( int i = 0; i < s1.length() && i < s2.length(); i++ ) {
if( s1.charAt(i) != s2.charAt(i) ) {
indexes.add( i );
}
}
return indexes;
}
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#difference%28java.lang.String,%20java.lang.String%29
public static String difference(String str1,
String str2)
Compares two Strings, and returns the portion where they differ. (More precisely, return the remainder of the second String, starting
from where it's different from the first.)
For example, difference("i am a machine", "i am a robot") -> "robot".
StringUtils.difference(null, null) = null
StringUtils.difference("", "") = ""
StringUtils.difference("", "abc") = "abc"
StringUtils.difference("abc", "") = ""
StringUtils.difference("abc", "abc") = ""
StringUtils.difference("ab", "abxyz") = "xyz"
StringUtils.difference("abcde", "abxyz") = "xyz"
StringUtils.difference("abcde", "xyz") = "xyz"
Parameters:
str1 - the first String, may be null
str2 - the second String, may be null
Returns:
the portion of str2 where it differs from str1; returns the empty String if they are equal
Since:
2.0
Do loop on List 1 and List2, and compare index value like,
I assume you that both list has same size so,
for(int i=0;i<list1.size();i++)
{
if(!list1.get(i).equals(list2.get(i))
{
System.out.println("Not equal value of Index="+i);
}
}
Assuming the two Strings will always be the same length...
String first = "10000";
String second = "10101";
ArrayList differentIndexes = new ArrayList();
for(int i=0; i<first.length(); i++){
if(first.charAt(i)!=second.charAt(i)){
differentIndexes.add(i);
}
}
I am working on a solution to the TSP problem. I have generated all the permutations of the String "123456", however, I need to convert this into an ArrayList of Integer like this [1,2,3,4,5,6]...[6,5,4,3,2,1]. I then store this into an ArrayList of ArrayLists. Once there I will be able to compare all of the cities that need to be traveled to.
When I run my code, I have a method to generate the permutation, then a method to change that permutation into an ArrayList of Integer. When I convert them, I get the exception java.lang.NumberFormatException: For input string: "". I don't know of any other way to get the String to Integer
Here is my code.
public static String permute(String begin, String string){
if(string.length() == 0){
stringToIntArray(begin+string);
return begin + string + " ";
}
else{
String result = "";
for(int i = 0; i < string.length(); ++i){
String newString = string.substring(0, i) + string.substring(i+1, string.length());;
result += permute(begin + string.charAt(i), newString);
}
stringToIntArray(result);
return result;
}
}
public static void stringToIntArray(String s){
ArrayList<Integer> perm = new ArrayList<Integer>();
String [] change = s.split("");
for(int i = 0; i < 7; ++i){
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}
}
public static void main(String[] args) {
permute("", "123456");
}
These lines
String [] change = s.split("");
for(int i = 0; i < 7; ++i){
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}
Given a String like "12345", when you split it on nothing, it will separate every character. Giving you an array with ["","1","2","3","4","5"]. Since the empty String "" is not a Number, you will get the NumberFormatException. You could change your index i to start at 1 so as to ignore that first empty String.
The split method, when splitting on "", produces an empty string as the first element of the array, so you need to start iterating from i = 1.
Also, it would be safer to stop the iteration at change.length to make sure you process all characters when there are more than 6, and don't go out of bounds if there are fewer.
String [] change = s.split("");
for(int i = 1; i < change.length; ++i){ // ignore first element
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}
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]) {
...
}
}