How to Convert String of numbers to a distinct ArrayList - java
I have a troubles with an application.
I would like to move my String into this ArrayList.
My String contains numbers like 15 17 18 110 113 (numbers from 1 do 200).
I have about 80 numbers in one String, eg.:
I/System.out: 15 13 13 12 12 11 11 21 21 39 39 38 38 40 40 41 41 42 42 43 43 74 74 75 75 76 76 77 77 78 78 80 80 99 99 100 100 102 102 103 103 105 105 104
While I have List<String> tmpPath = new ArrayList<>(); and I have tried two different methods:
1.
public void transferStringToArray(string s1){
for(int i = 0; i < s1.length(); i++){
int extra = 0;
if(s1.charAt(i) != ' '){
String x = Character.toString(s1.charAt(i));
tmpPath.add(extra, x);
else extra++;
}
}
where the output is:
I/System.out: [4, 0, 1, 5, 0, 1, 5, 0, 1, 3, 0, 1, 3, 0, 1, 2, 0, 1, 2, 0, 1, 0, 0, 1, 0, 0, 1, 9, 9, 9, 9, 0, 8, 0, 8, 8, 7, 8, 7, 7, 7, 7, 7, 6, 7, 6, 7, 5, 7, 5, 7, 4, 7, 4, 7, 3, 4, 3, 4, 2, 4, 2, 4, 1, 4, 1, 4, 0, 4, 0, 4, 8, 3, 8, 3, 9, 3, 9, 3, 1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 5, 1]
(numbers are printed from last to first number which is wrong with my assumptions)
2.
public void transferStringToArray(string s1){
for(int i = 0; i < s1.length(); i++)
if(s1.charAt(i) != ' '){
String x = Character.toString(s1.charAt(i));
tmpPath.add(x);
}
where the output is in good order, but one number means one index of an array.
I/System.out: [1, 5, 1, 3, 1, 3, 1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 3, 9, 3, 9, 3, 8, 3, 8, 4, 0, 4, 0, 4, 1, 4, 1, 4, 2, 4, 2, 4, 3, 4, 3, 7, 4, 7, 4, 7, 5, 7, 5, 7, 6, 7, 6, 7, 7, 7, 7, 7, 8, 7, 8, 8, 0, 8, 0, 9, 9, 9, 9, 1, 0, 0, 1, 0, 0, 1, 0, 2, 1, 0, 2, 1, 0, 3, 1, 0, 3, 1, 0, 5, 1, 0, 5, 1, 0, 4]
Do you have any ideas how to move full number as one index separated by a space?
Also I have one more question:
How could I delete all repeated numbers? I know, that numbers are printed once or twice but in the result I have to have unique numbers.
All you need to do is a split with space s.split("\\s+"), and then put the result in a Set like this:
Set<String> set = new HashSet<>(Arrays.asList(s.split("\\s+")));
Or if you want to maintain the order, you can use :
Set<String> set = new LinkedHashSet<>(Arrays.asList(s.split("\\s+")));
If you are looking to use List and nothing else, then you can use, distinct like so :
List<String> set = Arrays.stream(s.split("\\s+"))
.distinct()
.collect(Collectors.toList());
Outputs
[15, 13, 12, 11, 21, 39, 38, 40, 41, 42, 43, 74, 75, 76, 77, 78, 80, 99, 100, 102, 103, 105, 104]
To convert space separated string into an array list :
You first need to split your string into an string array and then convert it into array list
public void convertStringToList() {
String stringToSplit = "15 13 13 12";
String[] splittedString = stringToSplit.split(" "); // Will split string based upon the space into an string array
List<String> listOfStrings = Arrays.asList(splittedString);
}
To remove the duplicates, you can insert all the array lists value into a Set. A set is a data structure in java which stores only unique values.
Set<String> uniqueValuesSet = new HashSet<>(listOfStrings);
for(String str : uniqueValuesSet) {
System.out.println(str);
}
In 2nd point, you might see your output is in random order. That is because HashSet doesn't maintain order of elements. If you need to maintain order as well. Use LinkedHashSet.
Set<String> uniqueValuesSet = new LinkedHashSet<>(listOfStrings);
for(String str : uniqueValuesSet) {
System.out.println(str);
}
Note: This solution assumes number in the original string are single space separated. If you want solution irrespective of number of spaces between 2 numbers, replace this line in point 1
String[] splittedString = stringToSplit.split(" ");
To
String[] splittedString = stringToSplit.split("\\s+");
I'm sticking with Set, as MaciejB wanted to eliminate duplicates and that's the contract of Set.
And, as MaciejB mentioned order too, I parsed them as Integer & put 'em in a TreeSet.
That looks like this:
Set<Integer> set = Stream.of(s.split("\\s+")).map(Integer::parseInt).collect(Collectors.toCollection(TreeSet::new));
Or if you prefer multiple lines:
Set<Integer> set = Stream // Result is ordered, parsed Set
.of(s.split("\\s+")) // -> String[]
.map(Integer::parseInt) // -> Integer[] for order in TreeSet
.collect(Collectors.toCollection(TreeSet::new)); // no duplicates
Outputs:
[11, 12, 13, 15, 21, 38, 39, 40, 41, 42, 43, 74, 75, 76, 77, 78, 80, 99, 100, 102, 103, 104, 105]
Related
Not able to solve Plus One Java problem on Leetcode [duplicate]
This question already has answers here: Plus one leetcode (7 answers) Closed 4 months ago. I am trying to solve Plus One on Leetcode The description is as follows: You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. Increment the large integer by one and return the resulting array of digits. Example 1: Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4]. My code is: class Solution { public int[] plusOne(int[] digits) { long temp=0;int c=0; for(int i:digits) { temp=temp*10+i; //System.out.println(temp); } //System.out.println(temp); temp+=1; //System.out.println(temp); long copy=temp; while(copy>0) { copy/=10; c++; } int[] result=new int[c]; for(int i=c-1;i>=0;i--) { //System.out.println((int)temp%10); result[i]=(int)temp%10; // System.out.println(result[i]); temp/=10; } return result; } } The problem is when I am trying to extract the number in the unit's digit it is givig 9 instead of 1. Expected output:[9,8,7,6,5,4,3,2,1,1] My Output:[9,8,7,6,5,4,3,2,1,9]
There is nothing really wrong with your code...it just needs a little tweak. The problem you are having is within the for loop that converts the incremented number held in temp to an int[] Array. Casting the temp % 10 to an int as in result[i] = (int) temp % 10; is going to produce an undesirable result. temp is a long and therefore shouldn't be cast to int until is has finished its modulo calculation. So, the simple solution would be to wrap the equation within parentheses, for example: result[i] = (int) (temp % 10); That should solve the immediate problem. An even bigger problem is the fact that you are limited to a numerical value that can only fit into a long data type. An int[] Array can hold an extremely large number if you were to take each element of that array and sequentially combine the digits. A long data type for example can only hold an unsigned value of 9223372036854775807. As you can see, this would create an int[] Array of 19 elements and that's a small Array. What if the Array contained 100 elements (digits)? That's a pretty big number but not necessarily out of the realm of use. This is why you have been advised (in comments) to utilize the java.math.BigInteger class. With BigInteger, you can work with any size of integer number which is basically what you really need. Here is how you could carry out the same task using BigInteger: public int[] plusOne(int[] digits) { java.math.BigInteger num = java.math.BigInteger.ZERO; // Convert int[] Array to a BigInteger number... for (int b : digits) { num = num.multiply(java.math.BigInteger.valueOf(10)) .add(java.math.BigInteger.valueOf(b)); } // Add 1 to the determined BigInteger number num = num.add(java.math.BigInteger.valueOf(1)); // Convert BigInteger number back to an Array digits = num.toString().chars().map(c -> c - '0').toArray(); return digits; } As an example, let's run this method against an int[] Array of 100 elements. That would be an integer number consisting of 100 digits. Now that's a large number: /* Auto-create an int[] array containing 100 elements of random digits 0 to 9 (the first digit of the Array will never be a 0). */ int[] array = new int[100]; for (int i = 0; i < 100; i++) { int n = new java.util.Random().nextInt(9); // Make sure the first digit isn't a 0. if (i == 0 && n == 0) { i--; continue; } array[i] = new java.util.Random().nextInt(9); } System.out.println("Original: -> " + Arrays.toString(array)); /* Cycle the plusOne() method 12 times and display the array within each cycle... */ for (int i = 0; i < 12; i++) { array = plusOne(array); // Display The array: System.out.println("Plus One: -> " + Arrays.toString(array)); } The Console Window should display something like this. You will need to scroll to the end to see the incrementing (plus one): Original: -> [7, 8, 8, 3, 7, 3, 2, 1, 4, 6, 8, 8, 0, 7, 5, 8, 1, 7, 7, 0, 2, 2, 3, 2, 7, 2, 2, 2, 3, 4, 6, 7, 4, 6, 1, 4, 2, 4, 3, 1, 0, 4, 2, 8, 3, 4, 3, 8, 3, 6, 2, 5, 6, 6, 3, 5, 1, 3, 0, 7, 0, 0, 8, 7, 0, 0, 2, 4, 8, 5, 0, 6, 0, 2, 3, 5, 0, 1, 3, 3, 4, 1, 2, 8, 8, 1, 8, 3, 0, 5, 8, 8, 2, 2, 6, 6, 3, 5, 2, 6] Plus One: -> [7, 8, 8, 3, 7, 3, 2, 1, 4, 6, 8, 8, 0, 7, 5, 8, 1, 7, 7, 0, 2, 2, 3, 2, 7, 2, 2, 2, 3, 4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6, 7, 4, 6, 1, 4, 2, 4, 3, 1, 0, 4, 2, 8, 3, 4, 3, 8, 3, 6, 2, 5, 6, 6, 3, 5, 1, 3, 0, 7, 0, 0, 8, 7, 0, 0, 2, 4, 8, 5, 0, 6, 0, 2, 3, 5, 0, 1, 3, 3, 4, 1, 2, 8, 8, 1, 8, 3, 0, 5, 8, 8, 2, 2, 6, 6, 3, 5, 3, 7] Plus One: -> [7, 8, 8, 3, 7, 3, 2, 1, 4, 6, 8, 8, 0, 7, 5, 8, 1, 7, 7, 0, 2, 2, 3, 2, 7, 2, 2, 2, 3, 4, 6, 7, 4, 6, 1, 4, 2, 4, 3, 1, 0, 4, 2, 8, 3, 4, 3, 8, 3, 6, 2, 5, 6, 6, 3, 5, 1, 3, 0, 7, 0, 0, 8, 7, 0, 0, 2, 4, 8, 5, 0, 6, 0, 2, 3, 5, 0, 1, 3, 3, 4, 1, 2, 8, 8, 1, 8, 3, 0, 5, 8, 8, 2, 2, 6, 6, 3, 5, 3, 8]
This is pretty straight forward solution. Just what you do in the school: increment right to left with keeping carry for the next digit. class Solution { public int[] plusOne(int[] digits) { boolean carry = true; for (int i = digits.length - 1; carry && i >= 0; i--) { carry = digits[i] == 9; digits[i] = carry ? 0 : digits[i] + 1; } if (carry) { int[] tmp = new int[digits.length + 1]; tmp[0] = 1; System.arraycopy(digits, 0, tmp, 1, digits.length); digits = tmp; } return digits; } }
Second class not resetting when testing from another class
I have a class ("TestProject") that is supposed to print the output of another class to the console, each time using a different input text file (e.g. "input01.txt", "input02.txt"). import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; public class TestProject { public static void main(String[] args) throws IOException { for(int inputNumber = 2; inputNumber <= 7; inputNumber++) { String[] arguments = new String[] {"input" + String.format("%02d", inputNumber) + ".txt", "1"}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream newPS = new PrintStream(baos); PrintStream oldPS = System.out; System.setOut(newPS); Project.main(arguments); System.out.flush(); System.setOut(oldPS); newPS.close(); System.out.println(baos.toString()); } } } This works correctly for the first input file, as seen below: arguments: "input02.txt" 0 1, 3, 80.5, 20, 60, 0, Stone, 0, 0 2, 3, 80.5, 20, 60, 0, Flame, 2, 2 1, 4, 80.0, 20, 60, 0, Stone, 0, 1 2, 4, 80.0, 20, 60, 0, Flame, 2, 2 1, 5, 79.5, 20, 60, 0, Stone, 0, 2 2, 5, 79.5, 20, 60, 0, Flame, 2, 2 1, 6, 79.0, 20, 60, 0, Stone, 1, 1 2, 6, 79.0, 20, 60, 0, Flame, 2, 2 But after this, every subsequent test prints only the final output of the first test: arguments: "input03.txt" 0 1, 6, 79.0, 20, 60, 0, Stone, 1, 1 2, 6, 79.0, 20, 60, 0, Flame, 2, 2 arguments: "input04.txt" 0 1, 6, 79.0, 20, 60, 0, Stone, 1, 1 2, 6, 79.0, 20, 60, 0, Flame, 2, 2 arguments: "input05.txt" 0 1, 6, 79.0, 20, 60, 0, Stone, 1, 1 2, 6, 79.0, 20, 60, 0, Flame, 2, 2 arguments: "input06.txt" 0 1, 6, 79.0, 20, 60, 0, Stone, 1, 1 2, 6, 79.0, 20, 60, 0, Flame, 2, 2 arguments: "input07.txt" 0 1, 6, 79.0, 20, 60, 0, Stone, 1, 1 2, 6, 79.0, 20, 60, 0, Flame, 2, 2 I thought that this might have something to do with calling the main() method of another class multiple times, but nothing online seems to suggest that this is an issue. When running the main program separately, the output works fine for all input files. This leads me to think that the problem exists in this short excerpt. Thanks in advance, to all.
How to delete last element in array and put new in front?
I have a question concerning Java. I started up new to Java and my google search brought many results but non was the final help. I created a class to track historical information. I have different values for different days and need to update them un a regular basis. I want to keep track of the last 30 days and created an array with 30 elements. When I call my 'shift' function I want to drop the last n elements and put zeros in front. Here is a minial example for 5 days: public class Testclass { private int[] histInfo; public Element() { this.histInfo = new int[5]; } public void shift_histInfo(long m) { //do magic } } What I want shift to do is INPUT: histInfo = [50,21,1,45,901] OPERATION: shift_histInfo(2); RESULT: histInfo = [0,0,50,21,1] I am thankfull for every kind of help you can support as well for thought-provoking impulses if you think that there is a way more elegant or efficient way. Best :-)
Unless there are very tight performance constraints using the standard Collection classes will get the job done. Have a look at java.util.LinkedList. As a programming exercise you might consider creating a ring buffer. The idea being to avoid copying the array on every insertion. Keep a oldestIndex value. When writing simply replace item[oldestIndex] and increment oldestIndex. To iterate you start at oldestIndex and use an increment method to deal with wrapping round to the start of the array. int nextIndex(int current) { return (current + 1) % arrayLength; } Writing a nice encapsulating class to hide all this would be a good exercise.
You can try this : public static void shift_histInfo(long m) { int[] myIntArray = {50,21,1,45,901}; int[] myIntArray2 = {50,21,1,45,901}; for (int j=0 ;j< myIntArray.length ; j++){ int temp = (int) (j+m); if (temp >= myIntArray.length){ temp = temp - myIntArray.length; myIntArray2[temp] = 0; } else { myIntArray2[temp] = myIntArray[j]; } } for (int j=0 ;j< myIntArray2.length ; j++){ System.out.println(myIntArray2[j]); } } Output : when shift_histInfo(2) , [0,0,50,21,1]
int[] array={1,2,3,4,5,6}; int removelength=2; int e=1; while(e<=removelength) { for(int i=1;i<array.length;i++) array[array.length-i]=array[array.length-i-1]; e++; } for(int i=0;i<removelength;i++) { array[i]=0; } for(int g:array) { System.out.print(g); }
For constraints that you wanted, although I did initialise the data in the same method instead of Element(). I don't know why the parameter is of type long so I left it and made an int local variable. All it does is copy the index value over to the new array starting at m then increments/iterates until the end of the array. You can also make the method return type int[] and then simply return changedInfo array. Instead of histInfo = changedInfo.clone(); private int[] histInfo; public void shift_histInfo(long m) { int n = (int) m; this.histInfo = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15}; int length = this.histInfo.length; int[] changedInfo = new int[length]; if (length - n >= 0) System.arraycopy(histInfo, 0, changedInfo, n + 0, length - n); //Edit: shortened to one line. histInfo = changedInfo.clone(); System.out.println("Remove: " + n + " - " + Arrays.toString(changedInfo) + "\n"); } public static void main(String[] args) { Main main = new Main(); main.shift_histInfo(0); main.shift_histInfo(30); main.shift_histInfo(1); main.shift_histInfo(15); main.shift_histInfo(29); } println: Remove: 0 - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] Remove: 30 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Remove: 1 - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] Remove: 15 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] Remove: 29 - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
QuickSort Program Not Outputting Right
I am attempting to make a QuickSort program and while I feel like it should be outputting as desired, it is not. I feel the problems lies in how I have constructed my loops but that may not be the case. As you can see, the first test with the runner prints out as I want and everything eventually gets sorted right. Any help would be greatly appreciated. My main program: import static java.lang.System.*; import java.util.Arrays; //use Arrays.toString() to help print out the array public class QuickSort { private static int passCount; public static void quickSort(Comparable[] list) { passCount=0; quickSort(list, 0, list.length-1); } private static void quickSort(Comparable[] list, int low, int high) { if(low >= high) return; int a = partition(list, low, high); quickSort(list, low, a-1); quickSort(list, a+1, high); } private static int partition(Comparable[] list, int low, int high) { int x = low + 1; int y = high; while(x <= y) { if(list[x].compareTo(list[low]) <= 0) {x++;} else if(list[y].compareTo(list[low]) > 0) {y--;} else if(y < x) {break;} else exchange(list, x, y); } exchange(list, low, y); out.println("pass " + passCount++ + " " + Arrays.toString(list) + "\n"); return y; } private static void exchange(Object[] list, int x, int y) { Object temporary = list[x]; list[x] = list[y]; list[y] = temporary; } } My runner: public class QuickSortRunner { public static void main(String args[]) { QuickSort.quickSort(new Comparable[]{9,5,3,2}); System.out.println("\n"); QuickSort.quickSort(new Comparable[]{19,52,3,2,7,21}); System.out.println("\n"); QuickSort.quickSort(new Comparable[]{68,66,11,2,42,31}); System.out.println("\n"); } } My output: pass 0 [2, 5, 3, 9] pass 1 [2, 5, 3, 9] pass 2 [2, 3, 5, 9] pass 0 [2, 7, 3, 19, 52, 21] pass 1 [2, 7, 3, 19, 52, 21] pass 2 [2, 3, 7, 19, 52, 21] pass 3 [2, 3, 7, 19, 21, 52] pass 0 [31, 66, 11, 2, 42, 68] pass 1 [11, 2, 31, 66, 42, 68] pass 2 [2, 11, 31, 66, 42, 68] pass 3 [2, 11, 31, 42, 66, 68] Desired output: pass 0 [2, 5, 3, 9] pass 1 [2, 5, 3, 9] pass 2 [2, 3, 5, 9] pass 0 [7, 2, 3, 52, 19, 21] pass 1 [3, 2, 7, 52, 19, 21] pass 2 [2, 3, 7, 52, 19, 21] pass 3 [2, 3, 7, 21, 19, 52] pass 4 [2, 3, 7, 19, 21, 52] pass 0 [31, 66, 11, 2, 42, 68] pass 1 [2, 11, 66, 31, 42, 68] pass 2 [2, 11, 66, 31, 42, 68] pass 3 [2, 11, 42, 31, 66, 68] pass 4 [2, 11, 31, 42, 66, 68]
The x++ and y-- to skip exchanges need to be in while loops so that exchange happens only when it is called for.
Java array to multi dimensional
Is it possible to take an array of say 100 chars and turn it into a 2d array of 10*10?
Here you go char[] chars = ("01234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789") .toCharArray(); char[][] char2D = new char[10][10]; for (int i = 0; i < 100; i++) char2D[i / 10][i % 10] = chars[i]; Now the this code... System.out.println(Arrays.deepToString(char2D).replaceAll("],","],\n")); ...prints the following [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
Iterate throughout your list of 100 chars and divide it amongst the 10*10, Modulus (%) will probably be very useful. You could use 2 nested for loops to assign the chars of the array to the appropriate element.