Is there a nicer way to do the count I'm doing below?
I'm sure this must be possible with modulus or something. I'm looking for someway to manipulate i instead of using the extra variable x. (to beautify this).
Here is the long way round:
int MAX = 4;
int x = 0;
for (int i = 0; i < 50; i++) {
System.out.print(x);
if(x++; == MAX)
x = 0;
}
Expected outcome:
// 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 .. etc
for (int i = 0; i < 50; i++) { System.out.print(i % MAX); }
Yes, you can just do x = i % MAX;
Your code is pretty clear as is. While modulus % might save you a few keystrokes, it's not necessary. Natural human expression is generally preferred, especially if your coding at 4am or coming back to your code 6 months later.
Related
I need to print a triangle of characters:
0
1 0
1 0 1
0 1 0 1
The code I have prints it as this:
0
1 0
0 1 0
1 0 1 0
I can print it alternating, but when I try to change from alternating to unique characters I run into issues.
public static void main(String[] args) {
//mod even = 0, mod 1 = odd
int height;
int zero = 0;
int one = 1;
height = 4;
for(int i=1; i<=height; i++) {
for(int j=1; j<=i; j++) {
if ((j % 2) == 1) {
System.out.print((i % 2 == 1) ? zero : one);
} else {
System.out.print((i % 2 == 1) ? one : zero);
}
}
System.out.println();
}
}
I've tried adding in the if statement a scenario such as
if ((j % 2) == 1 && i == height){
System.out.print((i % 2 == 1) ? one : zero);
}
to get the last line to print starting with one, but it gets buggy and affects all lines. Any suggestions?
private static void triangle(int height) {
int valueToPrintNext = 0;
for(int i = 0; i < height; i++)
{
for(int j = -1; j < i; j++)
{
System.out.print(valueToPrintNext + " ");
valueToPrintNext = valueToPrintNext==0 ? 1 : 0;
}
System.out.println();
}
}
Main:
public static void main( String[] args )
{
triangle(6);
}
Output:
0
1 0
1 0 1
0 1 0 1
0 1 0 1 0
1 0 1 0 1 0
First of all: you're a programmer now. Programmers start counting from 0, not 1. PARTICULARLY in our for(){} loops. You're almost certainly a student, so just keep working at it.
What you're printing is basically "1 0 1 0" with newLines sprinkled in... so that's exactly how I'm going to do it.
This shows you that there are at least two different approaches to solving this problem. Bonus credit for anyone who comes up with a 3rd one (no not really).
Lets do a little numeric analysis to figure out the math on the total character count given a particular number of lines...
1 = 2 "1\n"
2 = 6 "1\n0 1\n"
3 = 12 "1\n0 1\n0 1 0\n"
4 = 20
5 = 30
6 = 42
n = n^2 + n
Okay, so now we write that up as a fairly trivial function. Lots of little functions is always easier to write AND TEST than a few big ones. Small functions good. Big functions bad.
private int getEndOfLinePosition(int lines) {
return lines * lines + lines;
}
And here we have the code which handles the aforementioned testing. Unit tests are awesome. Many people encourage you to write your unit tests BEFORE the code your testing. A good idea, but one I have to work at to follow. I like JUnit 5.
// imports go before your class at the top of the file
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
#Test
public void eolTest() {
int correctLengths[] = {2, 6, 12, 20, 30, 42};
for (int i = 0; i < 6; ++i) {
Assertions.assertEquals(correctLengths[i], getEndOfLinePosition(i + 1));
}
}
We'll build two functions, one to build the ones and zeros, and the other two sprinkle in the new lines. And we'll need a 'main' to glue 'em together.
void main() {
int height = 4;
StringBuffer onesAndZeros = buildOnesAndZeros(height);
addNewlines(onesAndZeros, height);
System.out.print(onesAndZeros);
}
There shouldn't be any surprises there... except perhaps that I'm using a StringBuffer rather than a String. String is immutable in Java, StringBuffer is expressly intended to be messed with, and mess with it we shall. Also, using print instead of println: our return will be built into the string.
private StringBuffer buildOnesAndZeroes(int height) {
int stringLength = getEndOfLinePosition(height);
StringBuffer buffer = new StringBuffer(stringLength);
char nextChar = '0';
for (int i = 0; i < stringLength; i += 2) {
buffer.append(nextChar);
buffer.append(' ');
nextChar = i % 2 == 1 ? "1" : "0";
}
return buffer;
}
The expression to determine nextChar might be backwards, but that should be easy to detect and fix. I may have even gotten it backwards on purpose just to leave you a bug to squish.
String addNewLines(StringBuffer onesAndZeros, int height) {
for (int i = 0; i < height; ++i) {
int currentEnd = getEndOfLinePosition(i);
onesAndZeros.setCharAt(curentEnd - 1, '\n');
}
}
Wrap all that in a class, and Bob's your uncle. Where the hell does that expression come from anyway? I mean... England, yeah, but why?!
/* when I run this code there is no error in fact output generated is also correct but I want to know what is the logical error in this code? please can any one explain what is the logical error. */
class abc
{
public static void main(String arg[]){
int sum=0;
//for-loop for numbers 50-250
for(int i=50;i<251;i++){
// condition to check if number should be divided by 3 and not divided by 9
if(i%3==0 & i%9!=0){
//individual number which are selected in loop
System.out.println(i);
//adding values of array so that total sum can be calculated
sum=sum+i;
}
}
//final display output for the code
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n"+sum);
}
}
My philosophy is "less code == less bugs":
int sum = IntStream.rangeClosed(50, 250)
.filter(i -> i % 3 == 0)
.filter(i -> i % 9 != 0)
.sum();
One line. Easy to read and understand. No bugs.
Change this:
if(i%3==0 & i%9!=0){
to this:
if(i%3==0 && i%9!=0){
& = bitwise and operator
&& = logical operator
Difference between & and && in Java?
The only problems I saw were:
The variable sum was undeclared
Use && in place of &
int sum = 0;
for (int i = 50; i <= 250; i++) {
if (i % 3 == 0 && i % 9 != 0) {
System.out.println(i);
sum = sum + i;
}
}
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n" + sum);
Well, instead of touching every single value from 50 to 250 like you would do here for(int i=50;i<251;i++), you can consider something like this...
int i = 48;
int sum = 0;
while(i < 250) {
i += 3;
if(i%9 != 0)
sum += i;
}
This is somewhat optimized in the sense that I am skipping over values that I know are not possible candidates.
But, there is a much bigger issue in your code. The following code block prints true, sure. But, it is a bad idea to depend on the & since that is not its job. The & is for bitwise AND whereas the && is for logical AND, which is what you are trying to do.
boolean t = true;
boolean f = false;
System.out.println(f&t);
Why?
In Java, if it is a && operation, as soon as you find the first false, you are sure that the expression will evaluate to false. Meanwhile, in your implementation, it would need to evaluate both sides. f&t will evaluate to false, but the JVM would need to look at both the f and t variables. Meanwhile, on using &&, it wouldn't even need to look at the t.
I'm trying to figure out what constitutes an instruction in java code. In class lecture that I attended professor mentioned 7 things that can be constituted as instruction but. I am having trouble making out what.
assignment, access of array, return statement, addition multiplication subtraction,..
Here is a example code she gave out:
int sum = 0;
int i = 0;
while ( i < 3 ) {
sum += A[ i ];
i++;
}
she says there are total of 18 instructions in this java code but I only count 15. Could you guys clarify why this is.
I believe something is missed in the explanation what count as instruction
Taking this schema there would be twenty.
1) int sum = 0; // 1 assignment
2) int i = 0; // 1 assignment
3) while ( i < 3 ) { // 1 comparison
4) sum += A[ i ]; // 1 array access, 1 addition, 1 assignment --> sum = sum + A[i]
5) i++; // 1 addition, 1 assignment --> i = i + 1;
6) }
The lines 3-5 are executed three times.
Say that length=11 and that I want to subtract 2 from it on every cycle until it reaches 1. Is my code for the for method correct? And what would it be for a while loop?
for(int i =length ; i!=1; i-=2)
EDIT: This was the question. To solve it I made an if statement that if the length%2==1 I would use the for loop listed above. Then I am going to write an else stating modifying the code above to stop at 0. Does this make sense?
The sum of all digits at odd positions (right-to-left starting at 1 as the right-most digit) of a numeric input. (For example, if the input is 432677, the sum would be 7 + 6 + 3 = 16.)
For is not a method. It's a language construct. Just a nitpick.
Almost. If i starts out even you'll never end. Use:
for(int i =length ; i>1; i-=2)
If the 1 is inclusive, you could try:
for(int i = length; i >= 1; i -= 2){ ... }
Or
for(int i = length; i > 0; i -= 2){ ... }
If the 1 is exclusive, you could try:
for(int i = length; i > 1; i -= 2){ ... }
Lets say I have a number 1-5, now if I have 2, I want 4 as an output, if I had 3 then have 3 as the output, if I have 1 then 4 as the output. Here is a chart of what I want:
1-10 Chart:
Give 1 return 9
Give 2 return 8
Give 3 return 7
Give 4 return 6
Give 5 return 5
What algorithm do I use for such a thing?
I don't see that you need an algorithm as much. What you have is:
InverseNumber = (myCollection.Length - MySelection);
Thats all you need for even numbers.
With a collection of 1 - 6 for example:
Give 2; 6 - 2 = 4. Also if given 4, 6 - 4 = 2.
You will need a slightly different problem for odds:
1 - 5; with 1 given 1 is at index 0, the opposite is 5, 2 given and the inverse ( 5 - 2) is 3. But if 3 is given, there is no inverse. So you might want to also add a catch for:
if (((myCollection.Length *.5).Round) == mySelection) { //Inverse does not exist!!!}
If you are using just integers, and not arrays of numbers then just replace the myCollection.Length with the upperbound integer.
I think the following code will work for what you need:
int a[] = new a[length_needed];
int counter = length_needed;
for(int c = 0; c < length_needed; c++) {
a[c] = counter;
counter--;
}
int number_inputed;
for(int c = 0; c < length needed; c++) {
if(c == number_inputed) System.out.println(a[c]);
}
Let's say you are giving max number as input. Then you are going to have 0-n numbers. For ex., if 9 is the max number you will have 0-9.
Then you can do something like this:
public static void main(String[] a) {
int max = a[0]; // read values from cmd line args
int forWhichNum = a[1]; //for which number we need its inverse
Sop(max- forWhichNum);
}
Integer value = 2;
Integer maxValue = 6;
Integer reverseCounter = 0;
for (int i = maxValue; i > 0; i--) {
reverseCounter++;
if (i == value) {
return reverseCounter;
}
}