Way to combine integer array to a single integer variable? [duplicate] - java

This question already has answers here:
How to concatenate int values in java?
(22 answers)
Closed 7 years ago.
After finding the individual digits of a number by remainder procedure, the numbers are saved in an array.
What I want now is to take the individual elements of this array and make a single integer value of it.
eg.
int a = 4400
digits saved in array by using recursion (4400/10) :
let array be arr[]
arr[0]=0;
arr[1]=0;
arr[2]=4;
arr[3]=4;
final value:
int b= 4400 (by combining elements of array)
So I want to know if there is any way to combine the array elements to a single integer value ?

Just multiply and add the digits:
int result = 1000 * arr[3] + 100 * arr[2] + 10 * arr[1] + arr[0];
Or, if you need it to work for any length of array (up to the number of digits in Integer.MAX_VALUE):
int result = 0;
for (int i = arr.length - 1; i >= 0; --i) {
result = 10*result + arr[i];
}

I would use a stringbuilder.
StringBuilder builder = new StringBuilder();
builder.append(arr[3]);
builder.append(arr[2]);
builder.append(arr[1]);
builder.append(arr[0]);
System.out.println("Combined value is: " + Integer.parseInt(builder.toString());

How about using simple loop and multiplication (assuming you know basic math)
int b = 0;
int z = 10;
for (int i = 1; i <= arr.length; i++) {
b = (int) (b + (arr[i - 1] * Math.pow((double) z, i - 1)));
}

Related

Java/ Sum of any two values in an array of numbers

I have a task:
Write code that will have an array of valuesTable and givenNumber from integer. The method will list the number of such combinations that the sum of any two
elements in the array equal to the number stored in givenNumber.
Should I make another array to storage sum of any two elements?
What kind of method use to get the sum of any two elements in the array?
How list the number of combinations?
I would be very grateful for your help, this is my first steps in Java :)
public class NumberOfCombinations {
public static void main(String[] args) {
int[] valuesTable = {1, 2, 3, 4, 5};
int givenNumber = 3;
int index=0;
int sum = 0;
int n = valuesTable.length;
for (index = 0; index < n; index++)
sum = valuesTable[index] + valuesTable[++index];
}
}
Should I make another array to storage sum of any two elements?
If it is required to provide only the number of the pairs equal to the given number, array is not required, simple if statement allows to check the condition and increment the counter (and print the pair if needed):
if (a[i] + a[j] == x) {
pairs++;
System.out.println("Found a pair: " + a[i] + " + " + a[j]);
}
What kind of method use to get the sum of any two elements in the array?
Two nested loops:
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
//...
}
}
How list the number of combinations?
The total number of possible pairs is calculated by the formula of decreasing progression from n - 1 to 1: S = n * (n - 1) / 2, so for n = 5 it is 5 * 4 / 2 = 10.
The number of matching pairs is simply counted in the innermost loop.

Create histogram of array with doubles

I have an array including doubles:
double[] myArray = {1.23455, 1.23456, 2.45673, 6.45678, 8.12938}
The numbers in the array and the number of elements in array will vary. How can I create a histogram out of this array? I'm trying to create ranges by doing something like this:
double sizeOfRange = (max-min)/(numberOfRanges-1);
Where max and min are max and min values in myArray, but other than that I am completely lost regarding how to do this. I'm very new to java, hope the question is asked correctly.
I'm not sure this is what you want, but it certainly can help you if you are starter:
Double[] myArray = {1.23455, 1.23456, 2.45673, 6.45678, 8.56938, 3.65645, 5.65478, 2.54773, 9.63345};
int nRanges = 3;
int[] buckets = new int[nRanges];
double max = Collections.max(Arrays.asList(myArray));
double min = Collections.min(Arrays.asList(myArray));
double sizeOfRange = (max-min)/(nRanges - 1);
for (double elem : myArray){
for (int i = 0; i < nRanges; i++){
if ((elem >= sizeOfRange * i) && (elem < sizeOfRange * (i + 1)))
buckets[i]++;
}
}
for (int i = 0; i < nRanges; i++){
System.out.println(sizeOfRange * i + " - " + sizeOfRange * (i + 1) + ": " + buckets[i]);
}
Collections class provides a lot of useful method, just like max and min. Then the core of this code is from line 8 to 13: inside that for I am incrementing the frequency of the range in which the correspondent double value can be placed.

updating the array dynamically [duplicate]

This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 8 years ago.
I am beginner to java coding, I am facing some complexity in updating the array.
My problem is I have an array named s1[] which consists of 10 elements from that I have to choose 1st 3 elements and I have to store in one array i.e. max1[] array and in next array I have to choose randomly 3 elements from the same array i.e. s1[] and store it in max6[] and I need to do comparison between the two arrays i.e. max1[] and max6[] so that the matching values will be stored.
My code looks like this (here f1 = 3)
for (i1 = 0; i1 < f1; i1++) {
max1[i1] = s1[i1];
System.out.println("1st tree random leaf nodes of phy m/c 1 at tree 1 : " + max1[i1]);
System.out.println(" \n ");
max6[i1] = s1[(int) (Math.random() * f1)];
System.out.println(" random leaf nodes of phy m/c 1 at tree 2: " + max6[i1]);
System.out.println(" \n ");
}
for (int l1 = 0; l1 < f1; l1++) {
for (int k1 = 0; k1 < f1; k1++) {
if (max1[l1] == max6[k1]) {
c1[l1] = max1[l1];
k1++;
System.out.println("the value after crossover is:--------->" + c1[l1]);
break;
}
}
}
now what I want is that I have to repeat the loop for some iterations so that in the next iteration the values of the max1 array in 1st iteration shouldn't be repeated means I have to permanently remove the elements from s1 array until s1 array contains zero elements in it
I have two suggestions for you, it's up to you which you prefer.
Firstly I would suggest converting the array to a list and removing the necessary elements from the list then converting back to the array. Code follows :
List<Double> list = new ArrayList<Double>(Arrays.asList(s1));
list.remove(i1);
s1 = list.toArray(new Double[0]);
Secondly you can shift the specific element of the array to the back and just iterate one position less than the length. This will require you adding an extra int variable to either record the number of elements in the array or to record the amount of deleted elements, the former being the better idea. Code follows :
double temp;
for(int i = 0; i < test.length - 1; i++){
temp = s1[i];
s1[i] = s1[i + 1];
s1[i + 1] = temp;
}
nrE = nrE - 1;
This will require you to have an int nrE with value of the length of the array(here 10) before your first for loop.
Both of these should be implemented inside the for loop at the end of the iteration.
From what I've seen my first suggestion is used most.
Note : I may misunderstand what you are trying to achieve, but I believe your code for getting the 3 random elements is faulty. If f1=3 and you take element at the position Math.random() * f1 you will always get an element in the range 0 to 3. To fix this you can instead use Math.random() * s1.length

int array to int number in Java

I'm new on this site and, if I'm here it's because I haven't found the answer anywhere on the web and believe me: I've been googling for quite a time but all I could find was how to convert a number to an array not the other way arround.
I'm looking for a simple way or function to convert an int array to an int number. Let me explain for example I have this :
int[] ar = {1, 2, 3};
And I want to have this:
int nbr = 123;
In my head it would look like this (even if I know it's not the right way):
int nbr = ar.toInt(); // I know it's funny
If you have any idea of how I could do that, that'd be awesome.
Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result.
Result: 0
Loop 1: Result * 10 => 0, Result + 1 => 1
Loop 2: Result * 10 => 10, Result + 2 => 12
Loop 3: Result * 10 >= 120, Result + 3 => 123
This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal.
You have to cycle in the array and add the right value.
The right value is the current element in the array multiplied by 10^position.
So: ar[0]*1 + ar[1]*10 + ar[2] *100 + .....
int res=0;
for(int i=0;i<ar.length;i++) {
res=res*10+ar[i];
}
Or
for(int i=0,exp=ar.length-1;i<ar.length;i++,exp--)
res+=ar[i]*Math.pow(10, exp);
First you'll have to convert every number to a string, then concatenate the strings and parse it back into an integer. Here's one implementation:
int arrayToInt(int[] arr)
{
//using a Stringbuilder is much more efficient than just using += on a String.
//if this confuses you, just use a String and write += instead of append.
StringBuilder s = new StringBuilder();
for (int i : arr)
{
s.append(i); //add all the ints to a string
}
return Integer.parseInt(s.toString()); //parse integer out of the string
}
Note that this produce an error if any of the values past the first one in your array as negative, as the minus signs will interfere with the parsing.
This method should work for all positive integers, but if you know that all of the values in the array will only be one digit long (as they are in your example), you can avoid string operations altogether and just use basic math:
int arrayToInt(int[] arr)
{
int result = 0;
//iterate backwards through the array so we start with least significant digits
for (int n = arr.length - 1, i = 1; n >= 0; n --, i *= 10)
{
result += Math.abs(arr[n]) * i;
}
if (arr[0] < 0) //if there's a negative sign in the beginning, flip the sign
{
result = - result;
}
return result;
}
This version won't produce an error if any of the values past the first are negative, but it will produce strange results.
There is no builtin function to do this because the values of an array typically represent distinct numbers, rather than digits in a number.
EDIT:
In response to your comments, try this version to deal with longs:
long arrayToLong(int[] arr)
{
StringBuilder s = new StringBuilder();
for (int i : arr)
{
s.append(i);
}
return Long.parseLong(s.toString());
}
Edit 2:
In response to your second comment:
int[] longToIntArray(long l)
{
String s = String.valueOf(l); //expand number into a string
String token;
int[] result = new int[s.length() / 2];
for (int n = 0; n < s.length()/2; n ++) //loop through and split the string
{
token = s.substring(n*2, (n+2)*2);
result[n] = Integer.parseInt(token); //fill the array with the numbers we parse from the sections
}
return result;
}
yeah you can write the function yourself
int toInt(int[] array) {
int result = 0;
int offset = 1;
for(int i = array.length - 1; i >= 0; i--) {
result += array[i]*offset;
offset *= 10;
}
return result;
}
I think the logic behind it is pretty straight forward. You just run through the array (last element first), and multiply the number with the right power of 10 "to put the number at the right spot". At the end you get the number returned.
int nbr = 0;
for(int i = 0; i < ar.length;i++)
nbr = nbr*10+ar[i];
In the end, you end up with the nbr you want.
For the new array you gave us, try this one. I don't see a way around using some form of String and you are going to have to use a long, not an int.
int [] ar = {2, 15, 14, 10, 15, 21, 18};
long nbr = 0;
double multiplier = 1;
for(int i = ar.length-1; i >=0 ;i--) {
nbr += ar[i] * multiplier;
multiplier = Math.pow(10, String.valueOf(nbr).length());
}
If you really really wanted to avoid String (don't know why), I guess you could use
multiplier = Math.pow(10,(int)(Math.log10(nbr)+1));
which works as long as the last element in the array is not 0.
Use this method, using a long as your input is to large for an int.
long r = 0;
for(int i = 0; i < arr.length; i++)
{
int offset = 10;
if(arr[i] >= 10)
offset = 100;
r = r*offset;
r += arr[i];
}
This checks if the current int is larger than 10 to reset the offset to 100 to get the extra places required. If you include values > 100 you will also need to add extra offset.
Putting this at end of my post due to all the downvotes of Strings...which is a perfectly legitimate answer...OP never asked for the most efficient way to do it just wannted an answer
Loop your array appending to a String each int in the array and then parse the string back to an int
String s = "";
for(int i = 0; i < arr.length; i++)
s += "" + arr[i];
int result = Integer.parseInt(s);
From your comment the number you have is too long for an int, you need to use a long
String s = "";
for(int i = 0; i < arr.length; i++)
s += "" + arr[i];
long result = Long.parseLong(s);
If you can use Java 1.8, stream API makes it very simple:
#Test
public void arrayToNumber() {
int[] array = new int[]{1,2,3,4,5,6};
StringBuilder sb = new StringBuilder();
Arrays.stream(array).forEach(element -> sb.append(element));
assertThat(sb.toString()).isEqualTo("123456");
}
you can do it that way
public static int[] plusOne(int[] digits) {
StringBuilder num= new StringBuilder();
PrimitiveIterator.OfInt primitiveIterator = Arrays.stream(digits)
.iterator();
while (primitiveIterator.hasNext()) {
num.append(primitiveIterator.nextInt());
}
int plusOne=Integer.parseInt(String.valueOf(num))+1;
return Integer.toString(plusOne).chars().map(c -> c-'0').toArray();
}
BE SIMPLE!!!
public static int convertToInteger(int... arr) {
return Integer.parseInt(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining()));
}
this also possible to convert an Integer array to an int array
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i].intValue();
}

Efficient method to find permutations of variable number of arrays containing varibale number of elements [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I find all of the permutations consisting of 1 element from a variable number of arrays of variable length?
Suppose I have n arrays with elements like below
a1 -> e11,e12,e13
a2 -> e21,e22,e23,e24,e25
a3 -> e31,e32
a4 -> e41,e42,e43,e44
...
an -> en1,en2,en3,en4,en5,en6
I want to get all possible permutations with n elements in it from each array above.
For exm.
e11,e21,e31,e41.........,en1
e13,e25,e32,e41.........,en6
and so on...
Suggest me an efficient method and if possible code snippet in Java or C.
You may use following pseudo code:
Function to get next permutation:
function NextPermutation(int[] current)
{
current[0] = current[0] + 1;
int pointer = 0;
while(pointer <= n && current[pointer] == limit[pointer])
{
current[pointer] = 0;
pointer = pointer + 1;
current[pointer] = current[pointer] + 1;
}
}
Pre population code:
int[] limit = new int[n + 2];
int[] current = new int[n + 2];
limit[1] = a1.length;
...
limit[n] = an.length;
while(current[n+1] == 0)
{
Print(current);
NextPermutation(current);
}
current array containt indexes into arrays a1, a2, ... , an.
Since you are interested in all array combinations For loop will be great here
Here is a solution(should be modified for syntaxes though to get it working)
int i = 0
int j=0
int k =0
while(i<arraylength(a1))
{
while (j < arraylength(a2))
{
//and so till an
print a1[i],a2[j];
j++;
}
i++;
}

Categories

Resources