Change an array of ints to a series of strings - java

I'm trying to achieve the following output from the following input:
Sample input:
3 4
2 1
4 5
-1
Sample output:
7
3
9
So far, I have my program doing all of the math and I'm getting it to terminate when the user puts in a negative number. My problem is that I'm having trouble getting it to print in the above format. A sample of my input/output is below:
9 9
8 8
9 -8
[18, 16]
Here's my code so far:
import java.util.ArrayList;
import java.util.Scanner;
public class sums{
public static void main(String[]args){
int addition = 0;
int previous = 0;
ArrayList<String> sums = new ArrayList<String>();
String sumsy = new String("");
for (int i=0; i<=i;){
Scanner in = new Scanner(System.in);
previous = in.nextInt();
if (previous<0){
break;
}
else {
addition = in.nextInt();
if (addition<0) {
break;
}
else {
addition += previous;
sums.add(addition+"");
}
}
} System.out.println(sums);
}
}
I believe the answer lies in somehow using a delimiter ("/n") somewhere, and getting my array of ints to print out just as strings.
I'm sorry, these small things elude me completely. Can anyone point me in the right direction?
Thank you!
-Helen

for (String sum : sums) System.out.println(sum)
use this instead of
System.out.println(sums)

System.out is a PrintStream object, and its println methods are overloaded for a variety of different types.
In this case, because sums is an ArrayList, you're calling println(Object x), which works by calling String.valueOf(x) on the passed object (which in turn calls x.toString() if x does not equal null), and printing the resulting String.
Essentially, when you pass something other than a String or a primitive to println, you're delegating the details of how it gets printed to the class of the object. In this case, since ArrayList is a library class, you have no control over this.
To make it work the way you want, you need to iterate over the values in sums, something like:
for (String someSum : sums) {
System.out.println(someSum);
}
If you're not familiar with that loop syntax, see the second half of this page: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

sums is an list of strings, not a string, so printing it isn't going to give you what you want. You have two options, you could do
for(String i : sums){ System.out.println(i); }
or you could make sums a stringbuilder and do sums.append(addition) and then System.out.println(sums.toString())

Do you really have to use an ArrayList? IMO, this makes it much more complicated than necessary. From your example input, it appears that you simply want to sum each pair of numbers. This doesn't seem to require an array. You could just add the two numbers together and immediately print out the result.

Related

Finding the largest string in the second column of a 2d array

I have a 2d array and I'm trying to find the largest string only in the second column of the 2d array, but for some reason it only gives me the first string in the 2nd column even if there is a bigger string. Here's what I have:
class Main{
public static void main(String[] args) {
String[][] data = {
{"Jeep", "Wrangler", "35000"},
{"Honda", "civic", "25000"},
{"Toyota", "Corolla", "22000"}
};
LargestName(data);
}
public static void LargestName(String[][] a){
String largestN = a[0][1];
for(int i = 0; i < a.length; i++){
if(largestN.compareTo(a[i][1])<0){
largestN = a[i][1] + "";
}
}
System.out.println(largestN);
}
}
Again, I'm trying to compare the strings only in the second column of the 2d array but with what I have it only gives me the first string of the 2nd column "Wrangler", even if there is a larger string in the 2nd column. Please help
I cannot see a flaw in the code. So look at the definition of 'largest string': It is possible that the code really returns exactly that value that you chose in the beginning.
This can be easily tested by choosing a different start value.
On top of that you could add more System.out.println, or even better use a debugger to step through your code. This will give you a very good understanding of how the JVM executes your code.
You need to comapre length, compareTo is not good choice, please look what are you trying to do:
System.out.println("Wrangler".compareTo("civic"));
System.out.println("civic".compareTo("Corolla"));
System.out.println("Corolla".compareTo("Wrangler"));
result:
-12 32 -20

Print list of list of integer

I have the following list:
List<List<int[]>> graph;
How can I print the content of graph without using loop? I tried the following 2 methods but all of them failed to print:
int[][] input=new int[][]{{1,2,5},{1,3,6},{2,3,1}};
List<List<int[]>> graph = new ArrayList<>();
for (int i = 0; i <= 3; i++) graph.add(new ArrayList<>());
for (int[] conn : input) {
int city_A = conn[0], city_B = conn[1], price = conn[2];
graph.get(city_A).add(new int[] {city_B, price});
graph.get(city_B).add(new int[] {city_A, price});
}
graph.forEach(s->System.out.println("Output:"+s));
System.out.println(Arrays.deepToString(graph.toArray()));
Output:[[I#1fb3ebeb, [I#548c4f57]
Output:[[I#1218025c, [I#816f27d]
Output:[[I#87aac27, [I#3e3abc88]
Expected output is to print each element without going to new line:
Output: [[1,2], [1,3], [2,0]]
Edit: the original question has changed.
I think what you actually want is a string representation of your graph.Have you tried a simple
System.out.println(graph);
?
Leaving the answer to the original question up, which was how to print all the integers in the inner list without using a traditional for loop.
graph.forEach(innerList -> {
innerList.forEach(s-> System.out.println("Output: "+ s))
});
But why though..
Also the forEach is just the java functional library shorthand for a traditional for loop, so I'm not quite sure what you're gaining here. Hope that helps
Try this.
graph.stream creates a stream of List<int[]>
flatmap(List::stream) takes those lists and creates a single stream of int[]
Arrays.toString takes an array and prints it separated by commas.
Note that printing an array is printing an object. Its default toString is what you see when you print it so it won't work. Arrays.toString() actually iterates over each element and returns a string that is printable.
List<List<int[]>> graph = some list;
graph.stream().flatMap(List::stream)
.forEach(arr->System.out.print(Arrays.toString(arr) + " "));
More on printing arrays
Notice the numeric part (in hex) for printing out this array. The numeric part
comes from the hashCode. Also the [I in front of the first output means a simple int array. [[I signifies an array of int arrays.
int[] arr1 = {1,2};
System.out.println(arr1); // prints [I#4617c264 on my machine
System.out.println(Integer.toHexString(arr1.hashCode()));
int[][] arr2 = {{1,2},{3,4}};
System.out.println(arr2); // prints [[I#36baf30c on my machine

NZEC error in Hackerearth problem in java

I'm trying the solve this hacker earth problem https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/anagrams-651/description/
I have tried searching through the internet but couldn't find the ideal solution to solve my problem
This is my code:
String a = new String();
String b = new String();
a = sc.nextLine();
b = sc.nextLine();
int t = sc.nextInt();
int check = 0;
int againCheck =0;
for (int k =0; k<t; k++)
{
for (int i =0; i<a.length(); i++)
{
char ch = a.charAt(i);
for (int j =0; j<b.length(); j++)
{
check =0;
if (ch != b.charAt(j))
{
check=1;
}
}
againCheck += check;
}
}
System.out.println(againCheck*againCheck);
I expect the output to be 4, but it is showing the "NZEC" error
Can anyone help me, please?
The requirements state1 that the input is a number (N) followed by 2 x N lines. Your code is reading two strings followed by a number. It is probably throwing an InputMismatchException when it attempts to parse the 3rd line of input as a number.
Hints:
It pays to read the requirements carefully.
Read this article on CodeChef about how to debug a NZEC: https://discuss.codechef.com/t/tutorial-how-to-debug-an-nzec-error/11221. It explains techniques such as catching exceptions in your code and printing out a Java stacktrace so that you can see what is going wrong.
1 - Admittedly, the requirements are not crystal clear. But in the sample input the first line is a number.
As I've written in other answers as well, it is best to write your code like this when submitting on sites:
def myFunction():
try:
#MY LOGIC HERE
except Exception as E:
print("ERROR Occurred : {}".format(E))
This will clearly show you what error you are facing in each test case. For a site like hacker earth, that has several input problems in various test cases, this is a must.
Coming to your question, NZEC stands for : NON ZERO EXIT CODE
This could mean any and everything from input error to server earthquake.
Regardless of hacker-whatsoever.com I am going to give two useful things:
An easier algorithm, so you can code it yourself, becuase your algorithm will not work as you expect;
A Java 8+ solution with totally a different algorithm, more complex but more efficient.
SIMPLE ALGORITM
In you solution you have a tipical double for that you use to check for if every char in a is also in b. That part is good but the rest is discardable. Try to implement this:
For each character of a find the first occurence of that character in b
If there is a match, remove that character from a and b.
The number of remaining characters in both strings is the number of deletes you have to perform to them to transform them to strings that have the same characters, aka anagrams. So, return the sum of the lenght of a and b.
NOTE: It is important that you keep track of what you already encountered: with your approach you would have counted the same character several times!
As you can see it's just pseudo code, of a naive algorithm. It's just to give you a hint to help you with your studying. In fact this algorithm has a max complexity of O(n^2) (because of the nested loop), which is generally bad. Now, a better solution.
BETTER SOLUTION
My algorithm is just O(n). It works this way:
I build a map. (If you don't know what is it, to put it simple it's a data structure to store couples "key-value".) In this case the keys are characters, and the values are integer counters binded to the respective character.
Everytime a character is found in a its counter increases by 1;
Everytime a character is found in b its counter decreases by 1;
Now every counter represents the diffences between number of times its character is present in a and b. So, the sum of the absolute values of the counters is the solution!
To implement it actually add an entry to map whenever I find a character for the first time, instead of pre-costructing a map with the whole alphabet. I also abused with lambda expressions, so to give you a very different sight.
Here's the code:
import java.util.HashMap;
public class HackerEarthProblemSolver {
private static final String a = //your input string
b = //your input string
static int sum = 0; //the result, must be static because lambda
public static void main (String[] args){
HashMap<Character,Integer> map = new HashMap<>(); //creating the map
for (char c: a.toCharArray()){ //for each character in a
map.computeIfPresent(c, (k,i) -> i+1); //+1 to its counter
map.computeIfAbsent(c , k -> 1); //initialize its counter to 1 (0+1)
}
for (char c: b.toCharArray()){ //for each character in b
map.computeIfPresent(c, (k,i) -> i-1); //-1 to its counter
map.computeIfAbsent(c , k -> -1); //initialize its counter to -1 (0-1)
}
map.forEach((k,i) -> sum += Math.abs(i) ); //summing the absolute values of the counters
System.out.println(sum)
}
}
Basically both solutions just counts how many letters the two strings have in common, but with different approach.
Hope I helped!

Having trouble adding elements to ArrayList in correct order

So my program is supposed to iterate over a list of numbers (0-113) and then print the numbers line by line. If the number is odd, that should be added next to the number, if the number is divisible by 5, that should be added next to the number and so on. So I have my 4 boolean methods done and they look like this:
public static boolean isDivisibleBy5(int n){
if (n%5 ==0){
return true;
}
return false ;
}
Next I have a method that I am required to use as per assignment requirements and it is as follows:
public static ArrayList<String>iterate()
So the definition with this method is where I am having problems. Right now what I have is this:
public static ArrayList<String>iterate(){
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<114;i++){
if (isOdd(i)){
list.add(i+" Is odd");
}
if(isDivisibleBy5(i)){
list.add(i+" hi five");
}
if(isDivisbleBy7(i)){
list.add(i+" wow");
}
if (isPrime(i)){
list.add(i+" prime");
}
}
for(String elem:list)
System.out.println(elem);
return list;
}
But unfortunately my output looks like this:
0 hi five
1 Is odd
1 prime
3 Is odd
3 wow
3 prime
5 Is odd
5 hi five
5 prime
7 Is odd
7 prime
9 Is odd
10 hi five
10 wow
11 Is odd
I need it to look like this:
0, hi five
1, Is Odd, prime
2
3, Is odd, wow, prime
4
5, Is Odd, hi five, prime
etc.
So my question is basically how do I get all the conditions (when true) to add themselves to the same line with the corresponding number and also have the numbers that don't meet the conditions print on their lines as well, like 2 and 4 and 6.
I've been stuck on this question for awhile and I feel like there is a crucial piece of java that I am not thinking of that is required here. String Builder maybe? I'm not sure. Any help is appreciated. Even if you can just point me to a concept to look up and learn more of.
Thanks
EDIT:
I am seeing a lot of responses about building the string first and then adding to it. I believe this was the concept that I was not thinking of that has held me back so I will read up and practice implementing that. Thanks again for the quick responses. When I get it working I will come back here and up-vote anyone who helped.
You need to compose the string first and then add it only once:
public static ArrayList<String>iterate(){
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<114;i++){
String toAdd = String.valueOf(i);
if (isOdd(i)){
toAdd += ", Is odd";
}
if(isDivisibleBy5(i)){
toAdd += ", hi five";
}
if(isDivisbleBy7(i)){
toAdd += ", wow";
}
if (isPrime(i)){
toAdd += ", prime";
}
list.add(toAdd);
}
for(String elem:list)
System.out.println(elem);
return list;
}
So from what I see you're using list.add() and its adding a row every time you call it. Instead of using list.add() in every if statement, why don't you just add everything to a sting and then use list.add(string) to add it to your list?
Something like this:
public static ArrayList<String>iterate(){
String line =""; //creates line
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<114;i++){
line += i;
if (isOdd(i)){
line +=", Is odd";
}
if(isDivisibleBy5(i)){
line += ", high five"
}
...
list.add(line);

two dimensional array in java - difficulties

I'm used to python and django but I've recently started learning java. Since I don't have much time because of work I missed a lot of classes and I'm a bit confused now that I have to do a work.
EDIT
The program is suppose to attribute points according to the time each athlete made in bike and race. I have 4 extra tables for male and female with points and times.
I have to compare then and find the corresponding points for each time (linear interpolation).
So this was my idea to read the file, and use an arrayList
One of the things I'm having difficulties is creating a two dimensional array.
I have a file similar to this one:
12 M 23:56 62:50
36 F 59:30 20:60
Where the first number is an athlete, the second the gender and next time of different races (which needs to be converted into seconds).
Since I can't make an array mixed (int and char), I have to convert the gender to 0 and 1.
so where is what I've done so far:
public static void main(String[] args) throws FileNotFoundException {
Scanner fileTime = new Scanner (new FileReader ("time.txt"));
while (fileTime.hasNext()) {
String value = fileTime.next();
// Modify gender by o and 1, this way I'm able to convert string into integer
if (value.equals("F"))
value = "0";
else if (value.equals("M"))
value = "1";
// Verify which values has :
int index = valor.indexOf(":");
if (index != -1) {
String [] temp = value.split(":");
for (int i=0; i<temp.length; i++) {
// convert string to int
int num = Integer.parseInt(temp[i]);
// I wanted to multiply the first number by 60 to convert into seconds and add the second number to the first
num * 60; // but this way I multiplying everything
}
}
}
I'm aware that there's probably easier ways to do this but honestly I'm a bit confused, any lights are welcome.
Just because an array works well to store the data in one language does not mean it is the best way to store the data in another language.
Instead of trying to make a two dimensional array, you can make a single array (or collection) of a custom class.
public class Athlete {
private int _id;
private boolean _isMale;
private int[] _times;
//...
}
How you intend to use the data may change the way you structure the class. But this is a simple direct representation of the data line you described.
Python is a dynamically-typed language, which means you can think of each row as a tuple, or even as a list/array if you like. The Java idiom is to be stricter in typing. So, rather than having a list of list of elements, your Java program should define a class that represents a the information in each line, and then instantiate and populate objects of that class. In other words, if you want to program in idiomatic Java, this is not a two-dimensional array problem; it's a List<MyClass> problem.
Try reading the file line by line:
while (fileTime.hasNext())
Instead of hasNext use hasNextLine.
Read the next line instead of next token:
String value = fileTime.next();
// can be
String line = fileTime.nextLine();
Split the line into four parts with something as follows:
String[] parts = line.split("\\s+");
Access the parts using parts[0], parts[1], parts[2] and parts[3]. And you already know what's in what. Easily process them.

Categories