What does this method return? - java

I have just started learning to program. I was wondering what this method returns:
public int doSomething(int size) {
int[] b = new int [size];
int c = 0;
for (int d : b) {
c = c + d;
}
return c;
}

There is nothing adding in the array and the c value is still zero.
You might confused with the line
for (int d : b) {
That is java for each loop.

Two crucial things:
int[] b = new int [size]; will initialise every element in the array to zero.
for (int d : b) notation iterates over every element in the array.
So the computation is summing the elements of the array with answer zero.
(Note that in C and C++ arrays elements are not initialised to zero and the behaviour of a similar construct in those languages would be undefined).

The cycle accumulates the sum of the values in the array b into the variable c. As an integer is set to 0 by default and you never change the values of the elements in b, the sum of size zeros is still zero and thus c is 0 when it is returned.

You have blank array - default zeros as it is int array - So currently it is returning zero. Add some numbers in array you will get their addition in returned c.
public int doSomething(int size) {
int[] b = new int [size];
b[0]=5; // add integers like this to get non zero return
b[1]=8;
.
.
b[size-1]=3;
int c = 0;
for (int d : b) {
c = c + d;
}
return c;
}

Related

Why does my code not work? It passed the base case but after that it got stuck. The Question is "Non Repeating Numbers" on GFG

The Approach I took was I first used bit manipulation to find that first element which was unique in the variable "c", then i used another array to copy the elements of the original array, but without the repeating element, and then used the bit manipulation method again to find the 2nd unique element in "C1".After that since I needed to return an array i added both values to the array "a" and returned it.
class Solution
{
public int[] singleNumber(int[] nums)
{
int a[]=new int[2];
int c=0,c1=0;
for(int i1:nums)
c=c^nums[i1];
a[0]=c;
int b[]=new int[nums.length-1];
for (int i = 0, k = 0; i < nums.length; i++) {
if (nums[i] == c) {
continue;
}
b[k++] = nums[i];
}
for(int i2:b)
c1=c1^b[i2];
a[1]=c1;
return a;
}
}
This is the link for the Question
There are two problems:
expected space complexity is O(1), your is O(N)
as mentioned by #Haoliang: the result of xoring all elements is a ^ b (the xor of the two missing elements) and not one of the answers (a or b), so your logic doesn't work
Here is how you can solve it:
xor all elements => a ^ b
find a bit that is 1 in a ^ b (there has to be a bit that is one if a != b which is the case)
xor all numbers that have that bit set and all number that have that bit not set, this will give you a and b
public int[] solve (int[] arr) {
int xor = 0, a = 0, b = 0;
for (int x : arr)
xor ^= x;
int mask = 1;
while ((mask & xor) == 0)
mask <<= 1;
for (int x : arr) {
if ((mask & x) == 0)
a ^= x;
else
b ^= x;
}
return a < b ? new int[] {a, b} : new int[] {b, a};
}

How can I return the FIbonacci sequence using an int return type method without using recursion?

I'm trying to create a method in Java that prints the fib series up to the number passed to the method. My issue is that I'm required to use an int return type to return the series and I cannot use recursion.
My First Idea
My original idea was like shown. Which works just fine. It takes an argument of type int and returns void simply printing the numbers as they are calculated.
public void fibonacci(int num) {
int a = 0;
int b = 0;
int c = 1;
for (int i = 0; i < num; i++) {
a = b;
b = c;
c = a + b;
System.out.print(c + ", ");
}
}
What The Question Asks For
The code below shows what I was tasked to do. It asked for a method that takes an argument of type int and returns type int.
public int fibonacci(int num) {
//some code...
return x; //This is what confuses me. I know this isn't right.
}
To me this just seems impractical and maybe even impossible to use an int return type. I'm wondering if anyone knows a way this is possible.
Expected Output:
//Method call in driver class.
fibonacci(5);
//This would print to console.
1, 1, 2, 3, 5
You can use the equation [(h)^a - (j)^a] * [1/sqrt(5)].
'a' is fibonacci number wanted
'h' is [1 + sqrt(5)] / 2
'j' is [1 - sqrt(5)] / 2
public static int returnFibonacci(int a) {
double firstTerm; // calculate h
double secondTerm; //calculate j
double fib; //calculate 1/sqrt(5) with firstTerm and secondTerm
}

Swapping references in an Array [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
Ok, I was misunderstanding the problem. After reading it a couple of times I figured out randInt is actually the method itself i am using to populate the array. So when it says to call randInt its some sort of recursive call I think. This is somehow what it should look like:
static int[] randInt(int i, int j) {
int[] temp = new int[(j - i) + 1];
for ( i = 0; i < j; i++) {
temp[i] = i + 1; // here i populate the array
}
System.out.println(Arrays.toString(temp)); // this prints [1, 2, 3, 4, 5]
for ( i = 1; i < j;i++){
swapReferences(temp[i], temp[randInt(0,i)] ); //this is some sort of recursive call that swaps the references
// btw that statement does not compile, how can i pass a method as a parameter?
}
return temp;
}
static void swapReferences(int a, int b) { //these parameters are wrong, need to be changed
//Method to swap references
}
Sorry for the confusion, but I think thats how it should be correctly.
Java is pass-by-value, so reassigning the parameters as you try to do will not work.
What you need to do is to have the array itself and two integer indices as parameters:
int randInt = generate.nextInt(j-i) + 1; //this is gonna generate a # within the range of the array (so if array is size 5, generates something 1-5)
for ( i = 1; i < j;i++){
swapReferences(temp, i, randInt); //and this is my attempt at swapping the references
randInt = generate.nextInt(i) + 1 ;
}
static void swapReferences(int[] array, int a, int b){
int x = array[a];
array[a] = array[b];
array[b] = x;
}
You can mutate parameters such as arrays passed into a method, as is being done here, but you can't reassign the parameters themselves.
You are just changing the ints that a and b are pointing to, but not what the indicies the array is pointing to. You need to change your swapReferences method to take the array as input, and something like the indicies to swap
static void swapReferences(int[] arr, int indexA, int index B){
int x = arr[indexA];
a = arr[indexB];
b = x;
arr[indexA] = a;
arr[indexB] = b;
}
or
static void swapReferences(int[] arr, int indexA, int indexB){
int x = arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] = x;
}

Merge sort remove duplicates

I am trying to sort an array via merge sort, and while sorting, remove elements that I have deemed equal. I am recursively calling merge sort and then merging.
I get to this point and find that a and c are duplicates.
a b | c d
I determine which one I want based on certain criteria and I pick c. I increment the right hand counter and and the left hand counter and compare b and d. Say I pick d, then I pick b. I want my final list to only have the elements
c d b
However, what is happening is on the next recursive call, start and end are 0 and 3 so d is listed twice in the array on the next call. The array that the merge procedure works with is:
c d b d
Here is the code. Thanks in advance.
private static void merge(int[] data, int start, int mid, int end)
{
int firstCopied=0;
int secondCopied=0;
int index=0;
int length=end-start+1;
int[] temp = new int[end-start+1];
int firstSize=mid-start+1;
int secondSize=end-mid;
while(firstCopied < firstSize && secondCopied < secondSize)
{
if(data[start+firstCopied] < data[mid+1+secondCopied])
{
temp[index++] = data[start+firstCopied];
firstCopied++;
}
else if(data[start+firstCopied] > data[mid+1+secondCopied])
{
temp[index++] = data[mid+1+secondCopied];
secondCopied++;
}
else if(data[start+firstCopied]==data[mid+1+secondCopied])
{
boolean result = PickOne();
if(result)
{
temp[index++] = data[start+firstCopied];
}
else
{
temp[index++] = data[mid+1+secondCopied];
}
firstCopied++;
secondCopied++;
length--;
}
}
while(firstCopied < firstSize)
{
temp[index++] = data[start+firstCopied];
firstCopied++;
}
while(secondCopied < secondSize)
{
temp[index++] = data[mid+1+secondCopied];
secondCopied++;
}
for(int i=0; i<length; i++)
{
data[start+i]=temp[i];
}
}
The philosophy of the C++ Standard Library is to use algorithms that do one thing well. It's best to follow that approach since it will lead to more reusable code.
E.g. here's a mergesort sketch followed by a call to std::unique
template<typename BiDirIt>
void merge_sort(BiDirIt first, BiDirIt last)
{
auto const N = std::distance(first, last);
if (N < 2) return;
// sort each part individually, then merge back in-place
auto middle = first + N / 2;
merge_sort(first, middle);
merge_sort(middle, last);
std::inplace_merge(first, middle, last);
}
int data[] = { /* your data */ };
merge_sort(std::begin(data), std::end(data));
auto it = std::unique(std::begin(data), std::end(data));
for (auto ut = std::begin(data); ut != it; ++ut) {
// process unique data
}
If your data was in a std::vector instead of a C-array, you could call v.erase(v.begin(), it); to actually erase the non-unique data as well.
Your merge conceptually changes the length of the array. But there is no code to actually truncate data. I suggest you return length (instead of void) and use some final postprocessing step to either truncate the data to the final length, or at least avoid printing those past-the-end elements.
Make sure the elements in [start, mid] and [mid + 1, end] is sorted and unique, first.
Otherwise, duplicates will exists after your code run.

writing a method for fibonacci sequence

I'm trying to write a for loop that calls the method fibonacci and prints the first 25 numbers in the fibonacci sequence. The problem is I'm a little confused about how to do that correctly. I'm a little confused about when the for loop in the run method calls the fibonacci method do the values inside the fibonacci method reset after reach pass of the for loop? So for example during the first pass of the for loop i = 0 and the values for int a and int b change inside the the fibonacci method. Do the values inside the fibonacci method reset on the next pass of the for loop?
import acm.program.*;
public class Fibonacci extends ConsoleProgram{
private void run(){
for(int i = 0; i <= 25; i++){
fibonacci(i);
println(fibonacci(i));
}
}
private int fibonacci(int n){
int n = 0;
int a = 0;
int b = 1;
while (n < 25);
int c = a + b;
a = b;
b = c;
}
return(a);
}
You're looping in two different places - run() and fibonacci(). Only one of these places should care about the loop, and the other should care about computing Fibonacci(n).
What we can do remove the loop from fibonacci, and only rely on the loop on the outside. Also, we're going to remove that statement int n = 0, since that shadows the parameter you're passing in.
Lastly, we're going to create two new static variables a and b, so that the values of those are preserved with this instance. If you don't do that, then you'd have to rely on either recursion or some other methodology to provide the appropriate values of a and b.
I'm not entirely sure why you need to extend ConsoleProgram, but I'll leave it in for now.
So, here's what it should look like.
public class Fibonacci extends ConsoleProgram {
static int a = 0;
static int b = 1;
public void run() {
for(int i = 0; i <= 25; i++) {
// Print the call to fibonacci(i) with every iteration.
}
}
private int fibonacci(int n) {
int c = a + b;
a = b;
b = c;
return c;
}
}
Fibonacci it's a typical example of an algorithm that can be easily approached with recursion, that's because:
you can divide the entire fibonacci sequence in steps,
in each step you have to do the same thing except for the final step where you got 0,
and the last step is "special" because 0 times any number gives you 0,
so if you apply the same step as before you simply nullify everything, this means that when your counter is 0 you have to do something different from your previous steps and it's:
multiply the result that you have stored by 1 and not by 0 ( or you can leave it as it is, it's the same thing as multiply by 1
exit the loop and terminate the fibonacci sequence
Internet is full of Fibonacci examples, 1 & 2 are more than enough for you.
The variables reset for each iteration of the loop. The variables a, b, and c are local variables that only "live" within the method. Every call to the fibonacci(n) method should start from the beginning of the fibonacci sequence and print out the terms up until the nth term. Therefore, while (n < 25); should not be part of the method. Also, int n = 0 resets n to zero, which is bad because we need to know what n is to get the nth term.
The ideal way to do this loop is:
private void fibonacci(int n) {
int i = 1; // a new variable i to count from the 1st term
int a = 0; // the first term
int b = 1; // the second term
while (i <= n) {
int c = a + b; // the new value for b
a = b; // switch the old a for the new a
b = c; // get the (i + 1)th term for the next iteration
System.out.println(a); // print out the ith term
i++;
}
}
You are not storing the returned int value of fibonacci();
int currentSum=0;
for(int i = 0; i <= 25; i++){
currentSum+=fibonacci(i);
println(currentSum);
}
and why do you have another variable n in your fibonacci(int n) ?
Please make sure first your fibonacci method is working. (The infinite while loop, etc.)
public static void main (String args[]){
for(int i = 0; i<25; i++) {
System.out.println(fibonacci(i));
}
}
static int fibonacci(int n){
if(n==0) {
return 0;
}
int a = 0;
int b = 1;
for(int i = 0; i < n; i++){
int temp = b;
b += a;
a = temp;
}
return(b);
}

Categories

Resources