Removing space " " after last element [duplicate] - java

This question already has answers here:
Print out elements from an Array with a Comma between the elements
(14 answers)
Closed 5 years ago.
Extension to: Largest array / Comparing arrays (fresh view?)
Could someone give me a hint/solution how could I change code, so after the last output number it wouldn't add space after it?
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] productsAndCustomers = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] hind = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] raha = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
for (int m : raha) {
int largest = Integer.MIN_VALUE;
for (int p : hind) {
if (p > largest && p <= m) {
largest = p;
}
}
System.out.print(largest + " ");
}
}
}
Although it shows the right answer, It has to be that it won't show that spacing after that last output number. What would be the best option?

You can create a variable space and initialize it with a space after the first iteration like this :
String space = "";
for (int m : raha) {
//Your code...
System.out.print(space + largest);
space = " ";
}

Good idea is to use StringBuilder - you could use method append() to add all largest and after the for loop you could use its delete() method to get rid of last character.

I would suggest just using a regular, not an enhanced for loop so you can know when you are checking the raha array's last element.
Try:
for(int i = 0; i < raha.length; i++) {
// Your code
if(raha[i] != raha.length - 1)
System.out.println(largest + " ");
else
System.out.println(largest);
}

If you're using Java 8, then there's a simple method: instead of printing the results right away, you can collect them into a collection, and then use String.join method:
List<String> results = new ArrayList<>();
for (int m : raha) {
int largest = Integer.MIN_VALUE;
for (int p : hind) {
if (p > largest && p <= m) {
largest = p;
}
}
results.add(Integer.toString(largest));
}
System.out.println(String.join(" ", results));
If you're not using Java 8, then you will have to use some third party library that provides a similar join method.
If you don't want to collect the results, then you will have to track the index (so use a regular for loop instead of outer foreach) and omit the space for the last index.

You can iterate over array with for loop and implement simple if check to see if current iteration is last one:
if (i == array.length - 1)
System.out.print(element);
else
System.out.print(element + " ");
There are many more different ways, this is one of the easiest I can remember.

Related

How to know the fewest numbers we should add to get a full array

recently I met a question like this:
Assume you have an int N, and you also have an int[] and each element in this array can only be used once time. And we need to design an algorithm to get 1 to N by adding those numbers and finally return the least numbers we need to add.
For example:
N = 6, array is [1,3]
1 : we already have.
2 : we need to add it to the array.
3 : we can get it by doing 1 + 2.
4: 1 + 3.
5 : 2 + 3.
6 : 1 + 2 + 3.
So we just need to add 2 to our array and finally we return 1.
I am thinking of solving this by using DFS.
Do you have some better solutions? Thanks!
Here's an explanation for why the solution the OP posted works (the algorithm, briefly, is to traverse the sorted existing elements, keep an accumulating sum of the preceding existing elements and add an element to the array and sum if it does not exist and exceeds the current sum):
The loop tests in order each element that must be formed and sums the preceding elements. It alerts us if there is an element needed that's greater than the current sum. If you think about it, it's really simple! How could we make the element when we've already used all the preceding elements, which is what the sum represents!
In contrast, how do we know that all the intermediate elements will be able to be formed when the sum is larger than the current element? For example, consider n = 7, a = {}:
The function adds {1,2,4...}
So we are up to 4 and we know 1,2,3,4 are covered,
each can be formed from equal or lower numbers in the array.
At any point, m, in the traversal, we know for sure that
X0 + X1 ... + Xm make the largest number we can make, call it Y.
But we also know that we can make 1,2,3...Xm
Therefore, we can make Y-1, Y-2, Y-3...Y-Xm
(In this example: Xm = 4; Y = 1+2+4 = 7; Y-1 = 6; Y-2 = 5)
Q.E.D.
I don't know if this is a good solution or not:
I would create a second array (boolean array) remembering all numbers I can calculate.
Then I would write a method simulating the adding of a number to the array. (In your example the 1, 3 and 2 are added to the array).
The boolean array will be updated to always remember which values (numbers) can be calculated with the added numbers.
After calling the add method on the initial array values, you test for every Number x ( 1 <= x <= N ) if x can be calculated. If not call the add method for x.
since my explanation is no good I will add (untested) Java code:
static int[] arr = {3,5};
static int N = 20;
//An Array remembering which values can be calculated so far
static boolean[] canCalculate = new boolean[N];
//Calculate how many numbers must be added to the array ( Runtime O(N^2) )
public static int method(){
//Preperation (adding every given Number in the array)
for(int i=0; i<arr.length; i++){
addNumber(arr[i]);
}
//The number of elements added to the initial array
int result = 0;
//Adding (and counting) the missing numbers (Runtime O(N^2) )
for(int i=1; i<=N; i++){
if( !canCalculate[i-1] ){
addNumber(i);
result++;
}
}
return result;
}
//This Method is called whenever a new number is added to your array
//runtime O(N)
public static void addNumber( int number ){
System.out.println("Add Number: "+(number));
boolean[] newarray = new boolean[N];
newarray[number-1] = true;
//Test which values can be calculated after adding this number
//And update the array
for(int i=1; i<=N; i++){
if( canCalculate[i-1] ){
newarray[i-1] = true;
if( i + number <= N ){
newarray[i+number-1] = true;
}
}
}
canCalculate = newarray;
}
Edit: Tested the code and changed some errors (but rachel's solution seems to be better anyway)
It is a famous problem from dynamic programming. You can refer to complete solution here https://www.youtube.com/watch?v=s6FhG--P7z0
I just found a possible solution like this
public static int getNum(int n, int[] a) {
ArrayList<Integer> output = new ArrayList<Integer>();
Arrays.sort(a);
int sum = 0;
int i = 0;
while(true) {
if (i >= a.length || a[i] > sum + 1) {
output.add(sum + 1);
sum += sum + 1;
} else {
sum += a[i];
i++;
}
if (sum >= n) {
break;
}
}
return output.size();
};
And I test some cases and it looks correct.
But the one who write this didn't give us any hints and I am really confused with this one. Can anybody come up with some explanations ? Thanks!

Finding the same value at multiple indexes

I created a java program that will search for a value in array but my problem is when I input the same value in a different index, the first index is the only one that will be on output.
Example index 0 = 2, index 1 = 3, index 2 = 2
Output : array 2 is found at index 0 only
I break it on the loop to stop but if I did not do that, it will loop the Output
Here's what I want for Output: array 2 is found at index 0,2
Code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Buff {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter how many index :");
int v = Integer.parseInt( in .readLine());
int x;
int[] c = new int[v];
int vv;
for (x = 0; x < v; x++) {
System.out.print("Enter your value :");
c[x] = Integer.parseInt( in .readLine());
}
System.out.print("Enter your search number :");
int xx = Integer.parseInt( in .readLine());
for (x = 0; x < v; x++) {
if (c[x] == xx) {
System.out.print("array " + xx + " found at index :" + x);
break;
} else {
System.out.print("array not found");
}
}
}
}
You can also use StringBuilder if all you care is to output the indexes.
StringBuilder sb = new StringBuilder("array" + xx +" is found at index: ");
for (x = 0; x < v; x++) {
if (c[x] == xx) {
sb.append(x).append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
} else {
System.out.println("array not found");
}
The solution to to make a list of the indexes that match and populate it in your for loop.
then after the for loop is done, print out the results
List<Integer> foundIndexes = new ArrayList<>();
for (x = 0; x < v; x++) {
if (c[x] == xx) {
foundIndexes.add(x);
}
}
//now we looped through whole array
if(foundIndexes.isEmpty()){
System.out.print("array not found");
}else{
System.out.print("array " + xx + " found at index : ");
for(Integer i : foundIndex){
System.out.print(i + ",");
}
}
This will print out array 2 is found at index 0,2, with a trailing comma. It's slightly more complicated to not have a trailing comma at the last index but I will leave that up to you to figure out.
If I understand correctly the problem is the following:
You have elements in an array, you want to check if a particular value is in more than once position of the array, your problem is if you simply remove the break statement, it shows a message every time you don't find the desired number, that's frankly the only problem I see with removing the break statement.
Personally, what I'd do one of these two things:
Option A: You can create a boolean variable that changes if you find a number, then wait to deliver the "array not found" message until you have stopped searching for it, like this:
boolean found = false;
for( x=0; x<v; x++)
{
if(c[x] == xx)
{
System.out.println("array " + xx + " found at index :"+x);
found = true;
}
}
if (found = false)
{
System.out.println("array not found");
}
println does the same as print, only it introduces a \n at the end, so the response looks like this:
array 2 found at index :0
array 2 found at index :2
Instead of:
array 2 found at index :0
array 2 found at index :2
Option B: Probably more elegant solution would be to create other array that store the positions in which you have found the element you are looking for, then print them all at once, you could do this going over the array twice (one to count how many positions the array has to have, another to check the positions of the elements) or simply use an ArrayList, but since this looks like learning material I'm going to guess that's out of the question.
Also if it is possible, try to word your question better because I'm still not even sure if this is what you are asking.

Delete duplicates in array, Java [duplicate]

This question already has answers here:
How to efficiently remove duplicates from an array without using Set
(48 answers)
Closed 8 years ago.
I have written a method to count the number of occurrences of the words in a word file. Prior, in another method, i have sorted the words to appear in alphabetical order. There for a sample input into this method will look like this:
are
away
birds
birds
going
going
has
My question is.. How do i delete the repeated occurrences in this method? (after counting ofcoz) I have tried to use another string array to copy the unique ones into that string array, but i get a null pointer exception.
public static String[] counter(String[] wordList)
{
for (int i = 0; i < wordList.length; i++)
{
int count = 1;
for(int j = 0; j < wordList.length; j++)
{
if(i != j) //to avoid comparing itself
{
if (wordList[i].compareTo(wordList[j]) == 0)
{
count++;
}
}
}
System.out.println (wordList[i] + " " + count);
}
return wordList;
}
Any help will be much appreciated.
Oh, and my current output looks something like this:
are 1
away 1
birds 2
birds 2
going 2
going 2
has 1
I would prefer using Map to store word occurrence. Keys in the map are stored in Set so it can't be duplicated. What about something like this?
public static String[] counter(String[] wordList) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < wordList.length; i++) {
String word = wordList[i];
if (map.keySet().contains(word)) {
map.put(word, map.get(word) + 1);
} else {
map.put(word, 1);
}
}
for (String word : map.keySet()) {
System.out.println(word + " " + map.get(word));
}
return wordList;
}
I already posted an answer on this question. Your question is almost identical - he was having problems creating another array and getting an NPE too.
This is what I came up with (assuming the array is sorted):
public static String[] noDups(String[] myArray) {
int dups = 0; // represents number of duplicate numbers
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is the same
if (myArray[i].equals(myArray[i - 1]))
dups++; // add one to number of duplicates
}
// create return array (with no duplicates)
// and subtract the number of duplicates from the original size (no NPEs)
String[] returnArray = new String[myArray.length - dups];
returnArray[0] = myArray[0]; // set the first positions equal to each other
// because it's not iterated over in the loop
int count = 1; // element count for the return array
for (int i = 1; i < myArray.length; i++)
{
// if current number in original array is not the same as the one before
if (!myArray[i].equals(myArray[i-1]))
{
returnArray[count] = myArray[i]; // add the number to the return array
count++; // continue to next element in the return array
}
}
return returnArray; // return the ordered, unique array
}
Sample input/output:
String[] array = {"are", "away", "birds", "birds", "going", "going", "has"};
array = noDups(array);
// print the array out
for (String s : array) {
System.out.println(s);
}
Outputs:
are
away
birds
going
has

Iterating through ArrayList to get 5 Largest Numbers

Yes, this is homework, but I need some help with it. I have been able to make it sort through the highest number, but none of the numbers are correct after that. List of numbers: http://pastebin.com/Ss1WFGv1
Right now, we are learning arrays, so is this simply trying to shoot a fly with a cannonball?
package hw2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class HW2 {
public static ArrayList<Integer> nums1 = new ArrayList<Integer>();
public static int size = 0;
public static void main(String[] args) throws Exception {
ArrayList<Integer> sortedNums = new ArrayList<Integer>();
readFile();
System.out.println("Name: Jay Bhagat" + "\n" + "Email: xxxxxx");
size = nums1.size();
for(int l = 0; l<=10;l++){
nums1.set(sortThis(nums1, l), 90009);
System.out.println("\n\n");
}
// for (int k = 0; k <= size - 1; k++) {
// System.out.println("Number " + (k + 1) + sortedNums.get(k));
//
// }
}
public static void readFile() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("L:\\numbers.txt"));
while (reader.readLine() != null) {
nums1.add(Integer.parseInt((reader.readLine())));
}
reader.close();
}
public static int sortThis(ArrayList<Integer> current, int offset) {
int j = 0;
int tempNum = 0;
int curNum = 0;
int finalIndex = 0;
int prevIndex = 0;
int curIndex = 0;
for (j = 0; j < size-offset; j++) {
curIndex = j;
nums1.trimToSize();
curNum = current.get(j);
//Thread.sleep(1000);
if(curNum!=90009){
if (curNum > tempNum) {
tempNum = curNum;
System.out.println(tempNum);
prevIndex = j;
finalIndex = prevIndex;
}
if (curNum < tempNum) {
finalIndex = prevIndex;
}
}
}
return finalIndex;
}
}
An approach that lets you make just one pass through the list and doesn't require sorting:
Declare an array of 5 integers: int[] largest = new int[5];
Put the first 5 elements in the ArrayList into largest.
Starting with the 6th element, look at each element N in the ArrayList, and if N is larger than any element in largest, throw out the smallest number currently in largest and replace it with N.
If you need to exclude duplicates, the algorithm can be modified easily (just skip over any ArrayList element that's already in largest).
Why not use Collections.sort(List list) or Arrays.Sort(arr). This will save much of effort. Or is it part of your task?
Assuming your collection is sorted, and you want the last 5 elements, try this out:
for (int i = sortedNums.size() - 5; i < sortedNums.size(); ++i) {
System.err.println(sortedNums.get(i));
}
How I would go about doing this:
Create a temporary ArrayList, as a copy of the initial one.
After each largest element is found, remove it from the temporary ArrayList and add it to your 5 largest numbers
Repeat until complete
edit* This does not require your elements to be sorted, and has a fairly poor efficiency as a result
I assume you do not have the liberty to use sort and suchlike, considering this is a homework. So here is outline of an algorithm that you can try to implement
create an array of five integers (we will keep this sorted)
for each element in the list
find the index of the element in the array that it is greater than
if no such element exists in the array (i.e. it is smaller than all elements in the array)
continue on to the next element in the list
else
push all elements in the array to one index below, letting them fall off the
edge if need be (e.g. if the number in list is 42 and the array has
45 and 40 at index 3 and 2 respectively then
move arr[1] to arr[0], and arr[2] (40) to arr[1] and set arr[2] = 42)
end if
end for
At the end the array will have the five elements
I will leave one question for you to answer (it is important): what should you set the array to initially?
You only need two lines of code:
Collections.sort(nums1);
List<Integer> high5 = nums1.subList(nums1.size() - 5, nums1.size());
If you must "do it yourself", the simplest way to sort is a bubble sort:
iterate over the list
swap adjacent numbers if they are in the wrong order
repeat n times
Not efficient but very easy to code.

ArrayList of int array in java

I'm new to the concept of arraylist. I've made a short program that is as follows:
ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));
It gives the output: Arraylist contains:[I#3e25a5
Now my questions are:
How to display the correct value i.e. 1 2 3.
How can I access the single element of array a1 i.e. if I want to know the value at a1[1].
First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Use Arrays.toString( arl.get(0) ).
arl.get(0)[1]
The setup:
List<int[]> intArrays=new ArrayList<>();
int anExample[]={1,2,3};
intArrays.add(anExample);
To retrieve a single int[] array in the ArrayList by index:
int[] anIntArray = intArrays.get(0); //'0' is the index
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray ) {
System.out.println("Arraylist contains:" + aNumber );
}
To retrieve all int[] arrays in the ArrayList:
//iterate the ArrayList, get and print the elements of each int[] array
for(int[] anIntArray:intArrays) {
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray) {
System.out.println("Arraylist contains:" + aNumber);
}
}
Output formatting can be performed based on this logic. Goodluck!!
In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.
The answer to your first question is therefore
System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );
If you're looking for particular elements, the returned int[] object must be referenced as such.
The answer to your second question would be something like
int[] contentFromList = arl.get(0);
for (int i = 0; i < contentFromList.length; i++) {
int j = contentFromList[i];
System.out.println("Value at index - "+i+" is :"+j);
}
You have to use <Integer> instead of <int>:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}
Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.
Using,
Arrays.toString(arl.get(0))
means splitting the String object into a substring if you want to insert anything in between, such as commas.
Here's what I think amv was looking for from an int array viewpoint.
System.out.println("Arraylist contains: "
+ arl.get(0)[0] + ", "
+ arl.get(0)[1] + ", "
+ arl.get(0)[2]);
This answer is a little late for amv but still may be useful to others.
For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.
ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
while(n > 0)
{
int d = scan.nextInt();
Integer temp[] = new Integer[d];
for (int i = 0 ; i < d ; i++)
{
int t = scan.nextInt();
temp[i]=Integer.valueOf(t);
}
arrayList.add(temp);
n--;
}//n is the size of the ArrayList that has been taken as a user input & d is the size
//of each individual array.
//to print something out from this ArrayList, we take in two
// values,index and index1 which is the number of the line we want and
// and the position of the element within that line (since the question
// followed a 1-based numbering scheme, I did not change it here)
System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));
Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.
java.util.Arrays.toString() converts Java arrays to a string:
System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));
ArrayList<Integer> list = new ArrayList<>();
int number, total = 0;
for(int i = 0; i <= list.size(); i++){
System.out.println("Enter number " + (i + 1) + " or enter -1 to end: ");
number = input.nextInt();
list.add(number);
if(number == -1){
list.remove(list.size() - 1);
break;
}
}
System.out.println(list.toString());
for(int i: list){
System.out.print(i + " ");
total+= i;
}
System.out.println();
System.out.println("The sum of the array content is: " + total);
Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.
List<Integer> integerList = IntStream.range(0,100)
.boxed()
.toList();
This is one of the ways, you can initialize the fixed size ArrayList in Java using Java8+ - Stream API. integerList is going to contain integer values from 0 to 99.

Categories