Array and file creation basic Java Array Problem - java

I happen to be having a hard time with a problem. A test will be coming up soon for me and I'm just not so sure as to how to get this problem done. (Nothing too advanced) My main issue is that the reading of and creating the final file. the problem is right below. Any help is appreciated, thanks!
I've been told to add a summary due to the difficulty to understand what im asking. So essentially you have a file, text.txt and the program takes said file and adds all the numbers in it, spaces make the numbers distinguished and if a zero is at the front it needs to get taken away. All numbers are separated (whatever number of spaces are between them) is all separated with a space + space and a space = at the end followed by space the result of the addition. I'm looking for help as how to:
a) Make the new file
b) Make the +s and =s
c) Transferring from the original file
d) How to do the addition (dealing with large space gaps and doing the summing)
IM STILL VERY NEW TO JAVA SO ANY LONGER EXPLANATIONS WOULD BE GREATLY APPRECIATED
The approach you are to implement is to store each integer in an array of digits, with one digit per array element. We will be using arrays of length 25, so we will be able to store integers up to 25 digits long. We have to be careful in how we store these digits. Consider, for example, storing the numbers 38423 and 27. If we store these at the “front” of the array with the leading digit of each number in index 0 of the array, then when we go to add these numbers together, we’re likely to add them like this:
38423
27
Thus, we would be adding 3 and 2 in the first column and 8 and 7 in the second column. Obviously this won’t give the right answer. We know from elementary school arithmetic that we have to shift the second number to the right to make sure that we have the appropriate columns lined up:
38423
27
To simulate this right-shifting of values, we will store each value as a sequence of exactly 25 digits, but we’ll allow the number to have leading 0’s. For example, the problem above is converted into:
0000000000000000000038423
0000000000000000000000027
Now the columns line up properly and we have plenty of space at the front in case we have even longer numbers to add to these.
The data for your program will be stored in a file called sum.txt. Each line of the input file will have a different addition problem for you to solve. Each line will have one or more integers to be added together. Take a look at the input file at the end of this write-up and the output you are supposed to produce. Notice that you produce a line of output for each input line showing the addition problem you are solving and its answer. Your output should also indicate at the end how many lines of input were processed. You must exactly reproduce this output.
You should use the techniques described in chapter 6 to open a file, to read it line by line, and to process the contents of each line. In reading these numbers, you won’t be able to read them as ints or longs because many of them are too large to be stored in an int or long. So you’ll have to read them as String values using calls on the method next(). Your first task, then, will be to convert a String of digits into an array of 25 digits. As described above, you’ll want to shift the number to the right and include leading 0’s in front. Handout #15 provides an example of how to process an array of digits. Notice in particular the use of the String method charAt and the method Character.getNumericValue. These will be helpful for solving this part of the problem.
You are to add up each line of numbers, which means that you’ll have to write some code that allows you to add together two of these numbers or to add one of them to another. This is something you learned in Elementary School to add starting from the right, keeping track of whether there is a digit to carry from one column to the next. Your challenge here is to take a process that you are familiar with and to write code that performs the corresponding task.
Your program also must write out these numbers. In doing so, it should not print any leading 0’s. Even though it is convenient to store the number internally with leading 0’s, a person reading your output would rather see these numbers without any leading 0’s.
You can assume that the input file has numbers that have 25 or fewer digits and that the answer is always 25 digits or fewer. Notice, however, that you have to deal with the possibility that an individual number might be 0 or the answer might be 0. There will be no negative integers in the input file.
You should solve this problem using arrays that are exactly 25 digits long. Certain bugs can be solved by stretching the array to something like 26 digits, but it shouldn’t be necessary to do that and you would lose style points if your arrays require more than 25 digits.
The choice of 25 for the number of digits is arbitrary (a magic number), so you should introduce a class constant that you use throughout that would make it easy to modify your code to operate with a different number of digits.
Consider the input file as an example of the kind of problems your program must solve. We might use a more complex input file for actual grading.
The Java class libraries include classes called BigInteger and BigDecimal that use a strategy similar to what we are asking you to implement in this program. You are not allowed to solve this problem using BigInteger or BigDecimal. You must solve it using arrays of digits.
The sample program of handout #18 should be particularly helpful to study to prepare you for this programming problem. It has some significant differences from the task you are asked to solve, but it also has some similarities that you will find helpful to study. The textbook has a discussion of the program starting in section 7.6.
You may assume that the input file has no errors. In particular, you may assume that each line of input begins with at least one number and that each number and each answer will be 25 digits or fewer. There will be whitespace separating the various numbers, although there is no guarantee about how much whitespace there will be between numbers.
You will again be expected to use good style throughout your program and to comment each method and the class itself. A major portion of the style points will be awarded based on how you break this program down into static methods. As with the sample program in handout #18, try to think in terms of logical subtasks of the overall task and create different methods for different subtasks. You should have at least four static methods other than main and you are welcome to introduce more than four if you find it helpful.
Your program should be stored in a file called Sum.java. You will need to include the files Scanner.java and sum.txt from the class web page (under the “assignments” link) in the same folder as your program. For those using DrJava, you will either have to use a full path name for the file sum.txt (see section 6.2.2 of the book) or you will have to put the file in the same directory as the DrJava program.
Input file sum.txt
82384
204 435
22 31 12
999 483
28350 28345 39823 95689 234856 3482 55328 934803
7849323789 22398496 8940 32489 859320
729348690234239 542890432323 534322343298
3948692348692348693486235 5834938349234856234863423
999999999999999999999999 432432 58903 34
82934 49802390432 8554389 4789432789 0 48372934287
0
0 0 0
7482343 0 4879023 0 8943242
3333333333 4723 3333333333 6642 3333333333
Output that should be produced
82384 = 82384
204 + 435 = 639
22 + 31 + 12 = 65
999 + 483 = 1482
28350 + 28345 + 39823 + 95689 + 234856 + 3482 + 55328 + 934803 = 1420676
7849323789 + 22398496 + 8940 + 32489 + 859320 = 7872623034
729348690234239 + 542890432323 + 534322343298 = 730425903009860
3948692348692348693486235 + 5834938349234856234863423 = 9783630697927204928349658
999999999999999999999999 + 432432 + 58903 + 34 = 1000000000000000000491368
82934 + 49802390432 + 8554389 + 4789432789 + 0 + 48372934287 = 102973394831
0 = 0
0 + 0 + 0 = 0
7482343 + 0 + 4879023 + 0 + 8943242 = 21304608
3333333333 + 4723 + 3333333333 + 6642 + 3333333333 = 10000011364
Total lines = 14

Related

A problem where I'm finding the largest number you can "make" out of several numbers?

Sample input:
4
123 124 56 90
I'm to find the largest possible number you can get by combining each of these numbers together in whatever possible way.
So, the possible combinations for those numbers are {1231245690, 1241235690, 5612312490, 9012312456, 9056124123, etc.}, with the largest number being 9056124123.
I'm thinking of this problem like this: The largest number would start with the largest last digit in the set. So, the largest number here would start with "9", therefore 90 is the first number I'm concerned with. Then, I'm looking at the rest of the set with the largest last digit, which would be "5", so 56 is the second number I'm concerned with. If the largest last digit is a tie, I'd evaluate the second to last digit, etc.
For one, let me know if I'm the right track here with how I'm thinking about the problem, and if I am, which structures/types should I be looking at in order to implement this? Would this require something to do with bit manipulation? Because I'm a little stuck on that part.
You are almost on right path. There is no need for bit manipulation.
Sorting them using custom String comparator function as below is enough.
Collections.sort(inputArray, new Comparator < String > () {
public int compare(String a, String b) {
//if a = "80", b = "807"
String ab = a + b; // 80807
String ba = b + a; //80780
// now compare
return ab.compareTo(ba) > 0 ? -1 : 1;
}
});
later concat them.
#Dawood ibn Kareem Thanks for pointing out the edge case.
Carefully examine where the numbers are placed in your sample output. 90 56 124 123 The numbers go from greatest to least, depending on what the biggest digit is from the left. (Biggest first digit - #Mark)
There are possible inputs which require tiebreaking.
Given the numbers '80, 807, and 000'
Compare them from left to right.
8 0
| |\
8 0 7
Because 807 is longer than 80, compare the last bit of 807 (7) to 80.
7
|
8 0
Comparison completed, because the 8 of 80 was compared to the 7 of 807, showing that 80 should be first. Put 80 and 807 together and get 80807, and of course add the 000.
You are on a good path!
The easiest to go about types is to turn the numbers into strings. That allows you to quickly access the first, second,... digit of the original numbers. And concatenation is also much easier to do for strings!
Convert the numbers to strings, pad them with "X" on the right to make them all the same length, sort descending, concatenate removing the "X"s, there is your result.

How to replace numbers with same 'stem' that occur in two files using same logic?

So basically I have two .txt files that have the same numbers (16 digits), with the first 8 digits all being identical (eg. 12345678) and then the next 8 digits being random (eg. 38462943). What I have been trying to do is replace the numbers in both files to any unique random 16 digit numbers, using the same logic in both files.
TL;DR - The problem I'm having is how can I locate the same numbers in each file and then replace them using the same logic?
**note - the files do not just contain the numbers I want randomized, there is other information on the same line (eg.line 1 1234, 1234567800000234, 5678)
example: (notice how numbers are same but are not in same order)
File 1
1234567800000234
1234567800011523
1234567800284828
File 2
1234567800284828
1234567800011523
1234567800000234
expected output (just want numbers randomized, doesn't matter if stem is changed or not)
File 1
9348384028472894
9350148852541329
9761213142823690
File 2
9761213142823690
9350148852541329
9348384028472894
**edit - clairification
You have two real options here.
Use a pseudorandom conversion on the numbers that meet the criteria -- run it through a SHA1 or something. This will produce the same output every time, so you don't have to keep track. It won't be truly random though.
Keep a list of every substitution you've made, so that when you go through the second file you can use that list to find out what the correct substitution should be.

Generate a list of all permutations without repetition 2^9

I've been googling away like a mad man but can't anything that is specific enough for me to get started. Please forgive me for my complete noobiness and possibly diabolical skim reading ability.
Essentially, I have a questionnaire with 9 questions, each with 2 possible answers. After doing the math (2^9), I know that there are 512 permutations.
I am looking to generate a list of all the permutations, without any repetition, to provide me with a list of possible answer combinations.
I would like my output to look similar to this:
112112111
Where the 1s mean that the person selected answer "a" for a question and the 2s mean the person has selected answer "b".
Any help would be appreciated, thank you.
You are just enumerating the numbers between 0 and 512 and you want to print the string in its binary representation with 0s and 1s replaced by 1s and 2s, appropriately padded, so the following code will work:
for (int i = 0; i < 512; i++) {
System.out.println(String.format("%9s", Integer.toBinaryString(i)).replace('1', '2').replace('0', '1').replace(' ', '1'));
}
See this related question for generating a padded binary string in Java: How to get 0-padded binary representation of an integer in java?
One possible approach would be to find all the numbers between 111111111 and 222222222 that only contain 1s and 2s.
Something like:
for (i=111111111 ; i<=222222222 ; i++)
if (number_has_only_one_or_twos(i))
print i
If I am reading your question correctly, you are just wanting the binary representations of the numbers between 0 and 511 (because 511 - 0 + 1 = 512). All you need to do is find the 9 bit binary representation of each number in that range. Take 0s to mean answer B and 1s to mean answer A.
You could easily convert the binary numbers to strings and replace the 0 with 2 and print out. That's the beauty of binary representations of numbers. It is one of the best ways to find all the permutations in a given range.
Imagine finding the permutations of all elements of an array. Range the numbers from zero to the size of your array, and take a one to mean you want to use that index and a zero to not use that index. It will greatly simplify that problem whenever you run into it.

How to get the last digits of 2 power

I’m working on a problem where its demanded to get the last 100 digits of 2^1001. The solution must be in java and without using BigInteger, only with int or Long. For the moment I think to create a class that handle 100 digits. So my question is, if there is another way the handle the overflow using int or long to get a number with 100 digits.
Thanks for all.
EDITED: I was off by a couple powers of 10 in my modulo operator (oops)
The last 100 digits of 2^1001 is the number 2^1001 (mod 10^100).
Note that 2^1001 (mod 10^100) = 2*(2^1000(mod 10^100)) (mod 10^100).
Look into properties of modulo: http://www.math.okstate.edu/~wrightd/crypt/lecnotes/node17.html
This is 99% math problem, 1% programming problem. :)
With this approach, though, you wouldn't be able to use just an integer, as 10^100 won't fit in an int or long.
However, you could use this to find, say, the last 10 digits of 2^1001, then use a separate routine to find the next 10 digits, etc, where each routine uses this feature...
The fastest way to do it (coding wise) is to create an array of 100 integers and then have a function which starts from the ones place and doubles every digit. Make sure to take the modulus of 10 and carry over 1s if needed. For the 100th digit, simply eliminate the carry over. Do it 1001 times and you're done.

Find missing number in unsorted input with memory constraints

I was reading about the problem of finding the missing number from a series of 4 billion 32 bit integers in Programming Pearls, but could not quite get the solution.
Given a sequential file that contains at most 4 Billion 32-bit
integers in random order, find a 32-bit integer not on the file.
Constraint: Few hundrends of bytes of main memory but ample use of
extrernal scratch files on disk
The solution described is a process where we separate the numbers in ranges using the the upper bits (I.e. in the first pass we write those with leading 0 bit to one file and those with leading 1 bit to another.We keep going using the second bit etc.) and divide in half using as new search range the half containing less than half of the numbers in the range.
I googled and found a similar post in SO which does not quite answer my question which is how the exact number is found (I undestand how the binary search fits in separate the ranges).
The answer of #Damien_The_Unbeliever seems the most relevant but from my point of view I thought that following the process we would end up with 2 files: A file with 2 numbers in range and a file with 1 number.
By subtracting the (one) number in one file with the largest of the others we can get a missing number (no need of bitmask and I am not quite sure if we could actually apply a bitmask since the range is unknown at any point).
Am I wrong on this? Could someone help figure this out?
You needn't copy the data itself or write anything to disk; just count the members of some partition of the data to identify openings. The tradeoff is between number of passes and memory (more memory allows for more counts, smaller partitions).
Here's a solution in 8 passes. We'll partition the data using 4 bits at a time. 2^4 = 16 possible values, so we'll need 64 bytes to store counts for each of the 16 partitions. So each 4 bit nibble value has an associated count.
Make a pass through the data, incrementing the associated count matching the nibble in the first four bits of the number. If a partition is full, its count will be 2^28. Pick one of the nibbles that isn't full --- this will be the first nibble of your result.
Zero your counts and make another pass, ignoring numbers that don't match the first nibble and incrementing the count associated with the second nibble in the number. A full second nibble will have a value of 2^24. Pick one that isn't full.
Proceed in this manner until you have all 8 nibbles, and there's your answer in O(N).
If you only check one bit at a time, this would be a binary search requiring 32 passes. (EDIT: Not really a binary search, since you still have to read the values that you're skipping. That's why it's O(N). See edit below.) If you have a KB of memory for counts, you can do it in 4 passes; with 256 KB you can do it in 2 --- actually 128 KB since you could then use short ints for your counts. Here we're constrained to a few hundred bytes --- maybe 6 bits/6 passes/256 bytes?
EDIT: Li-aung Yip's solution scales better, and clearly it can be modified to partition by more than one bit in a pass. If the writing is slower than reading, then maybe the best solution would be a hybrid between this read-only answer and Li-aung Yip's disk based one.
Do a pass counting nibbles as above, then as you count the second set of nibbles, write only the numbers (or possibly just the last 28 bits of them) that match the first nibble, into 16 files according to the second nibble.
Pick your second nibble and read it to get counts for the third nibble, writing only the numbers matching the second nibble, etc. If the file is close to capacity, if the numbers are fairly uniformly distributed, or if you pick the least-full nibbles each time, you'll have to write no more than about 6.66% (1/16+1/16^2...) of the file size.
After repeated binary partitioning of your numbers into smaller and smaller files, you'll end up with:
a bunch of files that contain two numbers, which only differ in their last significant bit
one file with only one number in it.
Get the missing number by flipping the last bit of the number that's in a file by itself.
Take the example of the numbers from 0x00 to 0x07, missing 0x04:
000
001
010
011
... (missing)
101
110
111
Take 101, flip the least significant bit, and get 100, which is the missing 0x04.
4 Billion integers are representable using a 32 bit integer. XOR ing a number with itself is a standard trick to zero out a register in assembly code.
If you are guaranteed that only one number is missing, bitwise XOR on integers comes to the rescue, an O(N) solution, requiring only one additional 32 bit integer of space. Consider a simple example, a 3 bit number, thus numbers 0-7 representable and one of them is missing.
Assume 6 (110) is missing
missing = n1 XOR n2 XOR n3 XOR .. XOR n7.
= 000 XOR 001 XOR 010 XOR 011 XOR 100 XOR 101 XOR 111
Had the problem been find the missing number between 1 and 100, you would need to start of my xoring out the elements that must be excluded. AND could be used drop from a 32 bit integer range to smaller ranges by masking out bits in the number.

Categories