First time posting on here! So ive searched and searched and cant find an answer. I dont really need a table, just to have that kind of output such as
0 and 0 = 0,
0 and 1 = 1,
and so on...
I need to read from a file that will extract the numbers and they are 0 0..0 1..1 0..1 1
I need to then make the AND, OR, NAND, and NOR "table" for them.
I created an arrayList for them, so i can access them easier. the method i was going to do doesnt work and will take very long lines of code and pretty much be duplicated stuff. Im trying to think of a way to use a loop, but have mental block. can anyone help me please?
heres what im talking about the code i have
int rec3a = Integer.parseInt(list1.get(2));
int rec3b = Integer.parseInt(list1.get(3));
System.out.println("AND:");
if(rec3a == 0 && rec3b == 0)
{
System.out.println("0");
}
if(rec3a == 0 && rec3b == 1)
{
System.out.println("0");
}
if(rec3a == 1 && rec3b == 0)
{
System.out.println("0");
}
if(rec3a == 1 && rec3b == 1)
{
System.out.println("1");
}
}
this doesnt really work for the OR statement either..its just a giant mess lol..any help would be appreciated
You could use the bitwise operators,
int rec3a = 1;
int rec3b = 0;
// AND
System.out.println(rec3a & rec3b);
// OR
System.out.println(rec3a | rec3b);
// NAND
System.out.println((rec3a & rec3b) == 1 ? 0 : 1);
// NOR
System.out.println((rec3a | rec3b) == 1 ? 0 : 1);
Which (in this example) outputs
0
1
1
0
You could simplify this to:
if (rec3a == 1 && rec3b == 1)
{
System.out.println("1");
}
else
{
System.out.println("0");
}
For the OR case it would be:
if (rec3a == 1 || rec3b == 1)
{
System.out.println("1");
}
else
{
System.out.println("0");
}
With Integers 0 and 1, you can use the built in bit-wise operators:
System.out.println(rec3a & rec3b); //AND
System.out.println(rec3A | rec3b); //OR
Related
Currently I am working on a little personal project to help myself learn about coding.
I'm wondering for future reference if I can combine logical operators of different types in a single if statement.
For example if I had
if (n == 0 || n == 1 && m == 0 || m == 1) {
doSomething();
}
Would it check if either parts of the left side are true, then if either parts of the right are true, or would it do something similar to checking if both of the middle ones are true?
Does using parenthesis change anything
For example
if ((n == 0 || n == 1) && (m == 0 || m == 1)) {
doSomething();
}
Edit:
From a suggestion I tried it out, but when i put three variables it started acting weird
Here's my test:
int n = 1;
int m = 1;
int o = 1;
if (n == 0 || n == 1 && m == 0 || m == 1 && o == 0 || o == 1) {
System.out.println("True");
}
else {
System.out.println("False");
}
if ((n == 0 || n == 1) && (m == 0 || m == 1) && (o == 0 || o == 1)) {
System.out.println("True");
}
else {
System.out.println("False");
}
if all of them are 1 or 0, they both evaluate true, if n or m is not 1 or 0 the top evaluates true but the bottom does not.
However if o is not 0 or 1 both of them are false.
I have found that parenthesis do in fact make a difference, but I can't quite tell why it's acting the way it is.
&& has a higher precedence then ||, so n == 0 || n == 1 && m == 0 || m == 1 equals n == 0 || (n == 1 && m == 0) || m == 1. You may check the precedence table here.
Everybody knows that FizzBuzz question that interviewers ask students.
Basically, when you have an incrementor and for each number which is a divisible of 3 you say fizz, for a number divisible by 5 you say buzz, while if it is divisible by both(3 and 5) you say FizzBuzz, hence the name.
It is a relatively easy problem to solve and I have done it, but I think my solution is a bit clunky. This is it:
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if (i % 3 == 0) {
System.out.println("Fizz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println("FizzBuzz");
}
}
But the problem is that when the number is divisible by both 3 and 5 it gives me "Fizz" for some reason. Can somebody explain to me, because I'm new to java programming. Thanks in advance!
The problem lies in the order of your if statements. Lets take a look at the number 15, which is the first number divisible by both 3 and 5. Because of the order in which you have your if statements, the first statement that is checked is
if ( 15 % 3 == 0)
The result of the operation is indeed equal to 0, as 15 is divisible by 3 and so "Fizz" is printed and your else is ignored.
Think about how you should structure the order of your if statements and which additional condition should you introduce to catch the specific case of being divisible by both i % 3 == 0 && i % 5 == 0.
When you enter the if statement and your number is 15 for exemple, you enter the first if statement and.. prints "Fizz" as you stated, because 15 % 3 == 0 returns true. Then it ignores the else.
You want the first if to be
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");*
}
Try this code
public static void main(String[] args) {
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
for (int i : numbers) {
if ((i % 3 == 0) && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else if (i % 3 == 0){
System.out.println("Fizz");
}
}
}
I'm doing a hackernet challenge where n is an int input. The conditions are:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird.
Im sure the code makes logic and dont think theres syntax. It gives the correct responses and hackernet still says its incorrect so ive come here to see if anyone can see what the problem is
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
System.out.print("not weird");
}
}
The problem is the logic in your else condition, which would also catch values of N which are less than 2. Try this version:
if (N % 2 != 0)
{
System.out.print("weird");
}
else if (N >= 2 && N <= 5 || N > 20)
{
System.out.print("not weird");
}
else if (N >= 6 && N <= 20)
{
System.out.print("weird");
}
else
{
// NOTE: if the code still fails, remove this else condition
System.out.print("unexpected value of N");
}
Note: To get your code to pass the Hackernet task, you might have to completely remove the else condition. I added it for completeness, but Hackernet might test N=1 to see if nothing gets printed.
Read this condition :
if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20)
as
if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20))
Then see how operator precedence changes the behaviour and yield desired results.
Check the following one
public static void main(String[] args)
{
int N = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if(N%2!=0) {
System.out.print("weird");
}else if(N>=2 && N<=5) {
System.out.print("not weird");
}else if(N>=6 && N<=20) {
System.out.print("weird");
}else if(N>20) {
System.out.print("not weird");
}
}
For the technical part: start by reading about
precedence of java operators and then make your code easier to read.
Pushing that many conditions into a single if is not helpful. You see it yourself: you think the code is correct, but probably it isn't. And now you look to other people to explain your overly complex code back to you. And of course, all the other answers do all that for you ... but beyond that:
The "real" answer here is: learn how to test your code.
Instead of having a main that somehow asks for a number, and then makes decisions, write a method boolean isWeird() that takes a number and returns true/false according to your requirements.
And then simply test that method with all reasonable cases. And then check if that result is as expected.
Using JUnit, you could write something like
assertThat(isWeird(1), true);
assertThat(isWeird(21), true);
assertThat(isWeird(22), true);
...
Ideally, you write such tests before you implement that method. And then you implement all the conditions, and any check that fails tells you that you got something wrong.
I feel, In the if (N % 2 != 0 || N % 2 == 0 && N >= 6 && N <= 20) condition, you are verifiying the odd and even values at same time using && and || operator. Can you modify the condition into like this if (N % 2 != 0 || (N % 2 == 0 && N >= 6 && N <= 20)) and check? If N is odd weird will be printed or if N is even and it falls under the 6 and 20 inclusive, weird will be printed.
You already have a good few answers here but if you think logically about what you actually need, you can break it down easier.
It looks like the only "Not Weird" print out is 2, 4 and even numbers > 20
So an example could be something like:
if (n % 2 == 0) {
if ((n >= 2 && n <= 5) || (n > 20)) {
return "Not Weird";
}
}
return "Weird";
You can try this
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
if (n % 2 == 1 || (n >= 6 && n <= 20)) {
System.out.println("Weird");
} else {
System.out.println("Not Weird");
}
scanner.close();
}
I'm working on a project at the moment that's building a digitised version of a board game, and i'm having an issue with a while loop thats not doing as i expected.
Basically, if the player has 1 stone left in his/her hand, and the next pit is not empty, they pick up the next pits stones and continue doing so, until the next pit is empty.
Now, my code continues while the next pit is empty and while one stone is remaining in their hand, however, it doesn't pick up the next pits stones if it isn't empty, it just adds one until the next pit is empty.
So my code is almost there, just not quite. So i'm looking for some help to improve the current code (a big comment above the code that needs work).
Let me know if the explanation is poor, i'll do my best to re-write it.
Cheers
while(hand == 1 && pit.next.stones != 0 && pit.next.pit == false) {
int stones = pit.next.stones;
for(int i = stones; i >= 1; i--) {
hand++;
}
while(Hand >= 1 && pit.next.stones != 0) {
hand--;
addPieces(pit.next);
pit = pit.next;
}
}
Rather than having mutli-nested loops. You should probably just update the stones in hand and stones in the pit and let the main loop continue as normal since the main loop is just the main game logic loop: grab stones, drop in pits, grab more stones and repeat?, ???, profit!
Eg:
Instead of:
while(hand >= 1 && pit.next != null) {
// ...
while (hand == 1 && pit.next.stones != 0 && pit.next.pit == false) {
int stones = pit.next.stones;
for (int i = stones; i >= 1; i--) {
hand++;
}
while (hand >= 1 && pit.next.stones != 0) {
hand--;
addPieces(pit.next);
pit = pit.next;
}
}
do something like:
while(hand >= 1 && pit.next != null) {
// ...
if(hand == 1 && pit.next.stones > 0 && pit.next.pit == false) {
// update stones in hand
hand += pit.next;
// update stones in pit
pit.next.stones = 0;
}
// let main loop continue
}
(Note: I'm not 100% on the rules you are going for, just tried to follow what you said)
I was trying to solve Project Euler problem 10 using python, but my program gave a wrong result. Since I am a complete noob to python and I could not find any fault in my (apparently brute-force) logic, I wrote a program in java (almost translated it), and it gave a different result, which turned out to be right.
Here is the python code:
from math import *
limit = 2000000
def isPrime(number):
if number == 2: return 1
elif number % 2 == 0: return 0
elif number == 3: return 1
elif number == 5: return 1
elif number == 7: return 1
else:
rootOfNumber = sqrt(number)
tag = 3
while tag < rootOfNumber:
if number % tag != 0:
tag += 2
else:
break ###
if tag >= rootOfNumber: ###EDIT: it should by only tag > rootOfNumber here
return 1 ### Thats what the problem was.
else:
return 0
sum = 2 # 2 is an even prime, something we are not iterating for
for i in range(3, limit, 2):
if isPrime(i) == 1:
sum += i
print(sum)
print('done...')
The equivalent java code is:
public class Prob10{
static int limit = 2000000;
static long sum = 2L; // 2 is an even prime, something we are not iterating for
public static void main (String[] args) {
for(int i = 3; i < limit; i+=2) {
if( isPrime(i) )
sum += i;
}
System.out.println(sum);
}
private static boolean isPrime (int number) {
if (number == 2) return true;
else if (number == 3 || number == 5 || number == 7) return true;
else {
double rootOfNumber = Math.sqrt(number);
int tag = 3;
while (tag < rootOfNumber) {
if (number % tag != 0)
tag +=2;
else
break;
}
if (tag > rootOfNumber)
return true;
else
return false;
}
}
}
I think I am doing some silly mistake or missing some subtle point.
p.s. I know my isPrime implementation is not too good. I am not printing the outputs because it may spoil the problem for others.
Any comments about (bad) style in the python program are welcome.
Try running with your code for example isPrime(49). You should figure out your problem from there. You have replaced a > with a >= in if (tag > rootOfNumber)
.Also as some coding style, you could just replace the first lines with:
if i in (2, 3, 5, 7): return 1
elif number % 2 == 0: return 0
else:
......
After a quick skim it appears to me that this line in the Python version is superfluous and it might be the cause of the problem:
elif number % 2 == 0: return 0
Why don't you return False for return value of 0? That would make it more simple.