Need to find even sums of digits in the array - java

I need to find even sum of digits from an array in Java.
Array: int [] cars = {3, 4, 6, 5};
Output: 8 10
Process:
3 + 4 == 7 --> not even
3 + 6 == 9 --> not even
3 + 5 == 8 --> even (so print it)
4 + 6 == 10 --> even (so print it)
4 + 5 == 9 --> not even
6 + 5 == 11 --> not even

If this is to check two value combination, you can use something like the below,
int[] arr = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if ((arr[i] + arr[j]) % 2 == 0) {
System.out.println("" + arr[i] + "+" + arr[j] + "=even");
} else {
System.out.println("" + arr[i] + "+" + arr[j] + "=odd");
}
}
}
and the output will look like this
1+2=odd
1+3=even
1+4=odd
1+5=even
1+6=odd
2+3=odd
2+4=even
2+5=odd
2+6=even
3+4=odd
3+5=even
3+6=odd
4+5=odd
4+6=even
5+6=odd

filter the array into two lists, one for odd numbers and another for even numbers, then loop over each list summing each element with all the others and checking the results, at the end of the loop, remove that element.
the benefit of filtering the array to odd and even numbers is that odd + even is always odd, so, eliminating this case saves you some time.

Related

How to find longest run in an array and put parentheses around it and all other runs in the array? APCSA

The task is: Write a program that generates a sequence of 20 random die tosses (values 1 - 6). The user will be asked if they want to see all runs or the largest run. The array will then be printed designating the run by including them in parentheses.
I have tried my best to make methods to accomplish this task, but I am confused on how to add the parentheses after finding the run and finding runs greater than a length of 2. I also tried to find other programs such as mine online, but I was unable to find assistance in my issues of being able to put the parentheses around runs and finding all runs.
Example of finding all runs: 1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5 5 5) 6 3 1
Example of finding longest run: 1 2 5 5 3 1 2 4 3 (2 2 2 2) 3 6 5 5 5 5 6 3 1
Here is my code so far:
import java.util.*;
public class RunGenerator {
Scanner s = new Scanner(System.in);
static int max = 6;
static int min = 1;
public static void randomNumbers(int[]array)// generates the 20 random numbers from the die tosses using Math.random
{
for(int i = 0; i <= 20; i++)
{
array[i] = (int)Math.random()* (max-min +1) + min;
}
}
public static int findRun(int[]array)// finds runs among the array and returns the run surrounded by parentheses
{
for(int i = 0; i <= array.length; i++)
{
int count = 0;
int currentValue = array[i++];
int lastValue = array[i];
if(array[i] == array[i+1]) //checks to see if the element is equal to _____
{
System.out.println("(");
while(lastValue == currentValue) //while the two elements are equal, we do not close the parentheses
{
count++; //what do I do in here to check for further length??
}
System.out.println(")");
}
else
{
System.out.println(i + " " + (i+1) );
}
}
}
public static int findLargestRun(int[]array)
{
for(int i = 0; i <= array.length; i++)
{
if(array[i] == array[i++]) //checks to see if the element is equal to the adjacent element
{
while(array[i] == array[i++]) //while the two elements are equal, we do not close the parentheses
{
}
System.out.println("(" + i);
}
else
{
System.out.println(i + " " + (i+1) );
}
}
}
It may be worth to provide different methods to find the runs, to print the runs between ( and ), and to print longest runs using a helper class Run to store the data about the run: start, length, value:
static class Run {
int start;
int length = 1;
int value;
}
static List<Run> findRuns(int ... arr) {
List<Run> result = new ArrayList<>();
Run run = new Run();
run.start = 0;
run.value = arr[0];
int max = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != run.value) {
result.add(run);
run = new Run();
run.start = i;
run.value = arr[i];
} else {
run.length++;
if (max < run.length) {
max = run.length;
}
}
}
result.add(run);
System.out.println("Longest run: " + max);
return result;
}
Printing method uses Stream API + Collections.nCopies to build runs
static String printRuns(List<Run> runs) {
return runs.stream()
.map(r -> r.length > 1
? "(" + String.join(" ", Collections.nCopies(r.length, Integer.toString(r.value))) + ")"
: Integer.toString(r.value)
)
.collect(Collectors.joining(" "));
}
Similar printing of longest runs (which can be multiple)
static String printLongestRuns(List<Run> runs) {
int max = runs.stream().mapToInt(r -> r.length).max().orElse(-1);
return runs.stream()
.map(r -> r.length > 1
? (r.length == max ? "(" : "")
+ String.join(" ", Collections.nCopies(r.length, Integer.toString(r.value)))
+ (r.length == max ? ")" : "")
: Integer.toString(r.value)
)
.collect(Collectors.joining(" "));
}
Tests
System.out.println(printRuns(findRuns(1)));
System.out.println(printRuns(findRuns(2, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 5, 5, 6, 3, 1)));
System.out.println(printLongestRuns(findRuns(2, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 5, 5, 6, 3, 1)));
Output
Longest run: 1
1
Longest run: 4
(2 2) (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5 5 5) 6 3 1
Longest run: 4
2 2 5 5 3 1 2 4 3 (2 2 2 2) 3 6 (5 5 5 5) 6 3 1
some errors to fix:
your code needs an entry point where the program starts. java doesn't start at the top of the program. java instanciates all free* static variables(that are outside of functions within your class) and start execution at the first line inside a public static void main(String[] args) { /*here*/ } function. if you work inside an instance of your class (which you are not here) non-static free* variables will be instanciated within that instance. TLDR: make the Scanner static aswell and add a static void main(String[] args) function.
in your for loop for(int i = 0; i <= array.length; i++) you try to compare values if(array[i] == array[i++]) which will lead to if(array[array.length] == array[array.length+1]) in the last cycle and crash your application with arrayoutofbounds-exception
if you create a function with a return type other than void like you did with public static **int** findRun(int[]array) you can't compile without errors if you don't provide the return variable (return myint; // at the end of the function)
if you pass basic variables to functions they get copied in java, only objects from complex classes are treated as pointers. -> change function randomNumbers(int[]array) to function randomNumbers() and work with a static global array instead for example
also a word of warning:
Math.random() is a PSEUDO-random-number generator between 0.000... and 0.999.... Select other real/secure random generators for security and science functions.
I hope this helps you to start. I don't think a working code would help you that much at this point. Once you get the java concepts you can definitely do it.

How can I efficiently compute the sum of parts of an array of sizes in an arithmetic sequence?

I am trying to find the sum of parts of a given array with a length that is the sum of the first N positive integers for some whole number N. The size of each part for which I am to find the sum are the numbers in said arithmetic sequence. For instance, for an array of length 10, I need to find the sum of the first number, the next two numbers, and so on, until the next N numbers.
Example Input:
[1,4,5,2,6,7,9,8,7,10]
Example Output:
[1,9,15,34]//1, 4+5, 2+6+7, 9+8+7+10
Explanation:
The first sum is 1, the first element (index 0). The sum of the next two numbers is 4 + 5 = 9 (index 1 and 2). The sum of the next three numbers is 2 + 6 + 7 = 15 (index 3, 4, and 5). The sum of the last four numbers is 9 + 8 + 7 + 10 = 34 (index 6, 7, 8, 9).
You can compute the size of the result array using the formula for the sum of an arithmetic sequence, i.e. n(n + 1) / 2.
A prefix sum array can be applied here so so that any range sum can be computed in O(1) time with O(n) precomputation time and space (which is also the overall complexity of this algorithm).
final int[] input = { 1, 4, 5, 2, 6, 7, 9, 8, 7, 10 };
// size * (size + 1) / 2 = input.length
final int size = (-1 + (int) Math.sqrt(1 + 8 * input.length)) / 2;
// derived by quadratic formula
final int[] result = new int[size];
final int[] sum = new int[input.length + 1];
for (int i = 1; i <= input.length; i++) {
sum[i] = sum[i - 1] + input[i - 1];
}
for (int i = 1, j = 0; i <= input.length; i += ++j) {
result[j] = sum[i + j] - sum[i - 1];
}
System.out.println(Arrays.toString(result));
Ideone Demo
The following algorithm is very efficient and does not rely on the summation formula to work (as you had asked about) other than to compute the length of the result array. This should not be a problem since it is basic algebra. If you use a List implementation you would not have to do that.
It also only sums only to the max allowed by the given array. So if you provide an array like
1 2 3 4 5 6 7 8 9 10 11 12 13
It will silently ignore 11 12 and 13 since they don't comprise enough values to continue.
Here is the algorithm with your original data set and the output.
int[] arr = { 1, 4, 5, 2, 6, 7, 9, 8, 7, 10 };
int start = 0; // start of group
int end = 0; // end of group
int[] sol = new int[(int)(-.5 + Math.sqrt(2*arr.length + .25))];
for (int i = 1; i <= sol.length; i++) {
// initialize the sum
int sum = 0;
// compute next end
end += i;
// and sum from start to end
for (int k = start; k < end; k++) {
sum += arr[k];
}
// old end becomes next start
start = end;
sol[i-1] = sum;
}
Prints
[1, 9, 15, 34]

i want to find sum of array first and last element and 2nd and 2nd last element and 3rd and 3rd last element and so on

here remember array size and values is defined by user by the help of scanner class and i am using java
task is to find sum of first and last element and 2nd and 2nd last and so on
i already try research but failed
thanks in advance
int sum = 0;
int f = 0;
System.out.println("Your Array is even");
System.out.println("Kinldy enter Your Values of Array");
for(int i = 0 ; i<array.length ; i++)
{
array[i] = s.nextInt();
for(int j = 0 ; j< array.length-i-1 ; j++)
{
sum = j + array.length+1 ;
}
}
System.out.println("Your Sum " + sum);
You could just loop over your array and use the index to find the corresponding numbers from both sides.
The first element can be found by simply doing: array[i].
The corresponding element from the other side can be found by: array[array.length - 1 - i].
The complete code could be something like this:
public static void main(String[] args) {
int[] array = {1, 3, 6, 4, 1, 8};
for(int i = 0; i < array.length / 2; i++)
{
int firstNumber = array[i];
int secondNumber = array[array.length - 1 - i];
int sum = firstNumber + secondNumber;
System.out.println(firstNumber + " + " + secondNumber + " = " + sum);
}
}
Output:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
I made the assumption that you only want to do this for half of the array. That's why the for loop is only executed as long as i<array.length / 2. This solution assumes that the length of your array is always an even number. If your array has an uneven length, the middle element will not be considered.
In case you do want to do this for the complete array, all you have to do is remove the / 2 from the for loop statement. The output will be:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
4 + 6 = 10
1 + 3 = 4
8 + 1 = 9

Compose the sum

Given two numbers, s (sum)
and n (posit number, ii), there are several ways in which I can express and,
as a sum of n whole numbers, strictly positive.
for s = 7, n = 3; 7 = 4 + 2 + 1 and
7 = 1 + 4 + 2 are not considered distinct.
I have to calculate i th solution.
Example for input:
11
6
5
example for output:
11=3+2+2+2+1+1 (5th mode to compose the sum)
I tried to use backtraking to compose these sums but the algorithm does not produce all the solutions.
static boolean checkSum(int sum, int remPos, int elem) {
if (sum < remPos)
return false;
if (sum > remPos * elem)
return false;
return true;
}
private ArrayList<Integer> back(ArrayList<Integer> sol, int crtPos,
int sum, ArrayList<Integer> ans) {
//the solution was found
if (index == i) {
ans.addAll(sol);
return sol;
} else if (index > i) {
return null;
}
if (crtPos == k + 1) {
crtPos = 1;
index++;
}
for (int j = sol.get(crtPos - 1); j > 0; j--) {
//add to solution
sol.add(crtPos, j);
//decreases from the remaining sum
sum -= j;
//check
if (checkSum(sum, k - crtPos, j)) {
sol = back(sol, crtPos + 1, sum, ans);
}
//remove from solution
sol.remove(crtPos);
sum += j;
}
return sol;
}
Don't know what is wrong with your code, but let me give you an alternate algorithm that doesn't use recursion, and doesn't require boxing the values.
First, you said that order of values doesn't matter, e.g. 7 = 4 + 2 + 1 and 7 = 1 + 4 + 2 is the same solution. In the algorithm below, we ensure that by stating that values must be in ascending order, e.g. 7 = 1 + 2 + 4.
Let me illustrate algorithm using example of s=10, n=5, which for reference gives the following solutions:
10 = 1 + 1 + 1 + 1 + 6
10 = 1 + 1 + 1 + 2 + 5
10 = 1 + 1 + 1 + 3 + 4
10 = 1 + 1 + 2 + 2 + 4
10 = 1 + 1 + 2 + 3 + 3
10 = 1 + 2 + 2 + 2 + 3
10 = 2 + 2 + 2 + 2 + 2
First, build an int[] and fill it with 1's, except the last value is s - (n-1), aka s - n + 1 (where n-1 is the sum of the 1's):
[1, 1, 1, 1, 6]
That is your first solution.
Now we "increment" that to the next solution, where the last value is always calculated, i.e. the next solution is:
[1, 1, 1, 2, x] where x = s - (1+1+1+2) = 5
[1, 1, 1, 2, 5]
We continue that as long as last value >= second last value:
[1, 1, 1, 3, 4]
Next one would have been [1, 1, 1, 4, 3] but that violates our constraint, so be walk backwards to previous value, and increment that. Since values must be ascending, we will fill the following positions with the same value (represented as = below), except we calculate the last value (x):
[1, 1, 2, =, x] where x = s - (1+1+2+2) = 4
[1, 1, 2, 2, 4]
Next one is easy:
[1, 1, 2, 3, 3]
Now we can't increment the 3rd position from 2 to 3, because that would give us [1, 1, 3, 3, 2] so we walk back one more position:
[1, 2, =, =, x] where x = s - (1+2+2+2) = 3
[1, 2, 2, 2, 3]
Now we have to walk back one more time:
[2, =, =, =, x] where x = s - (2+2+2+2) = 2
[2, 2, 2, 2, 2]
And we're done, because we can't walk any further back.
Here is code in compact form:
public static void compose(int s, int n) {
if (s < n || n < 1)
throw new IllegalArgumentException();
int[] values = new int[n];
Arrays.fill(values, 1);
values[n - 1] = s - n + 1;
for (;;) {
printSolution(s, values);
int i = n - 1, remain = values[i];
for (; --i >= 0; remain += values[i])
if (--remain >= ++values[i] * (n - i - 1))
break;
if (i < 0)
break;
Arrays.fill(values, i + 1, n, values[i]);
values[n - 1] = remain - values[i] * (n - i - 2);
}
}
public static void printSolution(int s, int[] values) {
System.out.print(s + " = " + values[0]);
for (int i = 1; i < values.length; i++)
System.out.print(" + " + values[i]);
System.out.println();
}
Output from compose(7, 3)
7 = 1 + 1 + 5
7 = 1 + 2 + 4
7 = 1 + 3 + 3
7 = 2 + 2 + 3
Output from compose(10, 5) is already shown earlier.
If you just need the i'th solution, remove the printSolution call, change the forever loop to loop i-1 times, and return the values array.

Specify number of bits in a String represetation of a binary number

I am trying to write a algorithm that will print a powerset of a given set of numbers. I did that with a loop that goes from zero to 2^length of my set. I convert the index i to binary, and whenever there is a one, I print that number. However, since the string does not have any preceding zeros, I am not getting the right output.
For example, if I have a set of three numbers: {2, 3, 4}, when i is 3, I want the string to be "011", but instead it is "11" and I'm getting an output of 2, 3 instead of 3, 4.
Here is my code:
public static void powerset (int[] A){
double powerSetLength = Math.pow(2, A.length);
for (int i=0; i<powerSetLength; i++){
String bin = Integer.toBinaryString(i);
System.out.println ("\nbin: " + bin);
for (int j=0; j<bin.length(); j++){
if (bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
System.out.println();
}
Here is the output that I am getting:
9 7 2
bin: 0
bin: 1
9
bin: 10
9
bin: 11
9 7
bin: 100
9
bin: 101
9 2
bin: 110
9 7
bin: 111
9 7 2
Here is an example of the output that I would like to get:
9 7 2
bin 001
2
I would like to know if there is a way to convert an integer to binary with a specified number of bits so that I can get this output.
One easy way to deal with this problem is assuming that if a digit is missing in the representation, then its value is zero. You can do it like this:
// The number of digits you want is A.length
for (int j=0; j < A.length ; j++) {
// If j is above length, it's the same as if bin[j] were zero
if (j < b.length() && bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
Of course if you can assume that A.length < 64 (which you should be able to assume if you want your program to finish printing in under a year) you could use long to represent your number, and bit operations to check if a bit is set or not:
int len = A.length;
for (long mask = 0 ; mask != (1L << len) ; mask++) {
for (int i = 0 ; i != len ; i++) {
if ((mask & (1L << i)) != 0) {
System.out.print(A[j] + " ");
}
}
System.out.print();
}
String padded = String.format("%03d", somenumber);
or
System.out.printf("%03d", somenumber);
Would each pad to three digits (the 3 in the format specifier). You could additionally build the specifier programatically based on length you need:
String.format("%0" + n + "d", somenumber)
But this is unnecessary if you just need to know if bit N is set. You could just as easily do this:
if ((value & (1L << n)) != 0) { }
Where value is the number, and n is the ordinal of the bit you want. This logically ands the bit in question with the value - if it's set, the result is non-zero, and the if is true. If it is not set, the result is zero, and the if is false.

Categories

Resources