Printing ArrayList without brackets Java [duplicate] - java

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 10 months ago.
I have an ArrayList and I'm trying to print it without the bracket ("[]") , I don't know where the problem lies , is it with how the ArrayList is initialized or is it the print method ?
The output that I'm getting :
S0 = (q0) = [0, 2]
S1 = (q1) = [1, 0]
S2 = (q2) = [2, 1]
The output that I'm trying to get :
S0 = (q0) = {q0, q2}
S1 = (q1) = {q1, q0}
S2 = (q2) = {q2, q1}
How can this be achieved ?
CODE :
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void printArray(String[][] data){
System.out.print(" ");
for (int i = 0; i < data[0].length; i++) {
System.out.print("q" + i + " ");
}
System.out.println();
for (int i=0;i< data.length;i++){
System.out.print("q" + i + " ");
for (int j=0;j< data[0].length;j++){
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
public static ArrayList findEpsilon(String[][] data){
ArrayList<ArrayList<Integer> > aList = new ArrayList<>();
ArrayList<Integer> a1;
for (int i = 0; i < data.length ; i++) {
a1 = new ArrayList<>();
//aList = new ArrayList<>();
a1.add(i);
for (int j = 0; j < data[0].length; j++) {
if (data[i][j].contains("eps")){
a1.add(j);
}
}
aList.add(a1);
}
return aList;
}
public static void printArrayList(ArrayList<ArrayList<Integer>> aList){
for (int i = 0; i < aList.size(); i++) {
for (int j = 0; j < aList.get(i).size(); j++) {
System.out.println("S" + j + " = (q" + j + ") = " + aList.get(i).get(j) + "
");
}
// System.out.println();
}
}
public static void main(String args[]) {
String[][] data = {
{ "a", "b", "eps"},
{ "eps", "a", "-" },
{ "a", "eps", "b"}};
ArrayList<ArrayList<Integer> > aList = new ArrayList<ArrayList<Integer> >(3);
printArray(data);
System.out.println("\n");
aList.add(findEpsilon(data));
printArrayList(aList);
}
}

The type of aList should be ArrayList<ArrayList<ArrayList<Integer>>>. The compiler doesn't complain about this because the findEpsilon method returns an ArrayList without type parameters. It's generally good practice to specify the generic type (i.e., findEpsilon should return ArrayList<ArrayList<ArrayList<Integer>>>). You will need to fix this in several places.
If you want to use curly brackets for the array, you can then use the following code:
for (int j = 0; j < aList.get(i).size(); j++) {
String listAsString = aList.get(i).get(j).stream().map(Object::toString).collect(Collectors.joining(",", "{", "}"));
System.out.println("S" + j + " = (q" + j + ") = " + listAsString + " ");
}
The stream iterates over each of the elements in the list and converts them to a string. The Collectors.joining collector then joins the individual strings by inserting a comma between them and placing curly brackets at the start and at the end.

You can define a Lambda to take a List<String> and convert it like you want.
put the list.toString version in a StringBuilder.
then change the first and last characters to { and } respectively
import java.util.function.Function;
Function<List<String>, String> fmt = lst-> {
StringBuilder sb = new StringBuilder(lst.toString());
sb.setCharAt(0,'{');
sb.setCharAt(sb.length()-1,'}');
return sb.toString();
};
Now apply a list to the lambda.
List<String> s = List.of("A","B","C");
System.out.println(fmt.apply(s));
prints
{A, B, C}

Related

Make parenthesis the first priority on an arithmetic expression on TAC

So I have here my code implementing Three Address Code in arithmetic expression.
class ThreeAddressCode {
private static final char[][] precedence = {
{'/', '1'},
{'*', '1'},
{'+', '2'},
{'-', '2'}
};
private static int precedenceOf(String t)
{
char token = t.charAt(0);
for (int i=0; i < precedence.length; i++)
{
if (token == precedence[i][0])
{
return Integer.parseInt(precedence[i][1]+"");
}
}
return -1;
}
public static void main(String[] args) throws Exception
{
int i, j, opc=0;
char token;
boolean processed[];
String[][] operators = new String[10][2];
String expr="", temp;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter an expression: ");
expr = in.readLine();
processed = new boolean[expr.length()];
for (i=0; i < processed.length; i++)
{
processed[i] = false;
}
for (i=0; i < expr.length(); i++)
{
token = expr.charAt(i);
for (j=0; j < precedence.length; j++)
{
if (token==precedence[j][0])
{
operators[opc][0] = token+"";
operators[opc][1] = i+"";
opc++;
break;
}
}
}
System.out.println("\nOperators:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
//sort
for (i=opc-1; i >= 0; i--)
{
for (j=0; j < i; j++)
{
if (precedenceOf(operators[j][0]) > precedenceOf(operators[j+1][0]))
{
temp = operators[j][0];
operators[j][0] = operators[j+1][0];
operators[j+1][0] = temp;
temp = operators[j][1];
operators[j][1] = operators[j+1][1];
operators[j+1][1] = temp;
}
}
}
System.out.println("\nOperators sorted in their precedence:\nOperator\tLocation");
for (i=0; i < opc; i++)
{
System.out.println(operators[i][0] + "\t\t" + operators[i][1]);
}
System.out.println();
for (i=0; i < opc; i++)
{
j = Integer.parseInt(operators[i][1]+"");
String op1="", op2="";
if (processed[j-1]==true)
{
if (precedenceOf(operators[i-1][0]) == precedenceOf(operators[i][0]))
{
op1 = "t"+i;
}
else
{
for (int x=0; x < opc; x++)
{
if ((j-2) == Integer.parseInt(operators[x][1]))
{
op1 = "t"+(x+1)+"";
}
}
}
}
else
{
op1 = expr.charAt(j-1)+"";
}
if (processed[j+1]==true)
{
for (int x=0; x < opc; x++)
{
if ((j+2) == Integer.parseInt(operators[x][1]))
{
op2 = "t"+(x+1)+"";
}
}
}
else
{
op2 = expr.charAt(j+1)+"";
}
System.out.println("t"+(i+1)+" = "+op1+operators[i][0]+op2);
processed[j] = processed[j-1] = processed[j+1] = true;
}
}
}
Sample Output
Input : a * b / c
t1 = a * b
t2 = t1 / c
What the program does is evaluate the arithmetic expression and shows them step by step by operators.
Can you help me to include parenthesis in the priorities? and achieve an output like this
Sample Output
Input : a * ( b + c )
t1 = b + c
t2 = a * t2
Right now, the parenthesis is treated like an operand.
I did not use any of your code. Sorry.
This was a fun one to think about. I have never considered how you would do something like this. It does not follow all of the best practices to a "T", but the question inspired me to consider how you would do this in a rudimentary way.
You could make much of this code smaller by using more Java Frameworks, but it was enjoyable to strictly try to work this out logically.
This code is missing most validation (i.e. The user inputs an erroneous expression)
It does however check if there are an equal number of open and close parenthesis.
Lastly, I had to wrap things up so I did not extend into expressions with nested parenthesis.
Example a * ( b * ( c / d ) - e ) >> this code does not handle this scenario, and would have to be enhanced to accommodate for this.
Otherwise, it should give a pretty good idea as to one way you could go about building a program to work through parenthesis.
I hope it helps
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MathPriority {
public static void main(String[] args) {
String expression = "a * (b * c) + (d / e)"; //You can work out how you want input to com in
List<String> priorityList = getPriorityList(expression);//Find parenthesis and sets priority.
expression = expression.replace(" ", "").replace("(", "").replace(")", "");//Take out any spaces and parenthesis
for (int i = 0; i < priorityList.size(); i++) {//Replaces the piece in parenthesis with var and outputs var
expression = expression.replace(priorityList.get(i), "t" + (i + 1));
System.out.println("t" + (i + 1) + " = " + priorityList.get(i));
}
System.out.println("t" + (priorityList.size() + 1) + " = " + expression);//pushes final variable set
}
//You can use this to build a List of indexes of a character within a String
public static List<Integer> getAllOccurencesOfChar(List<String> expression, String indexO) {
List<Integer> parIndexList = new ArrayList<>();
for (int i = 0; i < expression.size(); i++) {
if (expression.get(i).contains(indexO)) {
if (!parIndexList.contains(i) && i > 0) {
parIndexList.add(i);
}
}
}
return parIndexList;
}
//Outputs a list of substrings. They can later be used to parse through the inital string
public static List<String> getPriorityList(String expression) {
List<String> priorityList = new ArrayList<>();
expression = expression.replace(" ", "");
String[] eParts = expression.split("");
List<String> expressionParts = new ArrayList<>();//Get expression into single chars
for (String e : eParts) {//If you change this to an Array.List, it will not work. This type of list is fixed in size
expressionParts.add(e);
}
List<Integer> parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
List<Integer> rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
if (parIndexList.size() != rParIndexList.size()) {
System.out.println("Your Equation does not have an equal number of open and close parenthesis");
System.exit(0);
}
//Work out the parenthesis
int loopIterator = parIndexList.size();//This will change as we iterate
for (int pars = loopIterator - 1; pars >= 0; pars--) {
int start = parIndexList.get(pars); //Define a start
int end = 0; //and End
//int end = rParIndexList.get(pars);
for (int contemplate = 0; contemplate < loopIterator; contemplate++) {//contemplate where given parenthesis starts and where its closing tag is
if (parIndexList.get(pars) < rParIndexList.get(contemplate)) {
end = rParIndexList.get(contemplate);//find first occurence and set true end
break;//then stop
}
}
String expre = "";
for (int concat = start + 1; concat < end; concat++) {
expre += expressionParts.get(concat);//put the priorityList's subExpression together
}
priorityList.add(expre);//add that subExpression to the list
expressionParts.subList(start, end + 1).clear();//remove these expressionParts
/*Re-establish where the parenthesis are, since we removed parts of the expression in the list*/
parIndexList = getAllOccurencesOfChar(expressionParts, "(");//find all open paranthesis
rParIndexList = getAllOccurencesOfChar(expressionParts, ")");//find all close paranthesis
loopIterator = parIndexList.size();//resize the forLoop
}
return priorityList;
}
public static List<Integer> getStartEndPosition(String fullExpression, String subExpression) {
List<Integer> sAndE = new ArrayList<>();
String[] eParts = subExpression.split("");
List<String> wordParts = new ArrayList<>();
wordParts.addAll(Arrays.asList(eParts));
/*Find multiples of same operand*/
List<Integer> add = getAllOccurencesOfChar(wordParts, "+");
List<Integer> subtract = getAllOccurencesOfChar(wordParts, "-");
List<Integer> divide = getAllOccurencesOfChar(wordParts, "/");
List<Integer> multiply = getAllOccurencesOfChar(wordParts, "*");
/*Find single Operands*/
int plus = subExpression.indexOf("+");
int minus = subExpression.indexOf("-");
int div = subExpression.indexOf("/");
int mult = subExpression.indexOf("*");
int multiOperands = plus + minus + div + mult;//See if multiples exist
int startingPosition = 0;
if (add.size() > 1 || subtract.size() > 1 || divide.size() > 1 || multiply.size() > 1
|| multiOperands > 0) {
//expression has multiple opreands of different types
String findStart = wordParts.get(0) + wordParts.get(1);
String findEnd = wordParts.get(wordParts.size() - 2) + wordParts.get(wordParts.size() - 1);
startingPosition = fullExpression.indexOf(findStart);
sAndE.add(startingPosition);
int endPosition = fullExpression.indexOf(findEnd);
sAndE.add(endPosition);
} else {
startingPosition = fullExpression.indexOf(subExpression);
sAndE.add(startingPosition);
sAndE.add(startingPosition + subExpression.length());
}
return sAndE;
}
}
String expression = "a * (b * c) + (d / e)"
Outputs:
t1 = d/e
t2 = b*c
t3 = a*t2+t1

deleting an object from an array of objects in java

import java.util.StringTokenizer;
class Count {
int count;
String name;
void SetCount(int c, String n) {
this.count = c;
this.name = n;
}
void Show() {
System.out.print("Word= " + name);
System.out.print(" Count= " + count);
System.out.println();
}
}
class Contains2 extends Count {
public static void main(String args[]) {
String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out";
int i, c2, j;
StringTokenizer st = new StringTokenizer(s, " ");
c2 = st.countTokens();
String[] test = new String[c2];
Count[] c = new Count[c2];
for (i = 0; i < c2; i++) {
c[i] = new Count();
}
i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
test[i] = token;
c[i].SetCount(0, test[i]);
i++;
}
for (i = 0; i < c2; i++) {
for (j = 0; j < c2; j++) {
if (c[i].name.equals(test[j]))
c[i].count += 1;
}
}
for (i = 0; i < c2; i++) {
c[i].Show();
}
}
}
so i made this small program to count the number every word was repeated in a paragraph. its working as planned but now i am getting duplicates of every word since i made separate objects for each and printing them all. so is there any way i could delete the duplicate words i mean deleting those objects based on their names. i can set them to null but it would still print them so i just wanna get rid of them or skip them somehow
You cannot adjust the size of a array once it's created. You could only create a new array with a different size and copy the non-null elements.
You could also set elements to null and just ignore those elements for printing...
for (i = 0; i < c2; i++) {
if (c[i] != null)
c[i].Show();
}
An alternative would be using a List, which allows you to remove elements.
Alternatively a Map<String, Integer> mapping from a word to the count could be used. In this case you don't even need the Count class:
String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out";
StringTokenizer st = new StringTokenizer(s, " ");
Map<String, Integer> map = new HashMap<>();
while (st.hasMoreTokens()) {
map.merge(st.nextToken(), 1, Integer::sum);
}
for (Map.Entry<String, Integer> e : map.entrySet()) {
System.out.print("Word= " + e.getKey());
System.out.print(" Count= " + e.getValue());
System.out.println();
}

Basic array method in a class - JAVA

Alright so I've created an array of type int with size 10.
I've initialized it to random values between 1-100.
Now my task is to write a method named output which will take an int array as a parameter and displays all elements of the array in a column like this:
Output
arr[0] : 17
arr[1] : 42
etc etc, but when I do it in eclipse it says
i cannot be resolved to a variable,
so I was thinking of re-initializing it in my method, but wouldn't that give me a whole set of different numbers?
private int [] nums;
public UsingArrays(){
nums = new int [10];
for (int i = 0; i <nums.length; i++){
nums[i] = (int)(Math.random()*100)+1;
}
}
public String Output(){
String string;
string = "Arr[" + i + "]:" + nums[i];
return string;
}
}
i cannot be resolved to a variable
You forgot to surround the whole thing with a for loop that will be declaring & using that i variable :
public void Output(int[] array){
String string = "";
for(int i = 0; i < array.length; i++) {
string += "Arr[" + i + "]:" + array[i] + "\n"; // not recommended
}
System.out.println(string);
}
And in such cases, it would be better if you use a StringBuilder, so as to avoid creating new String instances at each iteration:
public void Output(int[] array){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < array.length; i++) {
sb.append("Arr[" + i + "]:" + array[i] + "\n"); // Accumulate results
}
System.out.println(sb.toString()); // print final result
}
I do not know why you are trying to initialize int[] in a constructor and keep this array as a global variable when you said that 'method named output which will take an int array as a parameter'.
Here is a proper solution according to your requirements:
public static void main(String[] args) {
final int sizeOfArray = 10;
final int[] nums = new int[sizeOfArray];
//JAVA 7
for(int i = 0; i < sizeOfArray; i++){
nums[i] = (int)(Math.random() * 100) + 1;
}
//JAVA 8
IntStream.range(0,sizeOfArray)
.forEach(i -> nums[i] = (int)(Math.random() * 100) + 1);
output(nums);
}
private static void output(final int[] arrayToDisplay){
//JAVA 7
for(int i = 0; i < arrayToDisplay.length; i++){
System.out.printf("arr[%d] : %d \n",i,arrayToDisplay[i]);
}
//JAVA 8
IntStream.range(0,arrayToDisplay.length)
.forEach(i -> System.out.printf("arr[%d] : %d \n",i,arrayToDisplay[i]));
}
You should always make sure that all variables initialized and have an appropriate type assigned to them (at least in Java). If I were you, I would stick to Java 7 version of the code above
This problem won't be complied because there is not definition of what 'i' means in output method.
Another solution can be :
public String Output(){
StringBuffer sb = new StringBuffer();
int i=0;
while(i<nums.length){
sb.append("Arr[" + i + "]:" + nums[i]);
System.out.println(sb.toString());
sb.clear();
}
}

How to make a String from two set of list with alternate values

I have two lists which contains some values,I have to make String from them so that i will take the 1st value of first list and 1 st value of 2 nd list and also 2nd value of first list and 2 nd value of 2nd list and so on..Lets says those two lists contains the interview timings.So i am giving my code here
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
for(String a :interviewTimingToFrom1){
System.out.println("Timing 1:"+a);
}
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
for(String a :interviewTimingToFrom2){
}
The values contain in the 1 st and 2nd list are
Timing 1:12:00am
Timing 1:2:00am
Timing 2:1:00am
Timing 2:3:00am
So now i need to make a string like from 12.00am to 1.00 am ,from 2.00 am to 3.00am how i can do that .Please help
int maxSize = Math.max(interviewTimingToFrom1.size(),interviewTimingToFrom2.size());
StringBuilder result = new StringBuilder();
for (int i=0; i<maxSize; i++)
{
if (i < interviewTimingToFrom1.size())
result.append(interviewTimingToFrom1.get(i));
if (i < interviewTimingToFrom2.size())
result.append(interviewTimingToFrom2.get(i));
}
System.out.println(result.toString());
Try this;
List<String> interviewTimingToFrom1 = Arrays.asList(interviewTime1.split(","));
List<String> interviewTimingToFrom2 = Arrays.asList(interviewTime2.split(","));
if (interviewTimingToFrom1.size() == interviewTimingToFrom2.size()) {
int noOfSlots = interviewTimingToFrom1.size();
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom1.get(i));
}
} else {
System.out.println("No match");
int noOfSlots = (interviewTimingToFrom1.size() > interviewTimingToFrom2
.size() ? interviewTimingToFrom2.size()
: interviewTimingToFrom1.size());
for (int i = 0; i < noOfSlots; i++) {
System.out.println("from " + interviewTimingToFrom1.get(i)
+ " to " + interviewTimingToFrom2.get(i));
}
}

Getting the size of a single String in a array of string in java?

I have a Array of strings and I want to get the number of characters in the particular element in the array of strings,how i can do that?
like a array arr have = {"abc", "bgfgh", "gtddsffg"}
if i use
a.length; I will get the 3 which is the no.of elements in array
but I want a method which when I apply on each element like
for(int = 0; ; i++)
{
int t = a[i].length; //this method doesn't work
}
to return the number of characters in each element
which is the given example has to be 3,5 and 8
PLEASE REPLY?
package stackoverflow.q_24933319;
public class FindLength {
public static void main(String[] args) {
String[] arr = {"abc","bgfgh","gtddsffg"};
System.out.println("Array size is: " + arr.length);
for(String s : arr) {
System.out.println("Value is " + s + ", length is " + s.length());
}
}
}
//Output:
//Array size is: 3
//Value is abc, length is 3
//Value is bgfgh, length is 5
//Value is gtddsffg, length is 8
Unlike arrays, String doesn't have an attribute length, but it has a method length() which returns the String's length (in Unicode code units, see JavaDoc).
Try this: a[i].length().
I think a good idea is to put numbers of characters into another table. If you want, you can after that make some other operation on each of this number outside the for loop.
String [] input = {"aaaa", "sdasdwdas", "sd"};
int [] output = new int [input.length];
for (int i = 0; i < input.length; i++)
output[i] = input[i].length();
I think this code has the answer to your question in at least one of the functions.
public int[] getEachLengthIndividually(String[] arr)
{
int[] retArray = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
String string = arr[i];
retArray[i] = string.length();
}
return retArray;
}
public int totalSize(String[] arr)
{
int totalSize = 0;
for(String string : arr)
{
totalSize += string.length();
}
return totalSize;
}
public static void main(String[] args)
{
String[] arr = {"abc", "bgfgh", "gtddsffg"};
int[] eachLengthIndividually = getEachLengthIndividually(arr);
int totalLength = getTotalLength(arr);
for(int i = 0; i < eachLengthIndividually.length; i++)
{
System.out.println("The string " + arr[i] + " at index " + i + " has length of " + eachLengthIndividually[i]);
}
System.out.println("The total length of all strings in the array is " + totalLength);
}

Categories

Resources