Convert long array to int array in Java - java

I've just begun using java and I can't convert a long array type to int array. Can you give a piece of advice what should I do?
Thank you!
public class Main {
public static void main(String[] args) {
long[] numbers;
numbers = sorting(new long[]{5, 21, 19, 55, 94, 73, 69, 100,});
}
public static long[] sorting(long [] numbers) {
for (long num : numbers) {
long j = 0;
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
j = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = j;
}
}
System.out.println(num + ",");
}
return (numbers);

To convert an long[] to int[], you need to iterate over your long[] array, cast each individual number to int and put it to the int[] array.
// Your result
long[] numbers = sorting(new long[] {5, 21, 19, 55, 94, 73, 69, 100});
// Define a new int array with the same length of your result array
int[] intNumbers = new int[numbers.length];
// Loop through all the result numbers
for(int i = 0; i < numbers.length; i++)
{
// Cast to int and put it to the int array
intNumbers[i] = (int) numbers[i];
}
Or you can also use Java Streams (>= 1.8) for a shorter version:
int[] intArray = Arrays.stream(numbers).mapToInt(i -> (int) i).toArray();

There is a similar question in
convert-an-int-array-to-long-array-using-java-8
You can try this:
long[] longArray = {1, 2, 3};
int[] intArray = Arrays.stream(longArray).mapToInt(i -> (int) i).toArray();

Something else to mention here. If you just cast long to int you risk an integer overflow. So to be safe I would recommend Math#toIntExact function which ensures the conversion is safe. Here is an example:
long[] longs = new long[] {1,2,3,4,5};
int[] ints = Arrays.stream(longs).mapToInt(Math::toIntExact).toArray();
If longs contains a value that can't be converted to an int then an
ArithmeticException will be thrown e.g.
long[] longs = new long[] {1,2,3,4,5, Long.MAX_VALUE};
int[] ints = Arrays.stream(longs).mapToInt(Math::toIntExact).toArray(); // Throws here
will throw Exception in thread "main" java.lang.ArithmeticException: integer overflow this ensures your code works correctly.

Related

How to convert int array into int

Currently i started reading a book about alogirthms so I'm now trying some very simple algorithms to get comfortable with converting and so on.. In this small class I want to enable a school adding function with carry.
How can i convert the resulting Int Array into an int? I do not know how to convert them adequate..
The current result is [7, 8, 3, 7, 9, 0, 5, 6] and I want to concat the numbers into one Integer of (78379056). Which possibilities do I have?
public class Addition {
public int[] addiere(int[] a, int[] b) {
int res = 0;
int[] c = new int[a.length];
for(int i = a.length-1 ; i>=0 ; i--) {
res = a[i]+b[i];
if(res>=10) {
c[i] = oneValue(res);
a[i-1]+=1;
} else c[i]=res;
System.out.println("a -- "+a[i]+" b -- "+b[i]+" c -- "+c[i]);
}
return c;
}
public int oneValue(int t) {
String res;
int val;
res=Integer.toString(t);
res = res.substring(res.length()-1);
val = Integer.parseInt(res);
return val;
}
public static void main(String[] args) {
int[] a = {3,4,6,8,9,1,2,4};
int[] b = {4,2,5,7,8,9,3,2};
Addition add = new Addition();
int[] result;
//returns an array of Integers
System.out.println(Arrays.toString(add.addiere(a, b)));
result = add.addiere(a, b);
//HERE should be a method to convert the result ( Array of Integers ) just into a normal integer
}
}
Given the array
int arr[] = { 7, 8, 3, 7, 9, 0, 5, 6 };
you can simply do:
long num = Long.parseLong(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining()));
which outputs
78379056
Explanation:
In the mapToObj(...) we convert each element from an int to
a String using the valueOf method.
Next, we collect each of these individual Strings into one String by
means of Collectors.joining()
Now, we convert this String into a long. You can read up more about
streams from the docs here
We use long here just in case the number is too big to be contained in an int.
You can either convert the array into a String and use Integer.parseInt() to get this result or you use a simple loop adding up the numbers multiplied by 10 with their position exponent:
int r = 0;
for (int i = 0; i < result.length; i++) {
r += result[i] * Math.pow(10, result.length - i - 1);
}
I would prefer this solution.
The result for the array [7, 8, 3, 7, 9, 0, 5, 6] is 78379056.
Beside that you should consider using long instead of int if you have numbers out of the int range (78379056).
Edit: Here is a solution with Integer.parseInt():
StringBuilder builder = new StringBuilder();
for (int i : result) {
builder.append(i);
}
int r = Integer.parseInt(builder.toString());
Alternatively you can take a look at Nicholas K's answer.
public static void main(String[] args) {
int[] a = {7, 8, 3, 7, 9, 0, 5, 6};
int m = 1;
int r = 0;
for (int i=a.length-1; i>=0; i--) {
r = a[i] * m + r;
m = m * 10;
}
System.out.println(r);
}
prints:
78379056
Eventually, you could multiply each number by a power of 10 and add them together. For example this code will return "1234".
int[] array = {1, 2, 3, 4};
int total = 0;
for(int i = 0; i < array.length; i++)
if(array[i] > 9 && array[i] < 0)
throw new IllegalArgumentException("Only use digits");
else
total += array[i] * Math.pow(10, array.length - i - 1);
System.out.println(total);
It works in all cases, except cases with number. Make sure you handle the error.
(be carrefull to Integer.MAX_VALUE)
You can use BigInteger to hold the number which is more than int max size as well as you can avoid NumberFormatException.
public static void main(String[] args) {
int[] ary = {2,1,4,7,4,8,3,6,4,7};
StringBuilder numBuilder = new StringBuilder();
for(int num:ary) {
numBuilder.append(num);
}
BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
BigInteger finalNum = new BigInteger(numBuilder.toString());
if(finalNum.compareTo(maxInt)>0) {
//number is more the max size
System.out.println("number is more than int max size");
}else {
int result = finalNum.intValueExact();
System.out.println(result);
}
}

Method that takes an integer input n and rotates an array n spaces

The my goal is to take a user's input and rotate the array however many times based off of their integer input. At first I was trying to get the array to reverse just to see it shift but I have a few errors in my function that won't let me compile.
Edit: I know I used list instead of using arr. I was looking at an example and accidentally typed it in.
Here is my code:
import java.util.Scanner;
public class Project1P2 {
public static void main(String[] args) {
int[] arr1 = {2,4,6,8,10,12};
int[] arr2 = shift(arr1);
Scanner input = new Scanner(System.in);
System.out.print("Here is the Array: " + arr1);
System.out.println("Enter a number to shift array: ");
int n = input.nextInt();
}
public static int[] shift(int[] arr) {
int[] arrShiftDone = new int[list.length];
for (int i = 0, j = arrShiftDone.length - 1; i < list.length; i++, j--) {
arrShiftDone[j] = list[i];
}
return arrShiftDone;
}
}
You need to fix a couple of things:
shift method never gets called from the main method, which means it won't do anything to the array
shift method should have another argument for the number of places to shift, say n
In shift method, you are using list whereas the argument is declared as arr
Below is an example method that shifts the array:
public static int[] shift(int[] arr, int n) {
if(n > arr.length)
n = n%arr.length;
int[] result = new int[arr.length];
for(int i=0; i < n; i++){
result[i] = arr[arr.length-n+i];
}
int j=0;
for(int i=n; i<arr.length; i++){
result[i] = arr[j];
j++;
}
return result;
}
The compilation error is because the variable list is unknown. Should be using the argument arr instead of list inside the method shift(int[] arr).
You can use Arrays.stream(int[],int,int) method twice to get two streams with the specified ranges of the array: near and far, then swap them and concat back into one stream, and thus get a shifted array:
public static int[] shiftArray(int[] arr, int n) {
return IntStream
.concat(Arrays.stream(arr, n, arr.length),
Arrays.stream(arr, 0, n))
.toArray();
}
public static void main(String[] args) {
int[] arr1 = {2, 4, 6, 8, 10, 12};
System.out.println("Source array: " + Arrays.toString(arr1));
System.out.println("Enter a number: ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] arr2 = shiftArray(arr1, n % arr1.length);
System.out.println("Shifted array: " + Arrays.toString(arr2));
}
Output:
Source array: [2, 4, 6, 8, 10, 12]
Enter a number:
3
Shifted array: [8, 10, 12, 2, 4, 6]
See also: Place positive numbers before negative
Your mistake is that in your shift method you are using list, it should be arr. I have updated it below. I have also included the shift method.
Edited to include negative shifts.
public static void main(String[] args) {
int[] arr1 = {2, 4, 6, 8, 10, 12};
int[] arr2 = reverseArray(arr1);
Scanner input = new Scanner(System.in);
System.out.println("Here is the Array: " + Arrays.toString(arr1));
System.out.print("Enter a number to shift array: ");
int n = input.nextInt();
int[] arr3 = shiftArray(arr1, n);
System.out.println("Here is the shifted Array: " + Arrays.toString(arr3));
}
public static int[] reverseArray(int[] arr) {
int[] arrShiftDone = new int[arr.length];
for (int i = 0, j = arrShiftDone.length - 1; i < arr.length; i++, j--) {
arrShiftDone[j] = arr[i];
}
return arrShiftDone;
}
public static int[] shiftArray(int[] arr, int shift) {
int[] arrShiftDone = new int[arr.length];
shift = shift % arr.length;
if (shift < 0) {
shift = arr.length + shift;
}
for (int i = 0 + shift, j = 0; j < arr.length; i++, j++) {
if (i >= arr.length) {
arrShiftDone[j] = arr[i - arr.length];
} else {
arrShiftDone[j] = arr[i];
}
}
return arrShiftDone;
}

Small challenge. Comparing sum of 3 individual arrays

The code suppose to sum every individual array. Afterwards it can be use to compare which sum is the biggest or the lowes. Do anybody knows shorter way or more efficient?
int[] route1 = {12,34,21,46,25};
int[] route2 = {24,1,5,64,10,15,21};
int[] route3 = {1,13,15,16};
public static String shortestRoute(int [] route1, int [] route2, int [] route3){
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
int[][] arrays = {route1, route2, route3};
//how to write shorter the part below???
///////////////////////////////////////////////////////////////
for(int i = 0; i<arrays.length; i++){
for(int j =0; j<arrays[i].length; j++){
if(i==0){
sum1 += arrays[i][j];
}else if(i==1){
sum2 += arrays[i][j];
}else{
sum3 += arrays[i][j];
}
}
}
/////////////////////////////////////////////////
}
Starting with Java 8, summing an array can be done in a single line of code, letting you remove all loops and multi-dimensional array handling from your program:
int sum1 = Arrays.stream(route1).sum();
Little bit more detailed example of single line solution for longest/shortest route calculation
public static void main(String[] args) {
int[] route1 = {12, 34, 21, 46, 25};
int[] route2 = {24, 1, 5, 64, 10, 15, 21};
int[] route3 = {1, 13, 15, 16};
shortestRoute(route1,route2,route3);
longestRoute(route1,route2,route3);
}
private static long shortestRoute(int[]... routes) {
return Arrays.stream(routes)
.mapToInt(value -> Arrays.stream(value).sum()).min().getAsInt();
}
private static long longestRoute(int[]... routes) {
return Arrays.stream(routes)
.mapToInt(value -> Arrays.stream(value).sum()).max().getAsInt();
}

Fast way to declare incremental elements of array - Java

Say I have 10 integer variables, x1 to x10.
I have an integer array, as follows:
Int[] countup = new Int[10];
I would like to specify the elements of the array as follows:
countup[0] = x1;
countup[1] = x1 + x2;
countup[2] = x1 + x2 + x3;
And so on until countup[9] is the sum of x1 to x10.
I could do this manually if it was just 10 elements, but in the actual program I'm writing, there's over 100 elements of the array. Is there any way to set the variables of this array quickly?
A for loop is your best bet, simply put your 10 (or 100) integers into an array of it's own, then loop over your second array referencing indexes of the first array:
int[] xNumbers = { x1, x2, x3, ... x10 };
int[] countup = new int[10];
//Set the 0 index so we don't have to do extra check inside the for loop
//for out-of-bounds exception
countup[0] = xNumbers[0];
for (int i = 1; i < 10; i++) {
//countup[i-1] is why we set index 0 outside of the loop
countup[i] = xNumbers[i] + countup[i-1];
}
since countup[i-1] is the sum of the previous numbers, the previous additions are already done for you. In case you don't know what a for loop is, more information can be found here
Succinctly:
int[] xNums = { /*your x numbers here*/ };
int[] resultArray = new int[xNums.length];
for(int n = 0; n < xNums.length; n++)
{
for(int i = 0; i <= n; i++)
{
resultArray[n]+=xNums[i];
}
}
Hope that makes sense!
I wanted to find a way to do it in Java 8, and the other answer is probably better:
Here's what I have, but it seems redundant and a waste of time, but I'm unfamiliar with Java 8:
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = arr.length;
for (int i = 1; i < length; i++) {
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 0, i + 1)));
arr[i] = Arrays.stream(Arrays.copyOfRange(arr, 0, i + 1)).sum();
}
System.out.println(Arrays.toString(arr));
}
arr[9] is [1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
I believe I also interpreted the question differently. I think he wanted in index[i] the sum of all previous elements.
If my interpretation of your question is correct, to do it without Java 8, using 2 loops:
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int length = array.length;
for(int i = 1; i < length; i++) {
int sumSoFar = 0;
for(int j = 0; j <= i; j ++) {
sumSoFar += array[j];
}
array[i] = sumSoFar;
}

divide every number of long number in java

i am newbie in android developing, i have a simple question.
Imagine I have a long long number, like 166516516516516515.
And i want to have divided output like:
1,6,6,5,1,6,5,1,6,5,1,6,5,1,6,5,...
I mean i want to have every every one in output.
I wrote this algorithm :
int temp = 2536;
ArrayList<Integer> array = new ArrayList<Integer>();
do {
array.add(temp % 10);
temp /= 10;
}
while (temp > 0);
for (int i = 0; i < array.size(); i++) {
Log.i("LOG", "Dynamic Numbers Array Index #" + i + " = " + array.get(i));
}
it works for small numbers (int)
but for long number it doesn't give true work,
How can i solve it to work with big numbers?
thanks.
Just read that stuff into a string and do:
for(char c : str.toCharArray()){}
No need to divide anything and you can have arbitrary length.
If you need ints just convert by doing:
int i = (int)(c - '0');
First of all, you need to watch out if you can "cram" all your number into simple int. Chances are that if it's too long you simply cannot do that at all - as you probably noticed by now.
I took another approach to the solution, but it might not be exactly what you need. Treat the number as a string.
String temp = "166516516516516515";
breakUp(temp);
private static void breakUp(String string){
int length = string.length();
for (int i = 0; i < length; i++) {
String temp = string.substring(i, i+1);
int tempInt = Integer.valueOf(temp);
System.out.print(tempInt + " - "); //or whatever here, you can make function return list instead of void
}
}
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class Callone {
public static void main(String[] args)
{
BigInteger i = new BigInteger("166516516516516515");
List<Integer> list = new ArrayList<Integer>();
BigInteger ten = new BigInteger("10");
while (!i.equals(BigInteger.ZERO))
{
list.add(0, i.mod(ten).intValue());
i = i.divide(ten);
}
System.out.println(list.toString());
}
}
output: [1, 6, 6, 5, 1, 6, 5, 1, 6, 5, 1, 6, 5, 1, 6, 5, 1, 5]
split longString to intArray
Split longString to char array and then use Character.digit to get digit value.
public static int[] splitLong(String longStr) {
int i = 0;
int[] nums = new int[longStr.length()];
for (char l : longStr.toCharArray())
nums[i++] = Character.digit(l, 10);
return nums;
}
Other approach:
public static int[] splitLongNum(String longStr) {
int len = longStr.length();
int[] nums = new int[len];
for (int j = 0; j < len; j++)
nums[j] = Character.digit(longStr.charAt(j), 10);
return nums;
}

Categories

Resources