array, integers and sum of array - java

Problem: Write a method that takes two integers n and m as parameters, and return the sum of alle the numbers (array of numbers) from n (including n) to m (including m).
public int getSum(int n, int m){
this.n = n;
this.m = m;
int [] x = {n,m};
int result = 0;
for(int i=0; i<x.length; i++){
result += x[i];
}
return result;
}
if n=1 and m=4 the method returns 5, but the method need to return 10, (1,2,3,4)=(1+2+3+4).
Guess this line is not right
int [] x = {n,m};
since the array will be {1,4} if n=1 and m=4. How to fix this, need to create the array {1,2,3,4} if n=1 and m=4

try this:
public int getSum(int n, int m){
int result = 0;
for(int i = n;i <= m;i++)
result += i;
return result;
}
or this:
public int getSum(int n, int m){
int result = 0;
while(n <= m)
result += n++;
return result;
}
or maybe with funny math:
public int getSum(int n, int m){
return (m*(m+1)/2) - ((n-1)*((n-1)+1)/2)
}
F(n) = (n*(n+1)/2) = 0+1+2+...+n
F(m) - F(n-1) = n + n+1 + n+2 + ... + m

Java 8
return IntStream.rangeClosed(n, m).sum();

#Andres has already given a perfect solution. But I wanted to explain some more, so here goes.
There are many problems with your code.
But yes, the central problem is the line. int [] x = {n,m};
What that line does is creates an array of just 2 numbers, and when you iterate over that array you are only adding those two numbers, not all the number in between.
In languages like C, C++, Java, etc... the simplest idiom to iterate over a range of numbers is
for(int i = n, i <=m, i++){
...
}
What this does is, create a temporary variable i and initialize it to the first number in the range n. And then run in the loop incrementing that temporary number i by one every time until it exceeds the last number of the range m.
Within the body of the loop each number of the range will now be available, for that iteration of the loop.
So in your case where you are summing up all the numbers, you can accumulate all those numbers in the range by setting up an accumulator variable like following.
int acc = 0;
for(int i = n, i <=m, i++){
acc = acc + i;
}

can't you just do this :
public static int getSum(final int n, final int m) {
// default value
int sum = 0;
// not permitted
if (n >= m)
return 0;
// all of the work here
for (int i = n; i <= m; i++)
sum += i;
return sum;
}

Related

rotate the elements of the given array k times to the right

I have made this code to rotate an array by k times. In this when I'm adding i=0 , it is showing an "ArrayOutOfBounds" exception, and when I'm changing the value of i by 1, it is showing wrong output. Why is it showing this exception? And is there any way I could correct this code?
public void rotate(int[] nums, int k)
{ int j=0, temp=0;
for(j=0;j<k;j++)
{
for(int i=0;i<nums.length;i++)
{
temp=nums[i-1];
nums[i-1]=nums[i];
nums[i]=temp;
}
}
}
}
At i=0 you are trying to access nums[i-1] = num[-1] which is an invalid position and hence an ArrayOutOfBound exception is thrown.
So, the modified version would be:
for (j=0; j<k; j++)
{
for (int i=1;i<nums.length;i++)
{
temp=nums[i-1];
nums[i-1]=nums[i];
nums[i]=temp;
}
}
But the above will rotate the array by k times towards the left not right as you are shifting the elements towards the left. So, to get the right rotation you need to shift the elements from the end of the array. Like:
for (j=0; j<k; j++)
{
for (int i=nums.length-1; 0<i; i--)
{
// shifting towards the right
temp=nums[i-1];
nums[i-1]=nums[i];
nums[i]=temp;
}
}
Edit (from comments above): If i is 0, you're trying to get an index of -1 which will raise an ArrayOutOfBounds exception. If i starts from 1, then you're not dealing with the first number.
Here's the function you can use to rotate integers to the right:
public void rotate(int[] nums, int k) {
int arrLen = nums.length;
// If the number of times you want to rotate is bigger than the size of the array, get the minimum number of rotations to get the same result.
while (k > n) {
k = k - arrLen;
}
k = arrLen - k;
k = k % arrLen;
int i, m, n, temp;
int g_c_d = gcd(k, arrLen);
// Move the value in the i-th index
for (i = 0; i < g_c_d; i++) {
temp = arr[i];
m = i;
while (true) {
n = m + k;
if (n >= arrLen) {
n = n - arrLen;
}
if (n == i) {
break;
}
arr[m] = arr[n];
m = n;
}
arr[m] = temp;
}
}
// Find the greatest common divisor of two numbers, a and b
public void gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
Let me briefly explain what it does. This is one of the most known algorithms: juggling. You divide the array into the n number of sets where n denotes the greatest common divisor of the length of the array and the number of times you want to rotate. Then, you move the numbers within sets.
This might be the most efficient in terms of time (as its time complexity is O(n)).
A better solution would be taking a copy of the given array with the values '0' then looping through the given array to obtain a new_index.
Formula for the New_index for the Clock-wise rotating array:
for(int i=0;i<nums.length;i++){
int new_index = (old_index+k)%(a.length)
copy[new_index] = a[old_index]
}
Now the entire function code would be:
public static void rotate(int[] a, int k)
{
int n = a.length;
int[] copy = new int[n];
// fill the values with zeroes
for(int i=0;i<n;i++){
copy[i]=0;
}
// rotate the array
for(int i=0;i<n;i++){
int new_index = (i+k)%n;
copy[new_index] = a[i];
}
// Now that the array is copied, copy the elements to the original array. Because they asked to rotate the given array.
for(int i=0;i<n;i++){
a[i]=copy[i];
}
}
function solution(arr, k) {
if(k == 0) return arr;
if(arr.length == k) return arr;
if(arr !== undefined && arr !== null){
let counter = k > arr.length ? k % arr.length : k;
let rotArray = [];
rotArray = arr.slice(arr.length - counter, arr.length).concat(arr.slice(0,arr.length - counter))
return rotArray;
}
return arr;
}

How can I use this for loop to correctly print the closest K integers to X?

public static int[] sortArray(int[] arr) {
Arrays.sort(arr);
return arr;
}
public static int findElement(int[] arr, int x) {
int start = 0;
int end = arr.length;
int mid = 0;
while (start <= end) {
mid = (start + end)/2;
if (arr[mid] == x) {
return x;
}
else if (x <= arr[mid]) {
end = mid - 1;
}
else {
start = mid + 1;
}
}
return mid;
}
public static void printKclosest(int arr[], int x, int k)
{
int element = findElement(arr, x);
int count = 0;
for (int i = 0; i < arr.length; i++) {
int difference = Math.abs(arr[i] - element);
while (count < k) {
if (difference > 0) {
System.out.println(arr[i]);
count++;
}
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] array = {-1, 3, 5, 2, 1, 7};
sortArray(array);
System.out.println(Arrays.toString(array));
printKclosest(array, 2, 3);
}
}
for find the k nearest elements, i was thinking I could use a for loop to go through each element in the array and subtract from the element that's X and print the number of k elements that have the smallest difference, but the output I'm getting is -1 k amount of times.
function findElement returns x value if x exists but index of potential place for x if it does not present in array.
So in the second case your comparison int difference = Math.abs(arr[i] - element); has no sense
How to overcome: change in findElement
int end = arr.length - 1;
return x;
to
return mid;
and
difference = Math.abs(arr[i] - arr[element]);
But approach to get k closest numbers is completely wrong. Suggestion:
Set L index to element and R index to element+1
Compare abs differences for L and R. Output smaller. If smaller is for R, decrement L, otherwise increment R. Repeat k times (don't forget about array range)
In addition to MBo's great suggestion for outputting the k closest elements using L and R pointers, you could also solve this without sorting the array in O(n log k) time by iterating over the array once and keeping the chosen elements in a heap, each time removing the farthest (k+1)th element.

Find "Missing" Integer in a Java Array

Given an array A[] of length n, find a "missing" number k such that:
k is not in A
0<=k<=n
I've seen similar questions asked where the A[] contains numbers 1 to n with one number missing, but in this question, A[] can contain any numbers. I need a solution in O(n) time. For example,
A = {1,2,3} -> 0
A = {0,1,2} -> 3
A = {2,7,4,1,6,0,5,-3} -> 3,8
I've gotten as far as checking if 0 or n are in the array, and if not, return 0 or n, but I cannot seem to think of any other solution. This problem seems considerably more difficult given the fact that A can contain any numbers and not necessarily numbers 1 to n or something like that.
Linearly iterate over the array and "cross out" every number you encounter. Then iterate of that listed of crossed out numbers again and see which one is missing.
public static int getMissingNumber(int[] A)
{
int n = A.length;
boolean[] numbersUsed = new boolean[n + 1]; //Because the definition says 0 <= k <= n, so k = n is also possible.
for(int k = 0; k < n; k++)
{
if(A[k] <= n && A[k] >= 0) //No negative numbers!
numbersUsed[A[k]] = true;
}
for(int k = 0; k <= n; k++)
{
if(numbersUsed[k] == false)
return k;
}
return -1; //nothing found
}
Complexity is 2*n because of the two for loops, giving overall complexity O(n).
Simple approach:
initialize a set with all the values you need. (In your case number 0 to n)
iterate over your arry and remove the number from the set
at the end the set is giving you the missing entries.
If you know that exactly one number is missing, there is a simple solution using xor.
static int missing(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++)
result ^= (i + 1) ^ arr[i];
return result;
}
If there may be more than one number missing you can return a Set like this:
static Set<Integer> missing(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i <= arr.length; i++)
set.add(i);
for (int a : arr)
set.remove(a);
return set;
}
Here is a solution that utilizes one loop. That's if we choose to ignore what Arrays.sort does
import java.util.Arrays;
class Solution {
public int solution(int[] A) {
Arrays.sort(A);
int min = 1;
for (int i = 0; i < A.length; i++){
if(A[i]== min){
min++;
}
}
min = ( min <= 0 ) ? 1:min;
return min;
}
}
class Missing{
public static void main(String[] args) {
int arr[]={1,2,4,5,6,7,9};
System.out.println(missingNumberArray(arr));
}
public static int missingNumberArray(int [] a) {
int result=0;
for(int i=0;i<a.length-1;i++){
if(a[i+1]-a[i]!=1){
result=a[i]+1;
}
}
return result;
}
}
//output:missing element is:3
// missing element is:8

Getting the wrong output? My coding is maybe off?

Well, I am doing a practice problem (preparing for midterm) and I was able to get one of the outputs correct. However, I am having troublesome getting the average input. It ends up at 12.0 instead of 6.5
Here's the prompt question:5.
Complete the following Java program by filling in the bodies of functions sum(), avg(), and ord(). A call to sum(n) should return the sum of all the integers from 1 to n, while avg(n) returns the average of the same set of numbers. A call to the boolean function ord(x, y, z) returns true if x < y< z and false otherwise. The Function main() should produce the following output
Output:
6.5 true false
This is my code:
class Problem5 {
// sum(): return 1+2+3+..+n
static int sum(int n) { //this is given
int sum = 0;
for(int i=0; i<n; i++) {
sum += n;
}
return n;
}
// avg(): return average of {1,2,..,n}
static double avg(int n) { // given
double sum = 0;
for (int i=1; i<n; i++) {
sum +=n;
}
return sum / n;
}
//ord(): return true if and only if x<y<z
static boolean ord(double x, double y, double z){ //given
if (x < y && y <z){
return true;
} else {
return false;
}
}
public static void main (String[]args) {
System.out.println(avg(12));
System.out.println(ord(1.2,3.4,5.6));
System.out.println(ord(3.4,1.2,5.6));
}
}
Overall I am having trouble coding/ filling in the code for static int sum(int) and static double avg(int).
This:
for (int i=1; i<n; i++){
Will skip n. (it will loop on 1...n-1). For 12, the sum will be 11*12/2, which you then divide by 12, resulting in 11/2 = 6.5
Fix it like so:
for (int i = 1; i <= n; i++) {
(or replace the whole loop by return (double) (n+1) / 2.0)
For your sum function, there is the same error, plus the return value is not good:
return n;
Should be
return sum;
And the increment should be sum += i;, not n (you want 1+2+3+4..., not 12+12+12+12...)
Again, you can replace the whole loop by return n * (n + 1) / 2
I assume your teacher would expect you to learn about re usability, and since your 2 loops in sum and in avg are identical, you could write:
public static double avg(int n) {
return (double) sum(n) / n;
}
A sum is just the addition of all the numbers in a certain range:
static int sum(int n) {
int total = 0;
for(int i = 1; i <= n; i++) {
total += i;
}
return total;
}
Average is just the sum of the range divided by the amount of numbers:
static double avg(int n) {
return sum(n) / (double) n;
}

Sum all odd indexes in an array

I have to complete a program according to these instructions:
public class SumOddIndex {
public static void main(String[] args){
int[] array = {1,1,8,4,2,6};
// Call the method sum, receive an integer value, and print the value on output.
// A call passing the example array should result in a value of 11.
// Use a while loop.
}
Here code a method called sum. The method sum should take an int - array as argument and return the sum of all values in all array cells that have an odd index number.
USE A WHILE- LOOP!
}
This is what I have tried so far, but it is not working.
public static void main(String[] args) {
int[] array = {1, 1, 8, 4, 2, 6};
sum(array);
}
public static int sum(int[] y){
int sum = 0;
int i = 0;
while(y.len
public static int sum(int[] y) {
int sum = 0;
int i = 0;
while (y.length%2 == 1) {
//y.length%2 == 1;
sum += y[i];
i++;
}
System.out.println(y[i]);
return i;
}
}
Assuming you are using java, try something like this:
int i = 0;
int sum = 0;
while(i < myArray.length){
sum += myArray[i];
i++;
}
This is a while loop that will execute only as long as your counter variable is less than the size of the array (that way you will never have an index out of bounds). Inside the loop, it will add to the sum the value at the index of the counter.
Don't forget to increment your counter inside the while loop, or you will be stuck inside an infinite loop.
EDIT
I misread your question, but if you only want to sum odd values, try this:
while(i < myArray.length){
if(myArray[i] % 2 == 1){ // If value is odd
sum += myArray[i];
}
i++;
}
EDIT 2
To only sum odd indexes, change the above code to check if your counter is odd instead of the value at that index, like this:
while(i < myArray.length){
if(i % 2 == 1){ // If index is odd
sum += myArray[i];
}
i++;
}
Or, you could start you indexing at 1 and increase by 2 each time. I will only give psuedocode for this one:
// Start counter at 1
// While counter is less than array length
// Add element's value to the sum
// Increment counter by 2
Using Streams in Java 8 you can use IntStream and filter and reduce down to a total sum:
int[] array = {1,1,8,4,2,6};
int sum = IntStream.range(0, array.length).filter(i -> i % 2 == 1).map(i -> array[i]).sum();
I know this question has been answered already, but I thought it would still help out.
int i = 1;
int sum = 0;
while(i < myArray.length)
{
sum += myArray[i];
i += 2;
}
return sum;
I added #Logan Murphy's suggestion for optimization.
Use stream's filter and reduce operation.
int[] array = {1,1,8,4,2,6};
int sum = array.stream().filter(s -> s % 2 != 0).reduce(0, Integer::sum);
A bit optimized approach can be to calculate and store the length of the array in a variable once, instead of calculating it in each iteration.
public int oddIndSum(int [] myArray){
int i = 1;
int sum = 0;
int length = myArray.length;
while(i < length){
if(i % 2 == 1){ // If index is odd then add
sum += myArray[i];
}
i++;
}
return sum;
}

Categories