This question already has answers here:
How to reverse a number more efficiently with Java
(4 answers)
Closed 1 year ago.
public class aa {
public static void main(String[] args) {
int number = 521;
String temp1 = "" + number;
int result = 0;
int[] temp2 = new int[temp1.length()];
for(int i=0; i<temp1.length(); i++){
int len = temp1.length();
temp2[i] = temp1.charAt(len-i-1);
System.out.println(temp2[i]);
System.out.println(temp1.charAt(len-i-1));
}
}
}
This program should make 521 to 125 (reverse). But when I run this program, the result is
49
1
50
2
53
5
I think that string value is right, but when I add that string value to array, it goes wrong way. Can some one tell me what is wrong?
As I was saying in the comments, temp2 is the wrong type. You declared it as an array of ints, so println, of course, is treating it as an array of numbers, not of printable characters.
Just change temp2's type to char[]:
public class aa {
public static void main(String[] args) {
int number = 521;
String temp1 = "" + number;
int result = 0;
char[] temp2 = new char[temp1.length()];
for(int i=0; i<temp1.length(); i++){
int len = temp1.length();
temp2[i] = temp1.charAt(len-i-1);
System.out.println(temp2[i]);
System.out.println(temp1.charAt(len-i-1));
}
// print the whole reversed number on one line
for(char c : temp2) {
System.out.print(c);
}
System.out.println();
}
}
Output
1
1
2
2
5
5
125
Of course this is not the optimal solution, just a way to fix the code you wrote so that it works. See Alex Rudenko's comment for a link with better solutions to the problem of reversing the digits of a number.
As temp2 is an array of int values, the following assignment needs to be fixed:
temp2[i] = temp1.charAt(len-i-1);
because it assign an ASCII value of char.
This can be done by subtracting a 0 or by using Character::getNumericValue
temp2[i] = temp1.charAt(len-i-1) - '0';
// or
temp2[i] = Character.getNumericValue(temp1.charAt(len-i-1));
A non-negative integer number may be reversed without using any String conversion:
The "length" of temp2 array is defined by Math.log10
Each digit is calculated with modulo operator % and dividing the input while it is greater than 0
public static void main(String[] args) {
int number = 521;
int len = number < 2 ? 1 : (int) Math.ceil(Math.log10(number));
int[] temp2 = new int[len];
for (int i = 0, n = number; n > 0; n /= 10, i++) {
temp2[i] = n % 10;
System.out.println(temp2[i]);
}
for (int i : temp2) {
System.out.print(i);
}
System.out.println();
}
Output
1
2
5
125
You question is not very clear about if you are asking for opinion. But a query that "when I add that string value to array, it goes wrong way."
So , String is a reference type, while your array is of int type. You need to parse the value from String to int
Integer.parseInt(String)
Related
I'm trying to sort the digits of a given integer by turning the integer to a String and creating an array by the size of that String length.
I'm using the modulu option to separate the digits and in the end I'm reversing it by multiplying by 10.
The problem that it's going out of bound each time and I don't know how to make the size of the array to work good for me.
Here are the code :
String s = String.valueOf(num);
int[] arr = new int[s.length()+1];
while(num != 0) {
arr[(int) num % 10]++;
num = num / 10;
}
long result = 0;
for(int i = 0 ; i < arr.length - 1 ; i++){
for(int j = 0 ; j < arr[i] ; j++) {
result = result * 10;
result = result + i;
}
}
return result;
There seems to be a lot of overkill solving this, as in a lot of code, so here is my take on it.
static int sortDigits(int num) {
char[] arr = Integer.toString(num).toCharArray();
Arrays.sort(arr);
return Integer.parseInt(new String(arr));
}
Test
System.out.println(sortDigits(4201514)); // 112445
You can of course do the same for the long and BigInteger versions:
static long sortDigits(long num) {
char[] arr = Long.toString(num).toCharArray();
Arrays.sort(arr);
return Long.parseLong(new String(arr));
}
static BigInteger sortDigits(BigInteger num) {
char[] arr = num.toString().toCharArray();
Arrays.sort(arr);
return new BigInteger(new String(arr));
}
If I understand your question correctly, when given an integer, you want to "sort" each digit, ignoring 0's.
To do so, so you can first convert it to a string:
String value = String.valueOf(num);
Since you have a string, you can use the split() function to split each 'number' like so:
String[] numbers = value.split("");
Then, you can find the indexes of 0's (and store it somewhere).
ArrayList<Integer> indexes = new ArrayList<>();
for (int i = 0; i < numbers.length; i++) {
if (numbers[i].equals("0")) {
indexes.add(i);
}
}
Then, you can sort the array of strings (numbers) using the sort() function:
Arrays.sort(numbers);
Then, you can remove the 0's like this (by creating a new ArrayList):
ArrayList<String> copy = new ArrayList<>();
for (String s : numbers) {
if (!s.equals("0")) {
copy.add(s);
}
}
(Here, you may use ArrayUtils if you already imported the library.)
Then, concatenate each element to make one entire string with join():
String result = String.join("", copy);
Finally, using the indexes, insert 0's to where they were located at initially:
for (int i : indexes) {
result = result.substring(0, i) + "0" + result.substring(i);
}
result would be what you want.
Note: This might not be the most sufficient way to do it, so you can modify it anywhere you want.
Based on your code I made a few modification
size of array should be 10 since in a number only 0 to 9 digits are possible
use this array to make a frequency array of occurrence of each digit
iterate over the array from 1 to 9 and make a sorted number
public static long sortInt(long num) {
int[] arr = new int[10];
while(num != 0) {
arr[(int) num % 10] ++;
num /= 10;
}
long result = 0;
for(int i = 1 ; i < arr.length ; i++)
while(arr[i]-- != 0)
result = result * 10 + i;
return result;
}
I want to find all possible binary permutations with a given number of ones in Java:
x is the desired number of ones in each sequence
n is the desired length of each sequence
For an example:
x=2, n=4
Output: 1100, 0011, 1010, 1001, 0101, 0110
I'm searching for an elegant and fast way to do this. Can you help me?
I've tested eboix solution in Print list of binary permutations but it is unfortunately too slow because the algorithm in this example is searching for all 2^n binary permutations.
I want to find sequences with a length of 50 or 100.
First of all, you're missing 0110 as an output case.
It's fairly intuitive that there are n choose x possibilities. You're finding all valid arrangements of x identical items among n total slots. So you can find the total number of sequences in O(1).
As a hint, try simply finding all permutations of the bitstring consisting of x ones followed n - x zeros.
To specifically address the problem, try creating a recursive algorithm that decides at every ith iteration to either include 1 or 0. If 1 is included, you need to decrement the count of 1's available for the rest of the string.
Actually, there may be an elegant way, but no fast way to do this. The number of string permutations is given by the binomial coefficient (see https://en.wikipedia.org/wiki/Binomial_coefficient). For example, x=10, n= 50 gives over 10 million different strings.
Here is just a basic version that will generate your desired output. Please work on it to make it more accurate/efficient -
This will not generate all the combinations, but you will get the idea of how to do it. Off course, for all the possible combinations generated by this, you will have to generate all the other possible combinations.
public class Test {
static int iter = 0;
public static void main(String args[]){
int n = 50;
int x = 5;
byte[] perms = new byte[n];
for(int i=0; i<x; i++){
perms[i] = 1;
}
print(perms);
for(int j=x-1; j>=0; j--){
for(int i=1; i<(n/2-j); i++){
iter++;
swap(perms, j, i);
}
}
}
public static void swap(byte[] perms, int pos, int by){
byte val = perms[pos+by];
perms[pos+by] = perms[pos];
perms[pos] = val;
print(perms);
val = perms[pos+by];
perms[pos+by] = perms[pos];
perms[pos] = val;
}
public static void print(byte[] perms){
System.out.println("iter = "+iter);
for(int i=0; i<perms.length; i++){
System.out.print(perms[i]);
}
System.out.println();
for(int i=perms.length-1; i>=0; i--){
System.out.print(perms[i]);
}
System.out.println();
}
}
Another inspiration for you. A dirty version which works. It allocates extra array space (you should adjust size) and uses String Set at the end to remove duplicates.
public static void main(String[] args) {
int x = 2;
int n = 4;
Set<BigInteger> result = new LinkedHashSet<>();
for (int j = x; j > 0; j--) {
Set<BigInteger> a = new LinkedHashSet<>();
for (int i = 0; i < n - j + 1; i++) {
if (j == x) {
a.add(BigInteger.ZERO.flipBit(i));
} else {
for (BigInteger num : result) {
if (num != null && !num.testBit(i) && (i >= (n - j) || num.getLowestSetBit() >= i-1))
a.add(num.setBit(i));
}
}
}
result = a;
}
String zeros = new String(new char[n]).replace("\0", "0");
for (BigInteger i : result) {
String binary = i.toString(2);
System.out.println(zeros.substring(0, n - binary.length()) + binary);
}
}
EDIT: changed the primitives version to use BigInteger instead to support larger n,x values.
I would like to read a file which is in the form of a matrix, so i tried reading a file put it in String arraylist and then converted to integer array. Now I need a 2D integer array. Can anyone help? Is there any better way to do this.
public class readMat {
private static ArrayList<String> list = new ArrayList<String>();
public static void main (String[] args)
{
// read file and put in arraylist
try
{
Scanner s = new Scanner(new File("link_info_test.txt"));
while (s.hasNext())
{
list.add(s.next());
}
}
catch (Exception e)
{
e.printStackTrace();
}
String[] stockArr = new String[list.size()];
stockArr = list.toArray(stockArr);
int[] sum= Convert(stockArr);
}
// convert string arraylist to integer 1 dimensional array private static int[] Convert(String[] stockArr)
{
if (list != null)
{
int intarray[] = new int[stockArr.length];
for (int i = 0; i < stockArr.length; i++)
{
intarray[i] = Integer.parseInt(stockArr[i]);
}
return intarray;
}
return null;
}
}
Let's say you have temperature data for each day of the week for 10 weeks (that is 70 pieces of data). You want to convert it to a 2d array with rows representing weeks and columns representing days. Here you go:
int temp[70] = {45, 43, 54, ........}
int twoD[30][7]
for(int i=0; i < 70; i++) {
twoD[i / 7][i % 7] = temp[i]
}
That's it.
After the line
int[] sum= Convert(stockArr);
you have your entire file in a 1D array of integers. At this point, you have to determine the width and height of the 2D array.
Let's say you want the 2D array to have 3 rows and 4 columns as an example. Do this:
int[][] int_table = new int[3][4];
for(int j = 0; j < 3; j++)
{
for(int i = 0; i < 4; i++)
{
int_table[j][i] = sum[j * 4 + i];
}
}
The equation I'm using within sum's index is a conversion function that goes from 1D to 2D coordinates. Starting at both j and i being equal to 0, sum[j * 4 + i] = sum[0 * 4 + 0] = sum[0]. The variable i would increment by one at the next step, and we would have sum[0 * 4 + 1] = sum[1]. At the end of the row, i would reset to 0 and j would increment by 1. At that point, we would have sum[1 * 4 + 0] = sum[4], or sum's fifth element. This makes sense if you consider the first four elements as those of the first row. now that we're on a new row, we can fill it with the next four. The "four" that I've been mentioning is the width of the row that we defined earlier while declaring the 2D array.
Keep in mind that the 2D array's width and height can't multiply together to be larger than the total number of integers in the 1D array. You'll get an IndexOutOfBoundsException if you try to read beyond that size.
Assuming that each entry of your String array consists of some integers, separated by some delimiter (comma, dot, hyphen, etc), then you can use the String.split() method. For instance, if your delimiter is a comma, then you would do something like this:
String Integer1;
String Integer2;
String[] TotalString;
TotalString = stockArr[i].Split(",");
Integer1 = TotalString[0];
Integer2 = TotalString[1];
Then just parse the Strings into integers and put them into your array.
If i understood, your question correctly you want to convert 1D array to 2D array ... You can use following method
public static int[][] convertArrayTo2DArray(final int[] _1darray) {
int[][] _2dArray = null;
int size = _1darray.length / 2;
if (_1darray.length % 2 == 0) {
_2dArray = new int[2][size];
} else {
_2dArray = new int[3][size];
}
int index = 0;
outter: for (int i = 0; i < _2dArray.length; i++) {
for (int j = 0; j < _2dArray[i].length; j++) {
if (index == _1darray.length) {
break outter;
}
_2dArray[i][j] = _1darray[index];
index++;
}
}
return _2dArray;
}
This question already has answers here:
Maximum number that can be formed from the given digits
(2 answers)
Closed 7 years ago.
I have a number which I need to re-arrange to find the largest number. As an example input number is 355 so for this number I need to find the largest number which can be formed by re-arranging the digits. So for 355, various combination can be possible after re-arranging -
355, 535 and 553
So here 553 is the largest number and that's what I need to return. Basically given an input, I need to find the largest number which can be formed by re-arranging the numbers.
How should I go ahead and solve this problem?
So far I am able to do shuffle the numbers like this:
public static void main(String[] args) {
//generate random number
int number = 355;
//put each digit in an element of a list
List<Character> numberList = new ArrayList<Character>();
for (char c : String.valueOf(number).toCharArray()) {
numberList.add(c);
}
//shuffle
Collections.shuffle(numberList);
//output
String shuffledNumber = "";
for (Character c : numberList) {
shuffledNumber += c;
}
System.out.println(shuffledNumber);
}
But I am confuse how can I find the largest number given an input after rearranging the numbers.
If you need to rearrange the numbers so that, if we read it from left to write, it should be largest number among all the arrangements,
then it's simple, you just need to sort the number in descending order.
Try this code :
public static void main(String args[]) {
//generate random number
int number = 355;
String numStr = number + "";
char[] numCharArr = numStr.toCharArray();
int[] numArr = new int[numStr.length()];
for(int i = 0 ; i < numCharArr.length ; i ++) {
numArr[i] = Integer.parseInt(numCharArr[i] + "");
}
// Sort in descending order
for(int i = 0 ; i < numArr.length ; i ++) {
for(int j = 0 ; j < i ; j ++) {
if(numArr[i] > numArr[j]) {
// swap
int temp = numArr[i];
numArr[i] = numArr[j];
numArr[j] = temp;
}
}
}
String largestNumber = "";
for(int i : numArr) {
largestNumber += i;
}
System.out.println("The largest number is : " + largestNumber);
}
Unless you actually need to create all the combinations, I wouldn't bother.
You can actually do it using arithmetic, but in this case it's probably easier in terms of strings
naive algorithm:
source number = number.toString()
target number = ""
While source number is not empty
d = remove biggest number from source number
target number += d
You can then convert target number back to an int if required.
Another approach would be count the number of 9s and append that many 9s to the result. Repeat for 8s, then 7s, then 6s...
I'm not allowed to use methods from any class except String and IO Class
So my code snippet is:
String line = reader.readLine();
while (line != null) {
String[] elements = line.split(",");
// Array could be too big if there are multiple occurances of
// the same number
// Array length + 1 because I can't use the 0 and with a input line of
// 1,2,3 for example would be the length 3 but I would have the
// numbers 0,1,2 in the Array as my index.
String[][] placeholderMatrix = new String[elements.length+1][elements.length+1];
for(int i = 0; i < elements.length-1; i++){
placeholderMatrix[(int)elements[i]][(int)elements[i+1]] = 1;
}
line = reader.readLine();
}
In the File I'm getting are only numbers like that: 1,2,3,4,5,8,7,4
So in my splitted String Array are only Numbers but now if I want to use them as my index for my Matrix(placeholderMatrix)
My problem is in my for loop where I want to use them as my Index I can't use them because it is a String Array. Normally I would use Integer.parseInt but I'm not allowed to :/
Any ideas on how I can implement them as my Index? and any Idea how I can get the perfect length of my Matrix? Because If I get the following numbers: 1,2,2,2,3 My Matrix should only have the numbers:
0 1 2 3
1
2
3
But if I'm using elements.length+1 for the length of my Matrix I would get the numbers 0 1 2 3 4 5
Hope you could understand my problem. Sorry for my bad english and Thanks in advance.
Edit: SO i got another problem with that. If I implement the method(parseInt) of Dici and am using it in the line "placeholderMatrix[parse(elements[i])][parse(elements[i+1])] = 1;" I'm getting the error ArrayOutOfBounce because my defined Array is just the length of my splitted String Array elements. But if I define it with Integer.MAX_VALUE as my length I get a memory error because it is too big. Any ideas?
Edit2: My Task:
I have to take a row of Numbers seperated by ",". (I will split it with the String split method to get only the numbers) Now I have to create a Matrix(2 dimensional Array) and look for the number at the index i of my new String Array and the number at the index i + 1 and have to take the first Number as my column and th second as my row (or vice versa) and implement at that point a 1. Now are my Numbers I will get from 1 to Integer.MAX_VALUE so I would have to create such a big Matrix but this isn't possible because I get the MemoryError.
Error: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at Test.main(Test.java:29)
To understand what I have to do: http://de.wikipedia.org/wiki/Adjazenzmatrix the image at the right but for numbers from to Integer.MAX_VALUE so my 2D Array has to be defined with the length of Integer.MAX_VALUE?
Edit:
So Dici asked for an example:
My Sequence could be: 1,2,5,4
So my Matrix should be:
Hope this is what you wanted Dici
But the numbers I can get from the sequence are 1 to Integer.MAX_VALUE
For converting strings to integers, you can simply implement your own integer parser, it is not complicated. You can start with this and improve it if needed.
public int parseInt(String s) {
int n = 0;
int pow = 1;
for (int i=s.length() - 1 ; i>=0 ; i--) {
String si = String.valueOf(s.charAt(i);
if (si.matches("[0-9]")) {
n += pow*(s.charAt(i) - '0');
pow *= 10;
} else if (si.matches("+|-") && i == 0)
n *= s.charAt(i) == '+' ? 1 : -1;
else
throw new NumberFormatException();
}
return n;
}
Then, I'll handle the second part of your problem. If Integer.MAX_VALuE is one of your input values, you cannot possibly allocate an Integer.MAX_VALUE x Integer.MAX_VALUE matrix. What you need to do is assign contiguous ids to your input values and record the ids in a map so that you can access easily the index of the matrix corresponding to one node value. Here is an example to get you to understand :
public void someMethod() {
int id = 0;
Map<Integer,Integer> idMap = new HashMap<>();
String[] split = reader.readLine().split(",");
int [] nodes = new int[split.length];
for (int i=0 ; i<nodes.length ; i++) {
nodes[i] = parseInt(split[i]);
if (!idMap.containsKey(nodes[i]))
idMap.put(nodes[i],id++);
}
// the map is now constructed, it should probably be stored in an attribute
int[][] placeholderMatrix = new int[nodes.length][nodes.length];
for(int i = 0; i < nodes.length; i++){
if (i > 0) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i-1])] = 1;
if (i < nodes.length-1) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i+1])] = 1;
}
}
There are other ways to do it, let me know if this solution is ok
You could do something like:
String keyword = "1,2,3,4,5,8,7,4";//input line from file
String replacedKeyword = keyword.replaceAll("[^\\d]", "");//except numbers replace all. Assuming one digit numbers only.
String[][] placeholderMatrix = new String[replacedKeyword.length()+1][replacedKeyword.length()+1];
char keys[] = replacedKeyword.toCharArray();
for (int i = 0; i<keys.length - 1; i++) {
placeholderMatrix[keys[i] - '0'][keys[i + 1] -'0'] = "1";
}
I couldn't really understand what you want exactly. but, if that going to help a simple method to convert String number to int:
int toInt(String number) {
int num = 0;
for (int i=0; i<number.length(); i++) {
num = num*10 + (number.charAt(i)-'0');
}
return num;
}