Outputing a square to console in java [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi i am doing my coursework and i have been given the task is to make an algorithm for a square that's 5x5 using "*" but has to be filled in with "." so like this:
*****
*...*
*...*
*...*
*****
I have used this code I know its probably very messy because im an absolute beginner to this stuff. I cant seem to get the "." in i currently have:
*****
*****
*****
*****
*****
here is my code:
public static void main( String args[] )
{
System.out.print ("#size of square");
int stars=BIO.getInt();
int j=1;
while(j <= stars)
{
int starsNumber=1;
while (starsNumber<= stars)
{
int i = 1; // Display trunk
starsNumber=starsNumber+1;
System.out.print('*');
}
System.out.println();
j= j +1;
}
}
p.s sorry for been so bad at coding :D and any help would be much appreciated thanks Gareth

Guidance rather than an answer since it's coursework...
It sounds like you need an if statement to decide whether to print * or .. The * should be printed when you are on the first line or the last line, or at the first column or the last column.
You will find the flow control more intuitive creating a square using a nested for loop, e.g.
for (int row=0; row<stars; row++)
{
for (int col=0; col<stars; col++)
{
// Do your output here
}
}

Have you gotten the program to print an 5x5 square full of asterisks working?
I'd strongly recommend getting that working first. After that, you just need a minor modification to print the dots in between.
For that, instead of always printing an asterisk, you'll need a conditional.
Pseudocode:
if(I'm currently on the edge)
Print an asterisk
else
Print a dot
I'll leave it to you to figure out how to translate this into real code. Good luck!
Edit, hints on how to determine if you're currently on the edge:
You are keeping track of the current row and current column (in order
to print a square exactly 5x5 characters).
The edge consists of the first and last row, and the first and last column.
Given hint 1 and hint 2, can you now determine when you are on the edge and when you're not? You'll need to do variable comparison, so read your textbook if you're not familiar with how to compare variables.
Hope that helps. There's really not much more I can say without giving away the exact answer.
Finally, think about your solution before coding it. Immediately jumping into coding can be a roadblock, especially when you're a beginner and not too familiar with the language so you get bogged down in the language syntax. Mentally put together the flow of your program, draw pictures, and maybe write pseudocode before you write the actual code. I find that doing this helps me write code easier and reduces the number of bugs that come up.

When either of your loop variables are at their limiting values (both upper and lower) you have to print a * and in other cases you have to print . Use if statement to control this flow. Cheers :)

All this "use if statement", let's do it some other way now. Of course this isn't actually useful, I just want to challenge the idea that you have to use control flow, and maybe people stumbling upon this might learn something from it..
First off, here's the code I came up with (it works)
for (int row = 0; row < stars; row++) {
for (int col = 0; col < stars; col++) {
System.out.print((char)((
(-col) >> 31 & // encodes the condition: col > 0
(-row) >> 31 &
(col - (stars - 1)) >> 31 &
(row - (stars - 1)) >> 31 & ('*' ^ '.')) ^ '*'));
}
System.out.println();
}
The basic principle I used to avoid control flow is that when a negative int is right shifted (with signed shift), the signbit is copied into the bits that are "shifted in" at the left side. A result of that is x >> 31 (where x is an int) has only two possible outcomes, 0 (if x was nonnegative) and -1 (if x was negative). You can use that principle to turn conditions into bitmasks. You can also do it with unsigned shift and a negation, but you might as well write it the shorter way.
Secondly, I used that (a ^ b) ^ a = b and a ^ 0 = a.
So when all conditions hold, '*' is xored with '*' ^ '.', giving '.', and otherwise '*' is xored with zero, giving '*'.
Of course, this is just for fun.

Related

Pothole fixing machine

I recently worked on an online problem for which answers were not provided, however, I would like to know where I went wrong. The prompt was strange, but I will do my best to explain it:
There is a machine that can fix all potholes along a road 3 units in length. A unit of Road will be represented with a period in a String. For example, "..." = one section of road 3 units in length. Potholes are marked with an "X" in the road, and also count as a unit of length. The task is to take a road of length N and fix all potholes with the fewest possible sections repaired by the machine. This problem is concerned with performance over correctness.
Example 1: A road represented by ".X." would require 1 fix.
Example 2: A road represented by "..X...X" would require 2 fixes.
Example 3: A road represented by "XXX.XXXX" would require 3 fixes.
My approach (shown below) was to count sections of String in increments of 3 chars at once. If that sequence contained an "X", then it needed a fix and vice versa. To account for roads that aren't multiples of 3 in length I just kept the sequence reading and checked whatever was left. I'm also not sure how to make the program better for performance (other than replacing my sequence String with a StringBuilder)
public class Solution {
//Note: I had to re-write this from memory, as I was not given it back by the online problem checker
public int solution(String S) {
int fixes = 0;
String sequence = "";//Perhaps use StringBuilder?
for (int i = 0; i < S.length(); i++) {//read the entire incoming string
for (int j = 0; j < 3; j++) {//Count 3 chars at once
sequence += S.charAt(i);//Add said Chars to our sequence
}
if (sequence.contains("X")) {//Check for potholes
fixes++;//We can fix everything in this sequence
sequence = "";//reset our sequence
}
}
if (sequence.contains("X")) {//Check anything left, since not all roads are multiples of 3
fixes++;
}
return fixes;
}
}
I thought this was good enough for what was asked, and it passed all of the given example Strings, but apparently failed horribly upon review. I don't know what I've done wrong, though I feel like there's probably something small and stupid that I'm missing.
UPDATE:
I was indeed missing something obvious, I need to start reading at the first "X", something like this:
if (S.charAt(i) == 'X') {//Start counting at the first X
for (int j = 0; j < 3; j++) {//Count 3 chars at once
if (i + j <= S.length() - 1) {//no outofbounds exceptions please!
sequence += S.charAt(i + j);//Add said Chars to our sequence
}
}
}
Now I just need to make sure it meets performance requirements.
and it passed all of the given example Strings
But... how?
Your code is completely wrong. How can it have passed the example strings? Must have been some very unlucky examples, then!
for (int j = 0; j < 3; j++) {//Count 3 chars at once
sequence += S.charAt(i);//Add said Chars to our sequence
}
This will add the exact same character, 3 times. i never changes. Thus, sequence is either "..." or "XXX".
if (sequence.contains("X")) {//Check for potholes
fixes++;//We can fix everything in this sequence
sequence = "";//reset our sequence
}
This boils down to: If it was "XXX", increment fixes.
if (sequence.contains("X")) {//Check anything left, since not all roads are multiples of 3
fixes++;
}
This if cannot possibly trigger. Think about it.
All your code does, is count potholes. In a convoluted way.
I thought this was good enough for what was asked
You've made 3 major errors. Each is individually probably sufficient to get a significant downgrade if this is an exercise for a job:
The code contains a performance faux-pas (concatenating strings using + in a loop), when the question explicitly calls out that performance is important. You'd have to call it out and explain why you intentionally broke a rule of thumb, at least.
The code straight up doesn't work, at all.
Even if you fix it, the code STILL does not work. Take, for example, the input ".X.X..". The correct answer is 1. Even if you fixed your code and you treat each chunk of 3 properly (instead of one at a time due to your messup between j and i), your algorithm returns 2. The question is a little more complicated than you think it is. Not much, mind. Still, the entire algorithm as written should just be tossed in the bin, and start over. Don't start with programming. Start with schetching out the problem and considering the algorithm required. Only then start coding.
Here is the correct algorithm. Just sketched out, thinking the problem through:
Just scan for a pothole. Once you find one, fix it and skip past the next 2 units of road while you're at it. They just do not matter. If they have potholes, we'll fix em for free along with the hole we found.
That's all you need to do. Just count potholes, ignoring any potholes that are 1 or 2 'to the right' of a pothole we fixed.
Here:
public int solution(String s) {
int holes = 0;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == 'X') {
holes++;
i += 2;
}
}
return holes;
}
This code is much simpler, is correct, and is clearly as fast as it's ever gonna get.
Segmenting the string into groups of 3 will fail when potholes don't align with those divisions. Sometimes it will be optimal for the machine to skip 1 or 2 units, or 4 or 5 -- some number that isn't a multiple of 3.
For example, consider this road:
.X.XX.XX.X
Your algorithm will declare that 4 segments need to be repaired:
|.X.|XX.|XX.|X|
But it can be done in 3 segments:
.|X.X|X.X|X.X|
Your program only reads the road in sections of 3 units. It can give a wrong answer for some configurations.
For instance, it will answer "2" for ..X.X...., while this road can be fixed in only one fix.
It will read ..X, .X., ..., when it should read up until the first X, forget what was before, and then do a fix of 3 units before continuing.
It should read .., X.X, ....
def pothole_fixing(road):
potholes = 0
sections = 0
for i in range(len(road)):
if road[i] == 'X':
potholes += 1
else:
if potholes > 0:
sections += -(-potholes // 3)
potholes = 0
if potholes > 0:
sections += -(-potholes // 3)
return(sections)
The function takes a string road representing the road with potholes and returns the minimum number of sections needed to fix all potholes.

Trying to Count the Number of Operations in Code

I have recently been reading Sedgewick's Algorithms Book, and I came across an example I didn't quite understand...
Using this code, Sedgewick mentions that the if statement is run precisely
N x (N-1)(N-2)/6 times.
I don't quite understand why that is.... I see that there are the triple nested loops, each with an upper bound that is increasing, but why is the value divided by six?
I ask for your understanding that I am not good at math, so the explanation may be a little bit cheesy.
In order to 'if(a[i] + j[i] + k[i]) statement' inside the code be executed The variables i, j, and k that point out an array 'a' index in Tripple for loop must fit the condition of the statement (0<= i <j<k <N), right?
For example, N is 4.
It seems to be available through the permutation (4P3 = 4^3) that selects three of the four, but if 4 is selected in 'i' as shown in the picture above, you can see that progress is blocked in 'j' for-loop (j = 4+1; j<4; j++).
So We can't get the number of times an if statement will run with a simple sequence.
What we need is a combination (nCr).
When index flows from 0 to N-1,
The number of cases (i,j,k) that satisfy i < j < k(=> if statement can run) can be obtained by the formula nC3.
According to this formula, if statement is run precisely N x (N-1)(N-2)/6 times
I hope you understand it well and if you don't, please leave a comment!
Have a nice day!

How to output this to the screen?

I'm currently studying for my introductory CS final, and I'm having a really rough time with a few problems. The one I'm most worried about asks me to produce the code, in Java, to create the following output to the screen:
+
+++0
++++++00
++++++++++000
... (this pattern continues for 200 lines)
This might seem like a very basic question, but how do I go about doing this? I know that I should write some arrays and use for loops to go through them and output stuff to the screen, but I would really appreciate some guidance on how to solve this problem, along with others of its ilk. Thanks!
The pattern for the number of 0 is simply an arithmetic sequence. The number of + is as follows:
Row 1: 1
Row 2: 3 = 1 + 2
Row 3: 6 = 3 + 3
Row 4: 10 = 6 + 4
Turns out that these are triangular numbers. So, calculate the triangular number for each row in a loop, and have a nested loop that prints + that many times, then print the required number of 0.
I don't think this deserves a -1. Beginner question is not equal to a bad question.
As for the question itself. You have to carefully identify the pattern first and then word it in plain English. The pattern is quite simple.
Start with 1 cross and 0 zero. For each iteration, increase the growth
of crosses by 1 (so it's +1, +2, +3...) starting with a growth of 2
units and increase the growth of zeroes by 1 starting at 1 unit.
Now put this into pseudo-code and then code it. Be sure to understand the patterns first. I cannot stress this enough. Going right into coding will not help you.
First you need to be able to recogonize the pattern, then you need to be able to code it.
I'm going to go out on a limb and suggest that you are mixing the two "steps" of this problem together, so let's be very specific in dividing them.
The (parenthesis) items are the _additional_ elements.
index 0 : +
index 1 : +(++)(0)
index 2 : +++(+++)0(0)
index 3 : ++++++(++++)00(0)
so a good guess is that the pattern could be described as:
the previous number of +'s (and index + 1 more),
followed by the previous number of 0's (and one more).
combined with
index 0 is "+"
You might want to calculate index 4, 5, and 6 from this "rule" and see if it seems to describe the pattern correctly.
Now that you have the pattern, you really only need two variables, the number of + signs, and the number of 0s. You can calculate the "next" one from the previous one. The coding shouldn't be too hard, but if it is, then post your program and your "new" problem with that program in another question.
public class Answer {
public static void main(String[] args) {
int plusCount = 1;
for(int i=0; i<200; i++) {
for(int j=0; j<plusCount; j++) {
System.out.write('+');
}
plusCount += i+2;
for(int j=0; j<i; j++) {
System.out.write('0');
}
System.out.println();
}
}
}

Trouble Determining End Game [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to check to see if a player can no longer make moves but i cant seem to figure out how to check for it.
Say i have 5 tiles or less and each tile has a value between 1 and 3 on it. I want to run through the tiles and check if there are any possible combinations that will add up to 10. Its not as simple as just checking the total because there could be 3 tile with 3's on them and one with a 2. I have spent hours trying to figure this out....
Any ideas on how i could check for all possible combinations? I only need to see if one combination is possible. As soon as one is found i would break the loop to reduce the number of checks.
Edit: If it helps you can kinda see what im talking about if you download it. Its Numero: 21 on the android.
The object of the game is to add tiles to 21. So when the user gets down to a few tiles, sometimes a combination of 21 cant be acheived even when the total of all the tiles is above 21 because the numbers dont add up to exactly 21. This creates a problem because i am unable to check for that and tell the user that they have lost.
I really dont even know where to begin when it comes to checking for it. i can loop through all the tiles multiple times but the thhing is a combination could be as many tiles are on the board. So i have to check for combinations of 3, then 4 , then 5 and so on until the number of tiles left is reached. Its kind of hard for me to explain this exactly
Corrective Edit For Future Reference:
I apologize for my initial question for being so ambiguous. Happened to be the first question I ever asked on here... This is a much better description of the problem and the solution. I decided to keep the previous text for record.
The game has numerous numbered tile and I you have to add them up to 21 to remove. You can not go over 21. It has to be exact.
What I was wanting to check is if there was still a combination of tiles that could be used to add up to 21 exactly. A basic sum check doesn't work because you could have 5 number 5 tiles and be more than 21 but not possible to eliminate anymore.
Solution
As #mellamokb answered subset sum recursion needed to be used. Basically you loop through the tiles and on each tile you call the same function twice. One call adds the current tile and the other continues to the next iteration without adding the current tile. If any return true then the function is true. Basically a binary tree.
Code
boolean validate(tiles, index, subtotal, total){
if index >= tiles.length return false;
if subtotal == total return true;
return validate(tiles, index + 1, subtotal + tiles[index].number, total) ||
validate(tiles, index + 1, subtotal, total);
}
Call it with
validate(tiles, 0, 0, 21)
That about does it.
This sounds like a variation of the subset sum problem. The simplest algorithm is O(2^n), iterating over every possible subset combination by using bit flags, for example.
for i = 0 to 2^n - 1
set subtotal = 0
for each bit in i
if bit i is set, add ith element to subtotal
check subtotal against desired total (i.e., 10)
Or, alternatively using recursion:
validate(set, index, subtotal, total)
if index >= set.length return false;
if subtotal == total return true;
return validate(set, index + 1, subtotal + set[index], total) ||
validate(set, index + 1, subtotal, total);
Usage:
validate(set, 0, 0, 10);

Java- Why for uses i,j [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why are we using i as a counter in loops?
Why are variables ā€œiā€ and ā€œjā€ used for counters?
This may seems stupid, but why everybody use i (if i is already in use, then j) in for loop checking ?
Means:
for(int i = 1;i <= 5;i++){
for(int j = 1;j <= i;j++){
System.out.print(i);
}
Why i and j ? We can use first and second also ? Check this, all (9 out of 10) uses i, j. Why ? Any reason or just doing because everybody does that ?
This programming convention has been around for a long time, and probably goes back all the way to Fortran. In Fortran 77, variables beginning with the letters I, J, K, L, M, or N were taken to be of type INTEGER (unless explicitly declared otherwise). That made them very well suited to be loop variables.
Of course i, j etc have been used in maths to denote matrix/vector/summation indices for much, much longer than computers have existed.
Simple variable names that are easy to read. Also it dates back to the C days in K+R
I think it is a habit that finds it simple origin in the fact that i is the first letter of integer and index.
i and j are commonly used in linear algebra when doing matrix multiplication and summations. i is conveniently short for index. and j is lexicographically adjacent to i.
Now that it's so established, I wouldn't use anything else, lest the programming gods bring pain upon ye.
i stands for index
j comes after i..
so its easy to remember and handle
that's why we are using in sequence i,j,k,l.....
i, and j are also used in math and physics. i is often the notation for Cartesian x-axis basis unit vector while j is used for Cartesian y-axis basis unit vector.

Categories