How to convert for loop into streams? - java

How would I use streams to achieve the same result as below? I am trying to find the average of this 'tot' value by first iterating through TickQueue (a queue implementation) and summing tot, and then afterwards dividing by the counter value to find the average.
int counter = 0;
double tot = 0;
for (Tick t: TickQueue)
{
if ((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0))
{
tot += 0;
}
else
{
tot += (t.getAskPrice() - t.getBidPrice());
counter++;
}
}
double avg = tot/counter;

Use a DoubleStream for sum/average/count:
double avg = tickQueue.stream()
.filter(t -> t.getAskPrice() != 0 && t.getBidPrice() != 0)
.mapToDouble(t -> t.getAskPrice() - t.getBidPrice())
.average()
.orElse(0.0);

TickQueue.stream().
filter(t -> !((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0)).
forEach(t -> {
tot += (t.getAskPrice() - t.getBidPrice());
counter++;
});
You first filter out the values where ((t.getAskPrice() == 0 && t.getBidPrice() == 0) || (t.getAskPrice() == 0) || (t.getBidPrice() == 0)), and then for the remaining values calculate tot and counter.

Related

Search algorithm optimization

The code "works", but I'm having problems with optimization.
Algorithms idea is count the number of ways you can navigate n × n grid starting from the top left corner, always moving one step to the left, right, up or down, visiting each square. For example, when n = 3, there are 8 possible paths.
For example the algorithm gets unbearably slow with p.count(7), any hints/tips?
public class Paths {
static int[][] grid;
static int n,counter;
public int count(int n) {
grid = new int[n][n];
counter = 0;
search(0,0,1,n);
return counter;
}
void search(int y, int x, int k, int n) {
if (y < 0 || x < 0 || y >= n || x >= n) return;
if (grid[y][x] != 0) return;
if (x-1 > 0 && x+1 < n && y == n && grid[y][x-1] == 0 && grid[y][x+1] == 0) return;
else if (x-1 > 0 && x+1 < n && y == 0 && grid[y][x-1] == 0 && grid[y][x+1] == 0) return;
else if (y-1 > 0 && y+1 < n && x == n && grid[y-1][x] == 0 && grid[y+1][x] == 0) return;
else if (y-1 > 0 && y+1 < n && x == 0 && grid[y-1][x] == 0 && grid[y+1][x] == 0) return;
else if (y==n && x==n && grid[y][x-1] == 0 && grid[y-1][x] == 0) return;
else if (y==n && x==0 && grid[y-1][x] == 0 && grid[y][x+1] == 0) return;
else if (y==0 && x==n && grid[y+1][x] == 0 && grid[y][x-1] == 0) return;
if (k == n*n) {
counter++;
return;
}
grid[y][x] = k;
search(y,x-1,k+1,n);
search(y,x+1,k+1,n);
search(y+1,x,k+1,n);
search(y-1,x,k+1,n);
grid[y][x] = 0;
}
}
Output:
public static void main(String[] args) {
Paths p = new Paths();
System.out.println(p.count(1)); // 1
System.out.println(p.count(2)); // 2
System.out.println(p.count(3)); // 8
System.out.println(p.count(4)); // 52
}
}

I'm facing an issue with control structures

My problem is with output of my code. When I enter 20, the output must be weird, but I am getting not weird. Same with the value 18.
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 2 && n >= 5){
ans="Not weird";
} else if(n <= 6 && n >= 20){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
the output must be weird,but i am getting not weird
Because, if(n%2 == 1) return false and fall to else block where
if(n <= 2 && n >= 5) is `false`
and
else if(n <= 6 && n >= 20) is also `false`
So, again falls to else block. You probably change
if(n <= 2 && n >= 5)
to
if(n >= 2 && n <= 5)
and
else if(n <= 6 && n >= 20)
to
else if(n >= 6 && n <= 20)
Otherwise, they will never be true and always falls to else.
In your program last else is being executed. Change && (logical AND) to || (logical OR) which will check if number is less than something OR higher than something, instead of checking if something is less or equal 5 AND higher or equal to 20 in the same time as it doesn't have a possibility to evaluate in any case.
I have come up with two solutions and also i see a flaw:
1. if(n%2 == 1) this code can be altered to if(n%2 == 0)
2. The flaw is **(n <= 2 && n >= 5)** . No number can be <2 and >5 at the same time. Try changing that to (n <= 2 || n >= 5) and same goes for (n <= 6 && n >= 20)
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 6 || n >= 20){
ans="Not weird";
} else if(n <= 2 || n >= 5){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}

Why doesn't this code work? FizzBuzz JAVA

I cant get "FizzBuzz". No matter what the input, the "FizzBuzz" code isn't running. What did I do wrong?
public String[] fizzBuzz(int start, int end) {
int diff = end-start;
String[] array = new String[diff];
for (int i = 0; i < diff; i++) {
if (start%3 == 0 && start%5 == 0) array[i] = "FizzBuzz";
if (start%3 == 0 || start%5 == 0) {
if (start%3 == 0) array[i] = "Fizz";
if (start%5 == 0) array[i] = "Buzz";
}
else {
array[i] = String.valueOf(start);
}
start++;
}
return array;
}
Logic in your if statements is a bit busted, using your code as the starting point, you'd have to do something like this.
if (start%3 == 0 && start%5 == 0) {
array[i] = "FizzBuzz";
}
else if (start%3 == 0 || start%5 == 0) {
if (start%3 == 0) array[i] = "Fizz";
if (start%5 == 0) array[i] = "Buzz";
}
else {
array[i] = String.valueOf(start);
}
String s = "" + i;
if ((i % 3) == 0) {
s += " Fizz";
}
if ((i % 5) == 0) {
s+= " Buzz";
}
System.out.println(s);
This code snippet placed in a loop will print Fizz, Buzz and Fizz Buzz on i divisible by 3, 5 and 15 respectively.
you should try this.
class FizzBuzz{
public static void main(String args[]){
int n = 100;
for(int i=0;i<=n;i++){
if((i % 3) == 0 && (i % 5) != 0){
System.out.println("Fizz");
}
else if((i % 5) == 0 && (i % 3) != 0){
System.out.println("Buzz");
}else if((i % 3) == 0 && (i % 5) == 0){
System.out.println("FizzBuzz");
}else{
System.out.println(""+i);
}
}
}
}

Missing Return Statement Error java

public String getValue(int n)
{
if (n % ham == 0 || n % spam==0)
{
if(n % ham == 0 && n % spam == 0)
{
return "hamspam";
}
else if(n % ham == 0 && n % spam != 0)
{
return "ham";
}
else if(n % ham != 0 && n % spam==0)
{
return "spam";
}
}
else
{
return Integer.toString(n);
}
}
Logically, we may conclude that if n is a multiple of ham or of spam, then either n is a multiple of both, or of exactly one of the two. We can logically conclude that there is no way that inside the outer if, at least one of the 3 conditions inside will be true and a return will be executed.
But the Java compiler is not that smart. It just sees no return past the last else if in the block, and concludes that there is an execution path that doesn't have a return, so it gives the compilation error.
Logically, if the first 2 conditions are false, given the outer if, the third condition must be true.
Replace
else if(n % ham != 0 && n % spam==0)
with
else
It is logically equivalent, and the compiler will also be satisfied that every execution path has a return statement.
public String getValue(int n)
{
if (n % ham == 0 || n % spam==0)
{
if(n % ham == 0 && n % spam == 0)
{
return "hamspam";
}
else if(n % ham == 0 && n % spam != 0)
{
return "ham";
}
else if(n % ham != 0 && n % spam==0)
{
return "spam";
}
// this return is missing
return "something";
}
else
{
return Integer.toString(n);
}
}
In your first if statement, you need an else clause or a return value.
To elaborate, what if:
if (n % ham == 0 || n % spam==0) //is true
if(n % ham == 0 && n % spam == 0) // is false
{
return "hamspam";
}
else if(n % ham == 0 && n % spam != 0) //is false
{
return "ham";
}
else if(n % ham != 0 && n % spam==0)//is false
{
return "spam";
}

Add binary values with points without shortcut [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have got a school project to add 2 binary numbers in java. The binary numbers can also have decimal values.
Example - 10.01 + 10.01 = 100.1
I cannot use short cuts like Integer.parseInt(str,radix); (These projects really suck)... :'(
I just have to use strings and stuff. I tried the following code but I am getting lost in the mid and especially to overcome the decimal factor is becoming next to impossible for me:-
String a = "101";
String b = "101";
for(int i=0;i<a.length() || i<b.length();i++){
int digit1 = Integer.parseInt(a.substring(a.length()-1));
int digit2 = Integer.parseInt(b.substring(b.length()-1));
if(digit1 == 0 && digit2 ==0 && carry == 0) {sum = 0;carry = 0;}
if(digit1 == 0 && digit2 ==1 && carry == 0) {sum = 1;carry = 0;}
if(digit1 == 1 && digit2 ==0 && carry == 0) {sum = 1;carry = 0;}
if(digit1 == 1 && digit2 ==1 && carry == 0) {sum = 0;carry = 1;}
if(digit1 == 0 && digit2 ==0 && carry == 1) {sum = 1;carry = 0;}
if(digit1 == 0 && digit2 ==1 && carry == 1) {sum = 0;carry = 1;}
if(digit1 == 1 && digit2 ==0 && carry == 1) {sum = 0;carry = 1;}
if(digit1 == 1 && digit2 ==1 && carry == 1) {sum = 1;carry = 1;}
...//could not continue further
Please help me...I am stuck very badly. Any help will be gladly appreciated! :)
This is the working code:
Note: I have just shown you how to add thses numbers. IF your 1st binary number has (say) 4 digits and 2nd binary number has (say) 10 digits then obviously this code won't work!you have to check that condition and add respective code.I have assumed that both numbers have same digits.
Also note the change in for loop conditions!
public class ADDBinary {
public static void main(String[] args) {
// TODO Auto-generated method stub
String num1 = "1101";
String num2 = "1010";
String sum = "";
int carry = 0;
for (int i = 0; i < num1.length() && i < num2.length(); i++) {
System.out.println("In for loop");
char digit1, digit2;
digit1 = num1.charAt(num1.length() - i - 1);
digit2 = num2.charAt(num2.length() - i - 1);
System.out.println("Digits="+digit1+digit2);
if (digit1 == '0' && digit2 == '0' && carry == 0) {
sum = sum + "0";
carry = 0;
} else if (digit1 == '0' && digit2 == '1' && carry == 0) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '1' && digit2 == '0' && carry == 0) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '1' && digit2 == '1' && carry == 0) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '0' && digit2 == '0' && carry == 1) {
sum = sum + "1";
carry = 0;
} else if (digit1 == '0' && digit2 == '1' && carry == 1) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '1' && digit2 == '0' && carry == 1) {
sum = sum + "0";
carry = 1;
} else if (digit1 == '1' && digit2 == '1' && carry == 1) {
sum = sum + "1";
carry = 1;
}
}
if(carry == 1)
sum = sum + "1";
System.out.println(new StringBuilder(sum).reverse().toString());
}
}
I have used same conditions!
First of all, some tips.
Looking at your code, I can see eight if's with the same format. This is called code duplication and it is to be avoided. You are basically typing the same lines over and over again, which is more work for you and makes your code less readable, adaptable and maintanable. If you encounter something that needs to be done multiple times, in slightly different ways, make a new method that does that thing.
You say they can have decimal values. That's not really good terminology, decimal implies base10. Radix point is what we call the decimal point in base10, but since we're working with base2, decimal doesn't apply, so we call it radix point instead.
As for your question:
(Deleted this because NullPointer beat me to it.)

Categories