Looping to create a custom String - java

I am looping to write data to an array of Strings. But what I want is that I create another loop where I will loop through the data of values as much as amount, but I would like to have some guidance on how to do so.
String[] s = new String[20];
String[] values = { "A", "B", "C", "D" };
final int amount = 2;
for (int i = 0; i < s.length; i++) {
s[i] = String.format("%s%04d", values[0], i); //TODO create another loop?
}
System.out.println(Arrays.toString(s));
The preferred output should be:
A0000, A0001, B0002, B0003, C0004, ...
The actual output is:
A0000, A0001, A0002, A0003, A0004, ...

Problem : your looping is wrong.
try this:
public static void main(String[] args) {
int k=0;
String[] s = new String[20];
String[] values = { "A", "B", "C", "D" };
final int amount = 2;
for (int i = 0; i < values.length; i++){
for (int j = 0; j < amount; j++){ //data of values as much as amount
s[k++] = String.format("%s%04d", values[i], k);
}
}
System.out.println(Arrays.toString(Arrays.copyOf(s,k)));
}
output:
[A0001, A0002, B0003, B0004, C0005, C0006, D0007, D0008]

You need to have 2 loops one to loop through the actual values array then another one is the amount (number of times).
Try this
List<String> a = new ArrayList<String>();
String[] values = { "A", "B", "C", "D" };
final int amount = 2;
int incrementVariable = 0;
for (int i = 0; i < values.length; i++){
for(int j = 0; j< amount; j++){
a.add(String.format("%s%04d", values[i], incrementVariable));
incrementVariable +=1;
}
}
System.out.println(a);
}
Output:
[A0000, A0001, B0002, B0003, C0004, C0005, D0006, D0007]

I like while loops better :)
String[] s = new String[10];
String[] values = {"A", "B", "C", "D"};
final int amount = 2;
for (int i = 0; i < values.length; ++i) {
int buffer = 0;
while(buffer <= amount) {
int index = i * amount + buffer;
s[index] = values[i] + String.format("%04d", index);
buffer++;
}
}
System.out.println(Arrays.toString(s));
[A0000, A0001, B0002, B0003, C0004, C0005, D0006, D0007, D0008, null]

Related

how to get String array containing distinct characters?

i have a String "iye" and i want make it distinct and also i have a array ["hi", "bye", "bebe"] and i want to make each element of the array and get the distinct characters only so my array would be like this ["hi", "bye", "be"] an then at last i want to take each element from that distinct array and count how many characters of distinctArray[i] are present in the distinct String "iye" and i will store that count for each element of distinct array in same order respectively to the elements of distinct array for e.g
sample input = "iyee" and ["hi", "bye", "bebe"]
sample ouput = [1, 2, 1]
below is my solution not working for larger inputs
static int[] mathProfessor(String B,String[] a){
List<String> distinct = new ArrayList<String>();
int[] arr = new int[a.length];
// store each value of names array as distinct value
for (int i = 0; i < a.length; i++) {
StringBuilder str = new StringBuilder();
a[i].chars().distinct().forEach(c -> str.append((char) c));
distinct.add(str.toString());
}
// System.out.println("distinct list: " + distinct.toString());
// store the count
int count = 0;
for (int i = 0; i < distinct.size(); i++) {
String s = distinct.get(i);
for (int j = 0; j < B.length(); j++) {
if (s.contains(Character.toString(B.charAt(j))))
count++;
}
arr[i] = count;
count = 0;
}
return arr;
}
static int[] mathProfessor(String b, String[] a) {
b = dist(b);
int count = 0;
String[] arr = new String[a.length];
int[] countArr = new int[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = dist(a[i]);
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < b.length(); j++) {
if (arr[i].contains(Character.toString(b.charAt(j))))
count++;
}
countArr[i] = count;
count = 0;
}
//System.out.println(Arrays.toString(countArr));
return countArr;
}
public static String dist(String s) {
StringBuilder sb = new StringBuilder();
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
if (set.add(s.charAt(i)) == true)
sb.append(s.charAt(i));
}
return sb.toString();
}
Using Java 8+ Streams:
static int[] mathProfessor(String b, String[] a) {
var distinctB = dist(b);
System.out.println(distinctB);
var result = new int[a.length];
for(int i=0, j=a.length; i < j; i++) {
result[i] = (int) Arrays.stream(dist(a[i]).split("")).filter(distinctB::contains).count();
}
return result;
}
public static String dist(String s) {
Set<String> set = new HashSet<>();
set.addAll(Arrays.asList(s.split("")));
return String.join("", set);
}

Is there a better way to write this method in Java - Random Generator

I have this method that takes in an array of spinner values. It takes the values and adds them to a prefix with 9 random digits.
So far, I have quite a lot of prefixes that go along with each spinner value.
Every value is checking if it's greater than 0, looping over the amount of values then adding the prefix + 9 digits. e.g R1 spinner value = 10, then an array gets spit out with R1+9DIGITS 10 times
There are so many if statements, and I'm sure there would be a better way. You an see below its extremely repetitive. Any help or ideas would be appreciated. Thanks!
Spinner<Integer>[] spinners = new Spinner[]{
r1Spinner, r2Spinner, r3Spinner, r5Spinner, rd2Spinner, rd8Spinner,m1Spinner,gSpinner, srSpinner, lcSpinner, singleURNSpinner,
customPrefixSpinner, prefixSpinner};
public static String[] randomPrefixGenerator(int[] values){
int R1 = values[0];
int R2 = values[1];
int R3 = values[2];
int R5 = values[3];
int RD2 = values[4];
int RD8 = values[5];
int M1 = values[6];
int G = values[7];
int SR = values[8];
int LC = values[9];
String[] urnR1 = new String[R1];
String[] urnR2 = new String[R2];
String[] urnR3 = new String[R3];
String[] urnR5 = new String[R5];
String[] urnRD2 = new String[RD2];
String[] urnRD8 = new String[RD8];
String[] urnG = new String[G];
String[] urnM1 = new String[M1];
String[] urnLC = new String[LC];
String[] urnSR = new String[SR];
if (R1 >= 0){
for (int i = 0; i < R1 ; i++) {
urnR1[i] = "R1" + random9digits();
}
}
if (R2 >= 0){
for (int i = 0; i < R2 ; i++) {
urnR2[i] = "R2" + random9digits();
}
}
if (R3 >= 0){
for (int i = 0; i < R3 ; i++) {
urnR3[i] = "R3" + random9digits();
}
}
if (R5 >= 0){
for (int i = 0; i < R5 ; i++) {
urnR5[i] = "R5" + random9digits();
}
}
if (RD2 >= 0){
for (int i = 0; i < RD2 ; i++) {
urnRD2[i] = "RD2" + random9digits();
}
}
if (RD8 >= 0){
for (int i = 0; i < RD8 ; i++) {
urnRD8[i] = "RD8" + random9digits();
}
}
if (M1 >= 0){
for (int i = 0; i < M1 ; i++) {
urnM1[i] = "M1" + random9digits();
}
}
if (G >= 0){
for (int i = 0; i < G ; i++) {
urnG[i] = "G" + random9digits();
}
}
if (LC >= 0){
for (int i = 0; i < LC ; i++) {
urnLC[i] = "LC" + random9digits();
}
}
if (SR >= 0){
for (int i = 0; i < SR ; i++) {
urnSR[i] = "SR" + random9digits();
}
}
return Arrays.stream(mergeArray(urnR1,urnR2, urnR3,urnR5, urnRD2, urnRD8, urnG, urnM1, urnLC, urnSR)).toArray(String[]::new);
}
I don't know what the merge arrays function does. But i think you can optimize your code a bit using the code below:
public static String[] randomPrefixGenerator(int[] values) {
// we can use a map to retrieve your prefixes by their index
Map<Integer, String> prefixNameByIndex = Map.of(
0, "R1",
1, "R2",
2, "R3",
3, "R5",
4, "RD2",
5, "RD8",
6, "M1",
7, "G",
8, "SR",
9, "LC"
);
// this stream goes through value 0 to 9
return IntStream.rangeClosed(0, 9)
// we need objects for the flatmap to work
.boxed()
// flatmap so we get a single list of strings
.flatMap(generatePrefixNamesForIndex(values, prefixNameByIndex))
.collect(Collectors.toList())
// the to array call as last
.toArray(String[]::new);
}
private static Function<Integer, Stream<? extends String>> generatePrefixNamesForIndex(int[] values, Map<Integer, String> prefixNameByIndex) {
return index -> {
// we can retrieve the prefix from the map by its index
var prefixValue = prefixNameByIndex.get(index);
// retrieve te number of iterations from parameters given in the method call
return IntStream.range(0, values[index])
.mapToObj(i -> prefixValue + random9digits());
};
}
Updated
I ended up thinking of a solution.
private static String[] urnCounter(String[] urns){
String[] urnsProcessed = new String[Integer.parseInt(urns[0])];
if (Integer.parseInt(urns[0]) >= 0){
for (int j = 0; j < Integer.parseInt(urns[0]); j++) {
urnsProcessed[j] = urns[1] + random9Digits();
}
}
return urnsProcessed;
}
public static String[] randomURNGenerator1(int[] values){
String[] urnR1 = urnCounter(new String[]{String.valueOf(values[0]),"R1"});
String[] urnR2 = urnCounter(new String[]{String.valueOf(values[1]),"R2"});
String[] urnR3 = urnCounter(new String[]{String.valueOf(values[2]),"R3"});
String[] urnR5 = urnCounter(new String[]{String.valueOf(values[3]),"R5"});
String[] urnRD2 = urnCounter(new String[]{String.valueOf(values[4]),"RD2"});
String[] urnRD8 = urnCounter(new String[]{String.valueOf(values[5]),"RD8"});
String[] urnG = urnCounter(new String[]{String.valueOf(values[7]),"G"});
String[] urnM1 = urnCounter(new String[]{String.valueOf(values[6]),"M1"});
String[] urnLC = urnCounter(new String[]{String.valueOf(values[9]),"LC"});
String[] urnSR = urnCounter(new String[]{String.valueOf(values[8]),"SR"});
return Arrays.stream(mergeArray(urnR1,urnR2, urnR3,urnR5, urnRD2, urnRD8, urnG, urnM1, urnLC, urnSR)).toArray(String[]::new);
}
// function to merge two arrays
#SafeVarargs
public static <T> Object[] mergeArray(T[]... arr) {
Object[] array = Stream.of().flatMap(Stream::of).toArray();
for(T[] passedObject: arr){
array = Stream.of(array, passedObject).flatMap(Stream::of).toArray(String[]::new);
}
return array;
}

mergeTwo CodingBat puzzle in Java

I am trying to solve this CodingBat problem:
Start with two arrays of strings, A and B, each with its elements in alphabetical order and without duplicates. Return a new array containing the first N elements from the two arrays. The result array should be in alphabetical order and without duplicates. A and B will both have a length which is N or more. The best "linear" solution makes a single pass over A and B, taking advantage of the fact that they are in alphabetical order, copying elements directly to the new array.
mergeTwo({"a", "c", "z"}, {"b", "f", "z"}, 3) → {"a", "b", "c"}
mergeTwo({"a", "c", "z"}, {"c", "f", "z"}, 3) → {"a", "c", "f"}
mergeTwo({"f", "g", "z"}, {"c", "f", "g"}, 3) → {"c", "f", "g"}
Attempt:
public String[] mergeTwo(String[] a, String[] b, int n) {
String[] op = new String[a.length + b.length];
for (int i = 0; i < a.length; i++) {
op[i] = a[i];
}
int j = 0;
for (int i = 0; i < op.length; i++) {
if (op[i] == null) {
j = i;
break;
}
}
for (int i = 0; i < b.length; i++) {
op[j] = b[i];
j++;
}
Arrays.sort(op);
ArrayList<String> help = new ArrayList<String>();
for (int i = 0; i < op.length - 1; i++) {
if (op[i] != op[i + 1]) {
help.add(op[i]);
}
}
String[] res = new String[help.size()];
for (int i = 0; i < help.size(); i++) {
res[i] = help.get(i);
}
String[] op2 = new String[n];
for (int i = 0; i < n; i++) {
op2[i] = res[i];
}
return op2;
}
So the problem is that all the tests pass except one:
Why is that?
This is the line that has the problem:
if (op[i] != op[i + 1]) {
You are looking for a pattern where the lsst of several identical strings doesn't match the next string.
In the failing case, there is no "next string" because there are exactly 3 unique strings.
One way to deal with that is to look for a pattern where this string is different than the last string but you don't really check the array for the last string (since the 1st array element has no last string). You use a variable, say last, to store the last string and transfer only when this element isn't equal to last.
Try this ...
String last = "";
for (int i = 0; i < op.length - 1; i++) {
if (!op[i].equals(last)) {
help.add(op[i]);
}
last = op[i];
}
Also note that in Java strings are compared with the equals() method.
With Java8 it can be done with few simple rows of code:
public String[] mergeTwo(String[] a, String[] b, int n)
{
Set<String> set = new HashSet();
set.addAll(Arrays.asList(a));
set.addAll(Arrays.asList(b));
List<String> list = new ArrayList(set);
return list.subList(0, n).toArray(new String[n]);
}
Another solution:
public String[] mergeTwo(String[] a, String[] b, int n) {
String[] arr = new String[n];
int aI = 0;
int bI = 0;
for(int i = 0; i < n; i++) {
if(a[aI].compareTo(b[bI]) < 0) {
arr[i] = a[aI];
aI++;
} else if(a[aI].compareTo(b[bI]) > 0) {
arr[i] = b[bI];
bI++;
} else {
arr[i] = a[aI];
aI++;
bI++;
}
}
return arr;
}

java : get computed values outside loop

I do some calculation inside for loop and when I println values inside the loop, I got the expected values,
now, I need also that these values will be available outside loop and not only get the latest value.
example :
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
int value = Integer.parseInt(matrix[i][j - 1]);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value ); //it print me only third value
I would like that the value 1,2,3 will be also available outside loop
If you want to have access to all three variables. you have to declare a data structure that holds all the values.
e.g.
String[][] matrix = { { "1", "2", "3" } };
List<Integer> list = new ArrayList();
String[] y= { "TEST" ,"BUG"};
int a = 0;
int value;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
value = Integer.parseInt(matrix[i][j - 1]);
list.add(value);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value );
Declare the variable value outside of your loop:
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
int value = 0;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
value = Integer.parseInt(matrix[i][j - 1]);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value );
But if you need all three values available you should use array or some other containers like ArrayList:
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
Arraylist<Integer> values = new Arraylist<Integer>();
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
values.add(Integer.parseInt(matrix[i][j - 1]));
System.out.println(values); //this is OK it print me 3 values
}
}
System.out.println(values);
you have to declare your variable (that you want to use outside of the for-loop) on top of your code.
Example:
for (...) {
//only valid in this for loop
int i = 1;
}
//valid also after this for loop
int i = 1;
for (...) {
}

How to print two dimensional array of strings as String

I know how to do the toString method for one dimensional arrays of strings, but how do I print a two dimensional array? With 1D I do it this way:
public String toString() {
StringBuffer result = new StringBuffer();
res = this.magnitude;
String separator = "";
if (res.length > 0) {
result.append(res[0]);
for (int i=1; i<res.length; i++) {
result.append(separator);
result.append(res[i]);
}
}
return result.toString();
How can I print a 2D array?
The Arrays class defines a couple of useful methods
Arrays.toString - which doesn't work for nested arrays
Arrays.deepToString - which does exactly what you want
String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}};
System.out.println(Arrays.deepToString(aastr));
Gives
[[hello, world], [Goodbye, planet]]
You just iterate twice over the elements:
StringBuffer results = new StringBuffer();
String separator = ","
float[][] values = new float[50][50];
// init values
for (int i = 0; i < values.length; ++i)
{
result.append('[');
for (int j = 0; j < values[i].length; ++j)
if (j > 0)
result.append(values[i][j]);
else
result.append(values[i][j]).append(separator);
result.append(']');
}
IMPORTANT: StringBuffer are also useful because you can chain operations, eg: buffer.append(..).append(..).append(..) since it returns a reference to self! Use synctactic sugar when available..
IMPORTANT2: since in this case you plan to append many things to the StringBuffer it's good to estimate a capacity to avoid allocating and relocating the array many times during appends, you can do it calculating the size of the multi dimensional array multiplied by the average character length of the element you plan to append.
public static <T> String to2DString(T[][] x) {
final String vSep = "\n";
final String hSep = ", ";
final StringBuilder sb = new StringBuilder();
if(x != null)
for(int i = 0; i < x.length; i++) {
final T[] a = x[i];
if(i > 0) {
sb.append(vSep);
}
if(a != null)
for(int j = 0; j < a.length; j++) {
final T b = a[j];
if(j > 0) {
sb.append(hSep);
}
sb.append(b);
}
}
return sb.toString();
}
Two for loops:
for (int i=1; i<res.length; i++) {
for (int j=1; j<res[i].length; j++) {
result.append(separator);
result.append(res[i][j]);
}
}
public static void main(String[] args) {
String array [] [] = {
{"*","*", "*", "*", "*", "*"},
{"*"},
{"*"},
{"*"},
{"*","*", "*", "*", "*", "*"},
{"*"},
{"*"},
{"*"},
{"*"},
{"*"}};
for (int row=0; row<array.length;row++) {
for (int column = 0; column < array[row].length; column++) {
System.out.print(array[row][column]);
}
System.out.println();
}
}

Categories

Resources