I am trying to solve an exercise: I have a txt file with images (20 rows x 20 columns) of 0's and 1's made random. Between each image (20x20) there is a gap of one empty line.
Based on this txt file I have to calculate how many of these images have more 1's than 0's. At the end I need to also find the highest number of 1's occuring in one image.
Here is my code so far ... but I am a little bit lost
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
File input = new File("path to my txt file");
Scanner scanner = new Scanner(new File("path to my txt file"));
int counter = 0;
while (scanner.hasNext()){
String word1 = scanner.next();
String word2 = scanner.next();
boolean switcher = false;
int howManyOnes ("//path to my image file????") {
int ones = 0;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
ones +=?[i][j];
}
}
return ones;
}
}
}
Here is my understanding on which I will base my answer.
Your input is a text file in which each non-blank line has a total of 20 characters some of which are '1' and some of which are '0'.
An "image" is a collection of sequential non-blank lines. When one blank line is present it signals the end of one "image" and the beginning of the next "image".
Your objectives are:
to calculate how many of these images have more 1's than 0's.
and
find the highest number of 1's occurring in one image.
As this appears to be a homework type of question I will give you some guidance regarding how to design your code first and later if you're still struggling I can provide additional details. Please see how to ask and answer homework questions.
Assumptions:
You are allowed to use any of the methods of the String class.
Consider the things you want to track and in what scope you want to keep track of them. You need to be able to identify when an image begins and ends and track how many 1s and 0s you see within that image. That is, when an image begins the number of 1s and number of 0s for that image should be zero and you should increment them as you identify them in each line of the image. Once the image has been processed you will need to reset these to 0 to get ready to process the next image.
At the same time when you're done processing a single image you need to determine if the number of 1s in that image is greater than the number of 1s you've seen in any other image so far and if it is track that value. This value's scope is larger than the values mentioned previously as it is determined by the number of 1s in all of the images. It must NOT be reset with each image. Similarly, the number of images that have more 1s than 0s also has this kind of scope - it should NOT be reset with each image, rather it should be maintained until the entire file has been processed.
Next, consider how you can determine the number of 1s and 0s within an image. It looks like you're thinking about looping through every character and you could do it that way but there is a simpler way and it has to do with the assumption I mentioned.
I hope this gets you started. Please update your question as you write more code and I'll be happy to update my answer as well.
Related
Forgive me if this is not formatted properly, this is my first post. I looked to see if this issue has been found before and I cannot find anyone who has had the same problem I am having.
I am trying to learn Java and cannot for the life of me figure out why my for loops are not outputting the last iteration. I am going through codeabbey's exercises and completed the first two relatively easily. However on the third and fourth problems, I cant get my for loop to output during the last iteration.
I began looking on google and thought I would compare my answer to someone else's. I couldn't see why mine wouldn't work when my code was almost identical to the person I found. So I copied their code and to my surprise I had the same problem when this code also would not output on the last iteration.
So, here is the context.
The website gives you a single number first which is the number of sets of the following numbers. For the third problem, you are to add the sets of two, output the sum followed by a space and loop through the entire batch. For the fourth problem, it is similar where the first number is the number of sets in the batch but you are to compare the two numbers and output the lower number. I will copy my code here for the third problem because the code is simpler.
Here is the code:
import java.util.Scanner;
public class Summation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n;i++){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b + " ");
}
}
}
Here is the input you are to copy and paste:
3
100 8
15 245
1945 54
and this is my output:
108 260
So, as you can see we are missing the last output here. I tried changing the for loop to (i < (n+1) ) which still didn't change anything. Any help would be GREATLY appreciated!
Ok so I tested it, and with your numbers, typing them in one by one it works. Copy pasting them, press enter one more time at the end of the copy. If you don't press enter, the scanner thinks you're still adding to the second number so it won't continue until enter is pressed.
I would try using println() as someone else suggested, or calling flush() at the end of the program to make sure something isn't being held in a buffer and not being written.
I have to reverse the order of an array called myWordArray that plays from a thisisatest.wav file. It should play "test a is this" instead of "this is a test."
public void playReverseOrder(int pause) throws InterruptedException {
Sound orig = new Sound();
int length = myWordArray.length;
for (int i = 0, source = length - 1; i < length && source > 0; i++, source--) {
myWordArray[i].setSampleValueAt(i, orig.getSampleValueAt(source));
myWordArray[i].blockingPlay();
Thread.sleep(pause);
}
}
My logic is that I create a new sound, then use the length to increment the index i forward as the original source decrements. It plays forward, however I cannot get the words to reverse. I've thought of retrieving the samples of the myWordArray within new Sound (myWordArray.getSamples()); however that does not work, and I would try to access the file within the parameters, but we select the file manually within the test harness.
I am assuming, you meant test a is this. This is a harder problem and discussed below. If you want to make it sound like tset a si siht, you can simply arrange the content of the array in reverse order. Please note that, this sound wont be intelligible.
myWordArray[i].blockingPlay();
Thread.sleep(pause);
In your code, I guess you don't need this.
If you are interested in test a is this, the process would be something like this:
Find number of words in the sound file, requires little knowledge of audio signal processing
Mark their boundaries
Now, half of the work is done. Only remaining part is playing back the sounds of words in reverse order.
Create another Sound, fill the samples array with all segmented pieces of words, but in reverse order. Done.
I was wondering how to code the game, Mastermind, in Java, but with things up a notch (I want to inform the user not only how many pegs they got right or wrong, but also how many they guessed correctly in the wrong slots).
For instance, say the RNG answer of 5 digits of numbers 1-6 is:
22354
... and the user's guess is:
32624
Resulting in:
two guessed correctly (2 and 4)
two guessed partially correct (2 and 3)
one guessed incorrectly (6).
Here's my code for informing the user what they got correct:
String answer = "22354";
String guess = "32624";
int correctPegs = 0;
for (int i = 0; i < 5; i++) {
char a = answer.charAt(i);
char g = guess.charAt(i);
if (a == g) {
correctPegs++;
}
}
System.out.println(correctPegs);
How would I find the partially correct ones?
... and for calculating how many the user guessed incorrectly, I was thinking of using basic algebra to find the remaining characters after finding the correct and partially correct ones.
I would put '0' into the strings where they match. Then for every char that is not a zero, I would look through the answer string again. If any character in the answer string matches, I would make them both zero, and increment outOfPlacePegs.
This guards against two corner cases I am assuming you do not want:
One is when you have '323' as the answer and '223' as the input. You don't want the first '2' to be recorded as out of place.
Second is when you have '223' as the answer and '442' as the input. You don't want this recorded as two numbers out of place.
I'm a pretty newbie programmer and basically I'm trying to parse and manipulate a DL_POLY config file, which has the layout
CONFIG file created from Xmol file config.xmol
2 3 10000000 0.5000000000E-03
31.309729731729 0.000000000000 0.000000000000
0.000000000000 31.309729731729 0.000000000000
0.000000000000 0.000000000000 31.309729731729
Ca 1
6.421269411 -1.034199034 1.228702751
-1.06475894897 1.10274459622 1.31459311620
-6319.67959205 -10299.4183311 468.606019012
which sort of goes on for about 150 odd more entries of just the
Ca 1
6.421269411 -1.034199034 1.228702751
-1.06475894897 1.10274459622 1.31459311620
-6319.67959205 -10299.4183311 468.606019012
segment, where the second row represents x, y and z coordinates, which I need to manipulate by adding a slight displacement to, and the top row, where Ca represents the atom (in this instance, calcium) and the integer is an atom counter (this is the first atom, I have a system of about 75 CaCO3).
Now I've written some java code which reads in the string, sticks it in an arrayList and tokenises it and from there I'm pretty sure how to add the displacement only maintaining this weird formatting complicates it all. Obviously I'm aiming for as general a solution as I can get here, so I can reuse this, whilst I'm sure I could force it into the correct format, it means I can only ever use it for that file.
So, my questions are, how can I manipulate values in a file in java, keeping the format 100% intact? And within this system, how can I tell it to add the displacement on only the second row of each segment?
It's a bit complicated (or maybe not, I really don't know) but I would really appreciate some help.
So, I've got something like this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileReader;
public class testArrayReader {
static ArrayList<String> temp = new ArrayList<String>();
public static void main(String[] args) {
String[] arr = null;
String[][] twodim = null;
System.out.println("Array List initialised!");
try{
FileReader input = new FileReader(urlfortextfile);
BufferedReader reader = new BufferedReader(input);
System.out.println("Scanned!");
String line;
int onedimcounter = 0;
while((line = reader.readLine()) != null){
temp.add(onedimcounter++, line);
}
System.out.println(temp);
twodim = temp.toArray(new String[temp.size()][temp.get(0).length()]);
System.out.println("stage 2 complete");
System.out.println(twodim);
}
catch(FileNotFoundException ex){
System.out.println("No file found boss.");
}
catch(IOException ex){
System.out.println("IO error.");
}
}
}
Few more queries,
1) [1st line, 2nd line, ..., nth line] - the comma denotes that the first and second line are separate elements, right?
2) I'm getting an ArrayStoreException and I'm really not 100% sure why - the documentation mentioned something about a casting error, so I'm assuming my arraylist items are still stuck as objects. How do I fix this?
3) Current plan for modification is to list the element index in the final array, modify and reprint, but I've chunked it line by line to preserve the formatting. Need a bit of conformation I'm on the right track here, my idea was to parse the line for doubles, do what I need to do and then try and get the computer to count the number of whitespaces between digits and replace build a string, which then I can just reinsert. Something like a counter with an if statement based off of some boolean looking for white space, then the counter will insert " " when I concatenate the final string.
Cheers.
First, parse the file to a table of values with associated position-in-file metadata.
Second implement all mutations on that table in terms of atomic duplication/insertion/removal of cells/rows/columns which also update position-in-file.
Third, implement a table serialize operator which takes in the old content so that you can look up the white-space between data lines and between cells within a line, and so you can deduce the number format (number of sig digits) from the old file when serializing changed numeric values.
how do I find and parse the position in file metadata?
To associate position information, keep track of
/** Number of line breaks since start of file */
int lineNumber;
/** Number of chars since start of file */
int charInFile;
/** Number of chars since start of line (if on the zero-th line) or last line break. */
int charInLine;
Then with each token, associate the position before the first character, and the position after the last character in the token.
When you parse a complex construct like a table, table row, or table cell, store with it the position before the first token that it spans, and the position after the last token it spans.
what's a table serialize operator? I know of serialization just not that
By operator, I just means part of a programming language that allows you to specify a relation between inputs and outputs. I use it to avoid language-specific jargon like function, method, or procedure.
how do you enter a return key in stack overflow
See "What is the reason for the top secret two space newline markdown weirdness?"
I don't want the answer, I just don't understand how to scan the first number to tell the program how many pairs there are. If you could nudge me in the right direction I would greatly appreciate it.
"Most programs should be able to make some choices and decisions. And we are going to practice conditional programming now.
This is usually done by a kind of if ... else statements which may look like:
IF some_condition THEN
do_something
ELSE
do_other_thing
ENDIF
Depending on your programming language syntax could be different and else part is almost always optional. You can read more in wikipedia article on Conditional statements.
Of two numbers, please, select one with minimum value. Here are several pairs of numbers for thorough testing.
Input data will contain number of test-cases in the first line.
Following lines will contain a pair of numbers to compare each.
For Answer please enter the same amount of minimums separated by space, for example:
data:
3
5 3
2 8
100 15
answer:
3 2 15 "
Firstly, you might want to format your example data a bit. I understood it, but mostly only because I've seen that question format before.
Well, to answer your question but not the question's question (heh), note this:
Following lines will contain a pair of numbers to compare each.
Note the "lines" (plural) and the "each." We're going to need a loop.
We also know each line is a test case.
So modify the instructions:
Loop over the following test cases, comparing each pair
But how many times do we loop?
Input data will contain number of test-cases in the first line
That's the first number.
So here's our code skeleton:
//We can use a Scanner for convenience, it has a readInt() method
Scanner input = new Scanner(/*your input*/);
int numCases = input.readInt();
for(int i = 0; i < numCases; i++) {
int first = input.readInt(); //readInt() will also skip newlines, just a tip.
int second = input.readInt();
/* Compare two inputs, do stuff*/
}
For the record, you could also simply ignore the first input and just loop until there is no more input, but that's sloppy.
First you need to create a Scanner. If you're reading from the console, then this will work:
Scanner scan = new Scanner(System.in);
If you need to read from a file, then you can add this line as well.
System.setIn(new FileInputStream("inputFileName"));
For your specific case, you can do something like:
int numPairs = scan.nextInt();
You can find out more about Scanner and its methods from the Oracle documentation here.