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);
}
}
Related
I need to execute by command line a code that will provide a multidimensional array with elements with not necessarily equal lengths.
The execution string is bellow:
start /wait java -jar testMSMWithIndex.jar Foursquare_weather_day_root-type_type 0,1,2-4
I'm considering to pass the parameter 0,1,2-4 and then convert it in a multidimensional array with elements of different lengths in this case, i.e. {{0}, {1}, {2, 4}}.
Note that {{0, null}, {1, null}, {2, 4}} does not work to my problem.
Do you guys know how to develop a method or even get directly as an array from args?
I really appreciate any help you can provide.
It's doubtful that anything already exists to do this for you, so you'll have to parse the string for yourself. Something like this would do it:
public static int[][] parseRaggedArrayFromString(String s)
throws NumberFormatException {
String[] ss = s.split(",");
int[][] result = new int[ss.length][];
for (int i = 0; i < ss.length; ++i) {
if (!ss[i].contains("-")) {
result[i] = new int[1];
result[i][0] = Integer.parseInt(ss[i]);
} else {
String[] range = ss[i].split("-", 2);
int lo = Integer.parseInt(range[0]);
int hi = Integer.parseInt(range[1]);
int size = hi - lo + 1;
result[i] = new int[size > 0 ? size : 1];
int j = 0;
do {
result[i][j] = lo;
++lo;
++j;
} while (lo <= hi);
}
}
return result;
}
It's basically a split on , and -. From there is just handling the data. Comments in the code.
/**
* #author sedj601
*/
public class Main {
public static void main(String[] args) {
String input = "0,1,2-3";
String[] firstArray = input.split(",");//Split on ,.
String[][] outputArray = new String[firstArray.length][];//The array that will be holding the output
//Used to process the firstArray
for (int i = 0; i < firstArray.length; i++) {
if (firstArray[i].length() > 1) {//If the lenght is greater than one. split on -.
String[] secondArray = firstArray[i].split("-");
//Subtract the two numbers and add one to get the lenght of the array that will hold these values
int arrayLength = Integer.parseInt(secondArray[1]) - Integer.parseInt(secondArray[0]) + 1;
String[] tempArray = new String[arrayLength];
int increment = 0;//Keeps up with the tempArray index.
//loop from the first number to the last number inclusively.
for (int t = Integer.parseInt(secondArray[0]); t <= Integer.parseInt(secondArray[1]); t++) {
tempArray[increment++] = Integer.toString(t);//Add the data to the array.
}
outputArray[i] = tempArray;//Add the array to the output array.
} else {//If the lenght is 1, creat an array and add the current data.
String[] tempArray = new String[1];
tempArray[0] = firstArray[i];
outputArray[i] = tempArray;
}
}
//Print the output.
for (String[] x : outputArray) {
for (String y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}
Output:
--- exec-maven-plugin:1.5.0:exec (default-cli) # JavaTestingGround ---
0
1
2 3
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.194 s
Finished at: 2021-01-08T00:08:15-06:00
------------------------------------------------------------------------
I really think that's possible when you create an array of type Object .(not a good idea) Since multi-D arrays can only hold arrays of same length (int[][]). Then you create and retrieve values from array by casting...
I am trying here to be creative and adopt to your requirements..
public class x {
public static void main(String[] args) {
Object[] arguments = new Object[args.length];
// Then make a loop to capture arguments in array..
// or add manually
arguments[0] = new String[]{args[0]};
arguments[1] = new String[]{args[1],args[2]};
//Then retrieve info from object later by casting
System.out.println(java.util.Arrays.toString((String[]) arguments[1]));
}
}
...
Although, please consider using a collection...
While I waited for the answer, I found a way to solve the problem.
The relevant information here is that we do not need to set the second array dimension in its instantiation.
The code is below:
// INPUT string = "2-3,1,4-5"
private static String[][] featuresConversion(String string) {
String[] firstLevel = string.split(","); // 1st lvl separator
String[][] features = new String[firstLevel.length][]; // Sets 1st lvl length only
int i = 0;
for (String element : firstLevel) {
features[i++] = element.split("-");
}
return features;
}
I want to thank you all. All suggested solutions also work fine!
Problem Description
Given an integer array containing digits from [0, 99], the task is to print all possible letter combinations that the numbers could represent. A mapping of digit to letters (just like on the telephone buttons) is being followed. Note that 0 and 1 do not map to any letters. All the mapping are like:enter link description here
Here is my design:
First,default the String array and input the elements to it;like:
Second,default the show method like:
Third,config the mapping about String array and number
Four,Use Scanner method;
the show result like
input:Array[]={99,2,3};
output:HAD HAE HAF HBD HBE HBF HCD HCE HCF EAD EAE EAF EBD EBE EBF ECD ECE
ECF LAD LAE LAF LBD LBE LBF LCD LCE LCF LAD LAE LAF LBD LBE LBF LCD
LCE LCF OAD OAE OAF OBD OBE OBF OCD OCE OCF
import java.io.*;
import java.util.*;
public class GFG
{
// Function to return a vector that contains
// all the generated letter combinations
static ArrayList<String> letterCombinationsUtil(int[] number, int n,
String[] table)
{
// To store the generated letter combinations
ArrayList<String> list = new ArrayList<>();
Queue<String> q = new LinkedList<>();
q.add("");
while(!q.isEmpty())
{
String s = q.remove();
// If complete word is generated
// push it in the list
if (s.length() == n)
list.add(s);
else
{
String val = table[number[s.length()]];
for (int i = 0; i < val.length(); i++)
{
q.add(s + val.charAt(i));
}
}
}
return list;
}
// Function that creates the mapping and
// calls letterCombinationsUtil
static void letterCombinations(int[] number, int n)
{
// table[i] stores all characters that
// corresponds to ith digit in phone
String[] table = { "", "", "abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz" };
ArrayList<String> list =
letterCombinationsUtil(number, n, table);
// Print the contents of the list
for (int i = 0; i < list.size(); i++)
{
System.out.print(list.get(i) + " ");
}
}
public static void main(String args[])
{
int[] number = { 2, 3, 7, 9};
int n = number.length;
letterCombinations(number, n);
}
}
input:
This question already has answers here:
Create ArrayList from array
(42 answers)
Closed 6 years ago.
I would like to convert an Array of Strings into an ArrayList of ArrayList, where the inner ArrayList has a dynamic number of elements. Who can help ? Thanks in advance
String[] sentences = {"hello","how are you","i am fine","and you ?","thank you"}
//Output with number of elements = 2
["hello","how are you"]
["i am fine","and you ?"]
["thank you"]
//Output with number of elements = 3
["hello","how are you","i am fine"]
["and you ?","thank you"]
public static void main(String[] args) {
String[] sentences = {"hello", "how are you", "i am fine", "and you ?", "thank you"};
System.out.println(split(2,sentences));
System.out.println(split(3,sentences));
}
public static List<List<String>> split(int numberOfElements, String[] sentences) {
List<List<String>> lists = new ArrayList<List<String>>();
int index = 0;
for (String sentence : sentences) {
if (index % numberOfElements == 0) {
lists.add(new ArrayList<String>());
}
lists.get(index / numberOfElements).add(sentences[index]);
index++;
}
return lists;
}
Output:
[[hello, how are you], [i am fine, and you ?], [thank you]]
[[hello, how are you, i am fine], [and you ?, thank you]]
public static void main(String[] args) {
String[] sentences = { "hello", "how are you", "i am fine", "and you ?", "thank you" };
List<List<String>> convertIntoList = convertIntoList(sentences, 2);
System.out.println(convertIntoList);
convertIntoList = convertIntoList(sentences, 3);
System.out.println(convertIntoList);
}
private static List<List<String>> convertIntoList(String[] sentences, int nbElement) {
List<List<String>> listOfListTarget = new ArrayList<List<String>>();
int currentIndex = 0;
while (currentIndex < sentences.length) {
int nextIndex = currentIndex + nbElement;
if (nextIndex > sentences.length) {
nextIndex = sentences.length;
}
final String[] copyOfRange = Arrays.copyOfRange(sentences, currentIndex, nextIndex);
List<String> subList = new ArrayList<String>();
subList.addAll(Arrays.asList(copyOfRange));
listOfListTarget.add(subList);
currentIndex+=nbElement;
}
return listOfListTarget;
}
Is this is a homework?
So you have an array of strings, and you want to create a List> with that, with each inner List containing at most x number of elements.
To get x number of elements and put them in a List, you can do a simple for loop.
String[] myStringArray = { ... };
List<String> myListOfString = new ArrayList<>();
for(int i=0; i<x; i++) {
myListOfString.add(myStringArray[i]);
}
So for example if you have these values
String[] myStringArray = {"a", "b", "c", "d", "e"};
x = 2;
You'll get the following list using the above loop:
["a", "b"]
Great! But we need to get all the contents of the myStringArray! How do we do that? Then let's do the first step, we iterate through all the contents of the array. We can do that like this.
int i=0;
while(i < myStringArray.length) {
System.out.println(myStringArray[i]);
i++;
}
Which will output:
a
b
c
d
e
This doesn't solve the problem... but at least we know how to iterate the whole thing. The next step is to get x of them. Sounds simple right? So basically we need to create a list of x from the contents. Maybe we can use the logic we created a few examples back to solve the problem.
// Create list of list of string here
int i = 0;
while(i < myStringArray.length) {
// Create list of string here
for(int j=0; j<x; j++) {
// Add myStringArray[j] to list of string here
}
// Add the list of string to the list of list of string here
i++;
}
Easy right? No. This gives the following lists:
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
["a", "b"]
Why? In the first loop, we are iterating up to how many is in the array. In the second loop, we are adding element 0 and 1 to a list. Obviously it wouldn't work. The second loop needs to be aware that it should not add previously added elements, and at the same time the first loop needs to be aware of what the second loop is doing. So you might think, maybe we can use the int i to indicate where the second loop should start?
int i = 0;
while(i<myStringArray.length) {
while(i<x) {
// add myStringArray[i];
i++;
}
i++;
}
Unfortunately, using the same values as previous, this will only give the following list
["a", "b"]
Because i is iterating through the whole array. So when it goes from 0 to length, whatever the value of i is used on the second array. When it loops again, i becomes 1, so the start of the second loop is at 1.
We need a separate variable to do the counting, while still keeping in mind where we currently are in the second loop.
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x) {
// Add myStringArray[count+i] to list of string
count++;
}
// Add to list of list of string
i += count + 1; // Need to be aware of how much we have processed
}
This will do what we want, but unfortunately we can get in trouble at certain values. Say x is 10 and myStringArray is only of length 2. This will throw an exception because when it reaches the point of count+i = 3, that index doesn't exist anymore. The second loop also needs to be aware of how much is still remaining.
Finally we'll have the following code
int i = 0;
while(i<myStringArray.length) {
int count = 0;
while(count < x && count+i < myStringArray.length) {
// Add myStringArray[count+i] to list of string
}
// Add to list of list of string
i += count; // Need to be aware of how much we have processed
}
Which will give
["a", "b"]
["c", "d"]
["e"]
Edit: Next time try to put some code that you tried something.
This code doesn't work. Whats wrong in it?
String arr[][] ={{"Jerry","s"},{"Jerry1","s1"},{"Oya","e"}};
String app1 = "Oya";
for(int i=0;i<arr.length();i++){
if(app1.equals(arr[i][i])){
appstr = arr[i][i+1];
return appstr;
}
}
Your secondary array subscripts are wrong. You know that the second dimension of the array will only ever be 0 - the word to compare and 1 - the value to return. This will do what you want:
String arr[][] = {
{"Jerry", "s" },
{"Jerry1", "s1"},
{"Oya", "e" }
};
String app1 = "Oya";
for (int i = 0; i < arr.length; i++) {
if (app1.equals(arr[i][0])) {
return arr[i][1];
}
}
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]