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();
}
Related
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);
}
}
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;
}
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;
}
How would one go about filling in an array so that, for example, if you had the following array.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 3;
arr[2] = 7;
arr[3] = 2;
arr[4] = -4;
so it would look like
arr = {1, 3, 7, 2, -4};
and you would pass it into your method to get a result of
arr = {1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4};
so that you essentially are filling in the numeric gaps. I'd like to make this under the assumption that I don't know how long the array passed in is going to be to make it a more universal method.
my current method looks like such right now...
public static void fillArray(int[] numbers){
int length = numbers.length;
for(int i = 0; i < numbers.length - 1; i ++){
if(numbers[i] <= numbers[i + 1]){
length += numbers[i + 1] - numbers[i];
}else if(numbers[i + 1] < numbers[i]){
length += numbers[i + 1] - numbers[i];
}
}
}
I have length to determine the size of my new array. I think it should work but I'm always down for some input and advice.
Looks like homework, providing algorithm only:
Navigate through the elements of the current array.
Get the distance (absolute difference) between the elements in the array.
Summarize the distances.
Create a new array whose length would be the sum of the distances.
Fill the new array using the elements of the first array and filling the gaps.
Return the array.
Like Luiggi Mendoza said, looks like HW, so here's another algorithm:
insert the first element into a list of integers.
loop on the rest of the elements.
for each two array elements X[i-1], X[i], insert the missing integers to the list
after the loop - use guava to turn the List to array.
This works. just check for array size < 2 for safety.
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
Integer[] result = fillArray(arr);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
private static Integer[] fillArray(int[] arr) {
List<Integer> list = new ArrayList<Integer>();
list.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
int prevItem = arr[i-1];
int gap = arr[i] - prevItem;
if(gap > 0){
fillGap(list, prevItem, gap, 1);
} else if(gap < 0){
fillGap(list, prevItem, gap, -1);
}
}
return list.toArray(new Integer[0]);
}
private static void fillGap(List<Integer> list, int start, int gap, int delta) {
int next = start+delta;
for (int j = 0; j < Math.abs(gap); j++) {
list.add(next);
next = next+delta;
}
}
Try
import java.util.ArrayList;
import java.util.List;
public class ArrayGap {
public static void main(String[] args) {
int[] arr = {1, 3, 7, 2, -4};
int high, low;
List<Integer> out = new ArrayList<Integer>();
for(int i=0; i<arr.length - 1; i++){
high = arr[i];
if(arr[i] < arr[i+1]){
for(int j=arr[i]; j<arr[i+1]; j++){
out.add(j);
}
} else {
for(int j=arr[i]; j>=arr[i+1]; j--){
out.add(j);
}
}
}
System.out.println(out);
}
}
public class Swap_Numbers {
public static void main(String[] args) {
int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers
System.out.println (numTens[3]); // I want my numTens displays numHundred
System.out.println (numHundred[4]); // I want my numHundred displays numTens
}
}
I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables.. hope some can explain me how Thanks!
I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables
You shouldn't, basically. Just take the simple route of a temporary variable:
int[] tmp = numTens;
numTens = numHundred;
numHundred = tmp;
For ints you can actually swap the values within the arrays using arithmetic without temporary variables (which is not the same as swapping which arrays the variables refer to), but it would be very odd to actually find yourself in a situation where you want to do that. Sample code:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] x = { 1, 2, 3, 4, 5 };
int[] y = { 15, 60, 23, 10, 100 };
swapValues(x, y);
System.out.println("x: " + Arrays.toString(x));
System.out.println("y: " + Arrays.toString(y));
}
static void swapValues(int[] a, int[] b) {
// TODO: Validation
for (int i = 0; i < a.length; i++) {
a[i] += b[i];
b[i] = a[i] - b[i];
a[i] -= b[i];
}
}
}
Even there, I would actually write swapValues using a temporary variable instead, but the above code is just to prove a point...
For that I'm assuming both arrays are of same size. Then you can do :
for (int i = 0; i < numTens.length; i++)
{
numTens[i] = numTens[i] + numHundred[i]; // statement 1
numHundred[i] = numTens[i] - numHundred[i]; // statement 2
numTens[i] = numTens[i] - numHundred[i]; // statement 3
}
Lets take the 2nd elements of both array
Ten[2] = 3;
Hundred[2] = 300;
-------------------------------------
Ten[2] = 303 // after statement 1
Hundred[2] = 3 // after statement 2
Ten[2] = 300 // after statement 3
-------------------------------------
Ten[2] = 300;
Hundred[2] = 3;
Values are swapped without using temporary variable.
If you want to swap the numbers in the array you can do something like this:
void swap(int[] arr1, int[] arr2)
{
//if parameters are as bellow
//arr1 = {1, 2, 3, 4, 5};
//arr2 = {10, 20, 30, 40, 50};
if(arr1.length == arr2.length)
{
for(int i =0; i < arr1.length ; i++)
{
arr1[i] = arr1[i] + arr2[i];
arr2[i] = arr1[i] - arr2[i];
arr1[i] = arr1[i] - arr2[i];
}
}
else
{
throw new IllegalArgumentException;
}
}
int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers
for (int i = 0; i < numTens.length; i++) {
numHundred[i] = numTens[i];
numTens[i] = numTens[i]*100;
}
System.out.println (numTens[3]);
System.out.println (numHundred[4]);