I'm working on an assignment for a beginning Java course and I am completely stuck on this problem.
Write a program that computes the sum of the differences of pairs of numbers in an array. For example if the array is [2, 3, 7, 8, 9, 12] the sum of the differences of pairs is
(2-3) + (7-8) + (9-12)
** we are not allowed to use built in Java functions.
Here is what I have so far.. (I know it is terrible)
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i++)
{
for(int j = i+1; j < A.length; j++)
sum = (A[i] - A[j]);
}
System.out.println(sum);
}
}
When you use that nested cycle you're doing this:
i = 0,
j = 1,
sum = 3 - 4;
// next cycle,
i = 0,
j = 2,
sum = 3 - 5;
// etc...,
i = 1,
j = 2,
sum = 4 - 5,
// etc..;
Which means for each value of A[i] you're making the difference of A[i] and all the values in the array for A[j + 1]. Also you're not updating the sum variable. When you do sum = A[i] - A[i + 1] because this operation only gives the variable sum a new value. What you want is sum+= value, which means sum = sum + newValue (newValue = A[i] - A[i +1]). This operation adds the new value to the old value stored in sum.
So what you need to do is add the two values and jump 2 indexes (i+=2) so you don't do (for example) 3-4, 4-5, 5-6 etc. what you want is 3-4, 5-6, etc.
Try this:
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i+=2)
{
sum +=(A[i] - A[i + 1]);
}
System.out.println(sum);
}
}
I am not sure what are you stuck on exactly but looks like you are not adding the sum.
public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0,i=0;
while(i<A.length){
sum+= (A[i] - A[i++]);
}
System.out.println(sum);
}
Related
Can you please help me understand what the following code means and what the value of number[2][2] is?
public static void main(String[] args) {
int[][] numbers = new int [3][3];
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[0].length; j++) {
numbers[i][j] = i*j;
}
In Java, a multiple dimension array is constructed with multiple one dimensional arrays. In your example numbers[3][3] will look like the below array:
numbers = [
[0, 0, 0],
[0, 1, 2],
[0, 2, 4]
]
Now when you ask what will be the length of numbers[0]? Then it is easy to say 3. numbers[0] holds [0, 0, 0]. And if you ask what is the value of numbers[2][2] then it is 4 ( since array index starts with 0 ).
Now here I put another example.
public class Array {
public static void main(String[] args) {
int[][] numbers = new int[3][];
numbers[0] = new int[2];
numbers[1] = new int[3];
numbers[2] = new int[4];
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
numbers[i][j] = j;
}
}
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
}
Here I take an array and make the internal array size differently. This array will look like this:
numbers = [
[0, 1],
[0, 1, 2],
[0, 1, 2, 3]
]
Here I create the first array with size 2, second array with size 3 and third array with size 4, put some data into it and simply print it.
I think you may now visualize what numbers[0].length actually means.
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
import java.util.*;
class Main {
/* Utility function that puts all non-positive
(0 and negative) numbers on left side of
arr[] and return count of such numbers */
static int segregate(int arr[], int size)
{
int j = 0, i;
for (i = 0; i < size; i++) {
if (arr[i] <= 0) {
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// increment count of non-positive
// integers
j++;
}
}
return j;
}
/* Find the smallest positive missing
number in an array that contains
all positive integers */
static int findMissingPositive(int arr[], int size)
{
int i;
// Mark arr[i] as visited by making
// arr[arr[i] - 1] negative. Note that
// 1 is subtracted because index start
// from 0 and positive numbers start from 1
for (i = 0; i < size; i++) {
int x = Math.abs(arr[i]);
if (x - 1 < size && arr[x - 1] > 0)
arr[x - 1] = -arr[x - 1];
}
// Return the first index value at which
// is positive
for (i = 0; i < size; i++)
if (arr[i] > 0)
return i + 1; // 1 is added becuase indexes
// start from 0
return size + 1;
}
/* Find the smallest positive missing
number in an array that contains
both positive and negative integers */
static int findMissing(int arr[], int size)
{
// First separate positive and
// negative numbers
int shift = segregate(arr, size);
int arr2[] = new int[size - shift];
int j = 0;
for (int i = shift; i < size; i++) {
arr2[j] = arr[i];
j++;
}
// Shift the array and call
// findMissingPositive for
// positive part
return findMissingPositive(arr2, j);
}
// main function
public static void main(String[] args)
{
int arr[] = { 0, 10, 2, -10, -20 };
int arr_size = arr.length;
int missing = findMissing(arr, arr_size);
System.out.println("The smallest positive missing number is " + missing);
}
}
}
If you need to use stream, the more straightfoward, but not optimal way to do it is to create an infinite stream, starting at 1 and return the first that is not in arr:
int[] arr = { 1, 3, 6, 4, 1, 2 };
Set<Integer> arrSet = Arrays.stream(arr).boxed().collect(Collectors.toSet());
Optional<Integer> found = IntStream.iterate(1, o -> o + 1).boxed()
.filter(value -> !arrSet.contains(value))
.findFirst();
found.ifPresent(System.out::println);
Output
5
As pointed out this is very inefficient, but in terms of computational complexity I believe is optimal, at least for the worst case i.e. the one you have to look at all the elements.
Below you can find the missing positive integer using Streams -
int ar[] = { 0, 10, 2, -10, -20 };
int max = Arrays.stream(ar).max().getAsInt();
System.err.println("maxvalue "+max);
int val = IntStream.range(1, max).filter(i->!Arrays.stream(ar).anyMatch(x->x==i))
.findFirst().getAsInt();
System.out.println(val);
int[] val1 = IntStream.range(1, max).filter(i->!Arrays.stream(ar).anyMatch(x->x==i)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(val1).forEach(System.out::println);
int[] valEven = IntStream.range(1, max).filter(i->Arrays.stream(val1).anyMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valEven).forEach(System.out::println);
int[] valOdd = IntStream.range(1, max).filter(i->!Arrays.stream(val1).anyMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valOdd).forEach(System.out::println);
int[] valOdd1 = IntStream.range(1, max).filter(i->Arrays.stream(val1).noneMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valOdd1).forEach(System.out::println);
int[] valEven1 = IntStream.range(1, max).filter(i->!Arrays.stream(val1).noneMatch(x->i%2==0)).map(p->p).toArray();
System.out.println("------------------");
IntStream.of(valEven1).forEach(System.out::println);
You can also do a mix of stream and primitive int loop:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numberSet1 = {1, 3, 6, 4, 1, 2};
int[] numberSet2 = {-1, -3};
int[] numberSet3 = {1, 2, 3};
System.out.println(calcularPrimero(numberSet1));
System.out.println(calcularPrimero(numberSet2));
System.out.println(calcularPrimero(numberSet3));
}
public static int calcularPrimero (int[] A) {
//IntStream intStream = Arrays.stream(A).filter(x -> x >= 0).distinct().sorted();
int[] B = Arrays.stream(A).filter(x -> x > 0).distinct().sorted().toArray();
for (int i = 0, index = 1; i < B.length; i++, index++) {
if (index != B[i]) {
return index;
}
}
return B.length + 1;
}
}
I am trying to sort a list of numbers from smallest to the biggest and print it. I've tried two things:
1.
public class Sorter {
public static void main(String[] args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
int[] sorted = new int[numbers.length];
for (int a = 0; a < numbers.length; a++) {
int check = 0;
for (int b = 0; b < numbers.length; b++) {
if (numbers[a] < numbers[b]) {
check++;
}
}
sorted[check] = numbers[a];
}
for (int c = numbers.length - 1; c >= 0; c--) {
System.out.print(sorted[c] + ", ");
}
}
}
and this thing works, but won't work with repeated values, so I tried this other thing
public class Sortertwo {
public static void main(String[] args) {
int[] numinput = {3, 2, 1, 4, 7, 3, 17, 5, 2, 2, -2, -4};
int[] numsorted = new int[numinput.length];
int n = 0;
for (; n < numinput.length; ) {
for (int b = 0; b < numinput.length; b++) {
int check = 0;
for (int c = 0; c < numinput.length; c++) {
if (numinput[b] <= numinput[c]) {
check++;
}
}
if (check >= (numinput.length - n) && numinput[b] != 0) {
numsorted[n] = numinput[b];
numinput[b] = 0;
n++;
}
if (n >= (numinput.length)) {
break;
}
}
}
for (int g = 0; g < numinput.length; g++) {
System.out.print(numsorted[g] + ", ");
}
}
}
Where it relies on the thing that once the number from the first array is used (the smallest one is found), it has to be ignored when the program goes through the array next time around.
I tried to assign it like null value, but it doesn't work, so I assigned it to zero and then ignore it, which is a problem, because the list cant have a zero in it.
Is there any like better way to go about it? Thanks.
You can always use:
Arrays.sort(numbers);
If you want to use your first method then change this:
if (numbers[a] < numbers[b])
{
check++;
}
to:
if (numbers[a] <= numbers[b])
{
check++;
}
Unless this is homework, using Arrays.sort as the comments suggest, should be the way to go
import java.util.Arrays;
public class S {
public static void main(String ... args) {
int[] numbers = {1, 3, 8, 2, 5, -2, 0, 7, 15};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
Prints:
[-2, 0, 1, 2, 3, 5, 7, 8, 15]
I keep getting an out of bounds error whenever i try to run my code. Does anyone know what is wrong with it? I can't seem to figure it out.
public class Swapper{
/**
This method swaps the first and second half of the given array.
#param values an array
*/
public void swapFirstAndSecondHalf(int[] values) {
// your work here
int[] first = new int[values.length/2];
int[] second = new int[values.length/2];
for(int i = 0; i < values.length / 2; i++) {
second[i] = values[i];
}
for (int j = values.length / 2; j < values.length; j++) {
first[j] = values[j];
}
for(int k = 0; k < values.length / 2; k++) {
values[k] = first[k];
}
for(int l = values.length / 2; l < values.length; l++) {
values[l] = second[l];
}
}
// This method is used to check your work
public int[] check(int[] values) {
swapFirstAndSecondHalf(values);
return values;
}
}
int[] first = new int[values.length/2];
So indexes [0..values.length/2 - 1] are valid for first.
for (int j=values.length/2; j<values.length; j++)
{
first[j] = values[j];
}
So with the first value of j being values.length/2, it's already out of bounds.
You need to practice debugging, placing a break point and tracing the code as it executes.
You could have used System.arraycopy() instead of all the for looping.
public static void main(String[] args) throws Exception {
int[] values = {1, 2, 3, 4, 5};
values = swapFirstAndSecondHalf(values);
System.out.println(Arrays.toString(values));
values = new int[]{1, 2, 3, 4, 5, 6};
values = swapFirstAndSecondHalf(values);
System.out.println(Arrays.toString(values));
}
public static int[] swapFirstAndSecondHalf(int[] values) {
boolean evenSize = values.length % 2 == 0;
int half = values.length / 2;
int[] swapper = new int[values.length];
System.arraycopy(values, evenSize ? half : half + 1, swapper, 0, half);
System.arraycopy(values, 0, swapper, evenSize ? half : half + 1, half);
// The middle number stays the middle number
if (!evenSize) {
swapper[half] = values[half];
}
return swapper;
}
Results:
[4, 5, 3, 1, 2]
[4, 5, 6, 1, 2, 3]
If you're wanting the middle number, for an odd sized array, to be part of the second half then the swapFirstAndSecondHalf() would look like this:
public static int[] swapFirstAndSecondHalf(int[] values) {
boolean evenSize = values.length % 2 == 0;
int half = values.length / 2;
int[] swapper = new int[values.length];
System.arraycopy(values, half, swapper, 0, evenSize ? half : half + 1);
System.arraycopy(values, 0, swapper, evenSize ? half : half + 1, half);
return swapper;
}
Results:
[4, 5, 3, 1, 2]
[4, 5, 6, 1, 2, 3]
Allocating new arrays is a waste of space. Just swap the halves in-place:
public static void swapFirstAndSecondHalf(int[] values) {
final int len = values.length / 2;
final int offset = values.length - len;
for (int i = 0; i < len; i++) {
int temp = values[i];
values[i] = values[offset + i];
values[offset + i] = temp;
}
}
The code allows odd length, and will leave center value alone.
My following code does the randomization of an array, however, I am wondering if I want to group first two or three elements together always, how should I proceed?
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i=1;i<=11;i++)
{
numbers.add(i);
}
Collections.shuffle(numbers);
for (Integer nums : numbers)
System.out.println(nums);
Example Output: 5, 7, 4, 11, 2, 3, 1, 9, 6, 8, 10
(Note that the sequence '1,2,3' is randomized within the main array.)
Something like this maybe:
final int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
final int iterations = 10;
final int groupOf = 3;
for (int i = 0; i < array.length; i += groupOf) {
int groupOfRemainder = array.length - i < groupOf ? array.length - i : groupOf;
for (int j = 0; j < iterations; j++) {
int rnd1 = Math.random() * groupOfRemainder;
int rnd2 = Math.random() * groupOfRemainder;
Object temp = array[i + rnd1];
array[i + rnd1] = array[i + rnd2];
array[i + rnd2] = temp;
}
}
public static void shuffleKeepingFirstRTogether(List<Integer> list, int r) {
int size = list.size();
Collections.shuffle(list.subList(0, r));
Collections.shuffle(list.subList(r, size));
Collections.rotate(list, new Random().nextInt(size - r));
}