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);
}
}
Related
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.
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;
}
newbie here and new to Java itself. Currently working on a little project and I am stumped where I am currently at. Basically my code has two arrays, passes these arrays down to my method. At this point my method is supposed to look and compare my arrays, find the HIGHEST common int which in this case for this program is 10, I would like my program to then take that 10 and return it back to main to be printed out, also this program is assuming that it is possible for there to be no common number which in that case it would print out -1. Here is my code so far.
public class arrayCompare
{
public static void main(String [] args)
{
int [] arrayA = {2, 4, 6 , 8, 10, 12};
int [] arrayB = {3, 4, 7 , 10, 11,13};
int result = largestInCommon(arrayA , arrayB);
}
public static int largestInCommon( int [] A, int[] B)
{
int counter = 0;
for( int x = 0; x < A.length; x++)
{
if(A[0]==B[x])
{
for(int y = 0; y < B.length; y++)
}
}
}
}
Loop over all the elements of the two arrays. Check if every element is equals to the other and also higher than the last higher element. If it is, this would be the new higher element
int[] arrayA = { 2, 4, 6, 8, 10, 12 };
int[] arrayB = { 3, 4, 7, 10, 11, 13 };
int higher = -1;
for (int a = 0; a < arrayA.length; a++) {
for (int b = 0; b < arrayB.length; b++) {
if (arrayA[a] == arrayB[b] && arrayA[a] > higher) {
higher = arrayA[a];
}
}
}
System.out.println(higher);
Output:
10
Your error is to compare the element before entering the second loop. You check only if the first element of arrayA[] exists also in arrayB[] and you never set and return the new higher value
You need to iterate over the two arrays and check if the A[x] == B[y] and largest>A[x], you can refer the below code:
public static int largestInCommon(int [] A, int[] B) {
int largest = 0;
for( int x = 0; x < A.length; x++) {
for(int y = 0; y < B.length; y++) {
if(A[x] == B[y] && largest>A[x]) {
largest = A[x];
break;//no need to iterate 2nd array,if common elment found
}
}
}
return largest;
}
You can do the following.
store array A in a hash set S
sort array b in decreasing order
from the 0 index to n-1 of b check whether the element is in S
a. if any value is found return that value
b. if no value found then return -1.
You can do it in O(sizeA) space and O(sizeB) time. [if already sorted else O[sizeB*lg(sizeB)]
public static void main(String [] args)
{
int [] arrayA = {2, 4, 6 , 8, 10, 12};
int [] arrayB = {3, 4, 7 , 10, 11,13};
int result = largestInCommon(arrayA , arrayB);
System.out.println("Max "+result);
}
public static int largestInCommon( int [] A, int[] B)
{
int counter = -1;
for( int x = 0; x < A.length; x++)
{
for(int y = 0; y < B.length; y++){
if(A[x]==B[y])
{
if(counter < A[x]){
counter=A[x];
}
}
}
}
return counter;
}
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;
}
I am trying to remove duplicates from a list by creating a temporary array that stores the indices of where the duplicates are, and then copies off the original array into another temporary array while comparing the indices to the indices I have stored in my first temporary array.
public void removeDuplicates()
{
double tempa [] = new double [items.length];
int counter = 0;
for ( int i = 0; i< numItems ; i++)
{
for(int j = i + 1; j < numItems; j++)
{
if(items[i] ==items[j])
{
tempa[counter] = j;
counter++;
}
}
}
double tempb [] = new double [ items.length];
int counter2 = 0;
int j =0;
for(int i = 0; i < numItems; i++)
{
if(i != tempa[j])
{
tempb[counter2] = items[i];
counter2++;
}
else
{
j++;
}
}
items = tempb;
numItems = counter2;
}
and while the logic seems right, my compiler is giving me an arrayindexoutofbounds error at
tempa[counter] = j;
I don't understand how counter could grow to above the value of items.length, where is the logic flaw?
You are making things quite difficult for yourself. Let Java do the heavy lifting for you. For example LinkedHashSet gives you uniqueness and retains insertion order. It will also be more efficient than comparing every value with every other value.
double [] input = {1,2,3,3,4,4};
Set<Double> tmp = new LinkedHashSet<Double>();
for (Double each : input) {
tmp.add(each);
}
double [] output = new double[tmp.size()];
int i = 0;
for (Double each : tmp) {
output[i++] = each;
}
System.out.println(Arrays.toString(output));
Done for int arrays, but easily coud be converted to double.
1) If you do not care about initial array elements order:
private static int[] withoutDuplicates(int[] a) {
Arrays.sort(a);
int hi = a.length - 1;
int[] result = new int[a.length];
int j = 0;
for (int i = 0; i < hi; i++) {
if (a[i] == a[i+1]) {
continue;
}
result[j] = a[i];
j++;
}
result[j++] = a[hi];
return Arrays.copyOf(result, j);
}
2) if you care about initial array elements order:
private static int[] withoutDuplicates2(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
int[] result = new int[a.length];
int j = 0;
for (int i = 0 ; i < a.length; i++) {
if (keys.add(a[i])) {
result[j] = a[i];
j++;
}
}
return Arrays.copyOf(result, j);
}
3) If you do not care about initial array elements order:
private static Object[] withoutDuplicates3(int[] a) {
HashSet<Integer> keys = new HashSet<Integer>();
for (int value : a) {
keys.add(value);
}
return keys.toArray();
}
Imagine this was your input data:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8
Value: 1, 2, 3, 3, 3, 3, 3, 3, 3
Then according to your algorithm, tempa would need to be:
Index: 0, 1, 2, 3, 4, 5, 6, 7, 8, ....Exception!!!
Value: 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 5, 6, 7, 8, 6, 7, 8, 7, 8, 8
Why do you have this problem? Because the first set of nested for loops does nothing to prevent you from trying to insert duplicates of the duplicate array indices!
What is the best solution?
Use a Set!
Sets guarantee that there are no duplicate entries in them. If you create a new Set and then add all of your array items to it, the Set will prune the duplicates. Then it is just a matter of going back from the Set to an array.
Alternatively, here is a very C-way of doing the same thing:
//duplicates will be a truth table indicating which indices are duplicates.
//initially all values are set to false
boolean duplicates[] = new boolean[items.length];
for ( int i = 0; i< numItems ; i++) {
if (!duplicates[i]) { //if i is not a known duplicate
for(int j = i + 1; j < numItems; j++) {
if(items[i] ==items[j]) {
duplicates[j] = true; //mark j as a known duplicate
}
}
}
}
I leave it to you to figure out how to finish.
import java.util.HashSet;
import sun.security.util.Length;
public class arrayduplication {
public static void main(String[] args) {
int arr[]={1,5,1,2,5,2,10};
TreeSet< Integer>set=new TreeSet<Integer>();
for(int i=0;i<arr.length;i++){
set.add(Integer.valueOf(arr[i]));
}
System.out.println(set);
}
}
You have already used num_items to bound your loop. Use that variable to set your array size for tempa also.
double tempa [] = new double [num_items];
Instead of doing it in array, you can simply use java.util.Set.
Here an example:
public static void main(String[] args)
{
Double[] values = new Double[]{ 1.0, 2.0, 2.0, 2.0, 3.0, 10.0, 10.0 };
Set<Double> singleValues = new HashSet<Double>();
for (Double value : values)
{
singleValues.add(value);
}
System.out.println("singleValues: "+singleValues);
// now convert it into double array
Double[] dValues = singleValues.toArray(new Double[]{});
}
Here's another alternative without the use of sets, only primitive types:
public static double [] removeDuplicates(double arr[]) {
double [] tempa = new double[arr.length];
int uniqueCount = 0;
for (int i=0;i<arr.length;i++) {
boolean unique = true;
for (int j=0;j<uniqueCount && unique;j++) {
if (arr[i] == tempa[j]) {
unique = false;
}
}
if (unique) {
tempa[uniqueCount++] = arr[i];
}
}
return Arrays.copyOf(tempa, uniqueCount);
}
It does require a temporary array of double objects on the way towards getting your actual result.
You can use a set for removing multiples.