0.%d range between 0-100 is the same as 100-1000 - java

I have the command:
string.format("movel(p[0.%d,- 0.%d, 0.%d, -0.5121, -3.08, 0.0005])"+ "\n", averageX1, averageY1, averageY2 )
Where average value can change from 0 to 700. When the value is
averageX1 = 344
averageY1 = 222
averageY2 = 150
The command becomes:
movel(p[0.344,- 0.222, 0150, -0.5121, -3.08, 0.0005])
When one of the average becomes lower then 100:
averageX1 = 80
The command becomes
movel(p[0.**80**,- 0.222, 0150, -0.5121, -3.08, 0.0005])
I want it to become :
movel(p[0.**080**,- 0.222, 0150, -0.5121, -3.08, 0.0005]
How can I change this so it will have the value that can be from 0 tot 100.
ps. It is the "0" that must be in front of the "8".
kind regards
pascal

Change 0.%d to 0.%03d. Also see here.

Related

How to get the remaining in java

I have a java program that will run every 15th and last day of the month, i have sample that has 2 different type of amount.
this type of amount is come from the query and its already sort by sysdate, this is the result of the query:
130
500
while running the program it will automatically deduct from the first amount and the remaining will go to the second amount.
this is first amount 125.
and this is the second amount 100.
how do i do that? it really appreciated your help.
//this is the query to get the 130,500.
String getAdvanceEmployee = "SELECT AMOUNT FROM CFV_CHARGES WHERE EMP_NO = '40000124' AND TO_DATE(DUE_DATE) = '30-JUN-19' AND IS_ADVANCE = '1'";
ResultSet result1 = stmt.executeQuery(getAdvanceEmployee);
while(result1.next()){
String amount = result1.getString("AMOUNT");
//the output 130,150
//this is the query to get the 125.
String getAdvancePayment = "SELECT AMOUNT FROM CFV_CHARGES WHERE EMP_NO = '40000124' AND TO_DATE(DUE_DATE) = '30-JUN-19' AND ENTRY_TYPE = '1'";
ResultSet result2 = stmt1.executeQuery(getAdvancePayment);
while(result1.next()){
String amount = result1.getString("AMOUNT");
//the output will 125
//im confused the logic itself
}
}
amount from the query:
130
500
the first amount 125
the second amount 100
actual result is:
125
-125 // this negative comes from the amount of 130 the remaining -5 will go to the next amount which is this
100
-5
-95
//and the remaining last was -405.
you can calculate it this way :
public int calculatAmountOne(int firstAmount , int secondAmount){
//in your case firstAmount = 125 , secondeAmount = 130
int rest = firstAmount - secondeAmount ;
return rest
}
public int calculatAmountTwo(int firstAmount , int secondAmount){
//in your case firstAmount = 100, secondeAmount = -5
int rest = firstAmount + secondeAmount ;
return rest
}
so now that you create the two method to calculate the two different amount you can use them
int restOne = calculatAmountOne(125,130) // restOne = -5 ;
int restTwo = calculatAmountTwo(100,restOne) // restTwo = 95 ;
int lastRemaining = restTwo + 500 // lastRemaining = 595
you should later use number that you get instead of the number i put as example based on your question !

Electronics Shop

I have been working on this question, and after submitting my code 7 cases passed, however, 9 cases failed. The question link is here of HackerRank : Electronic Shop
Problem Statement
A girl wants to buy a keyboard, and a USB drive, she want to spend as much as possible but within budget (combining both the items). And if the price of both the items exceeds her budget, return -1 or she can't buy. What is mandatory is that She wants to buy both the items, not a single one.
Example
A range of keyboards is given in the form of an array [40, 50, 60], and USB drives is given as [5,8,12]. Her max budget is 60. Now if we sum up both the things we get two max value of combination :
40 + 12 = 52
50 + 8 = 58
Since 58 one is greater, hence she will get the items worth of 50 and 8.
Input format
The first line contains three space-separated integers b, n, and m, her budget, the number of keyboard models and the number of USB drive models.
The second line contains space-separated integers , the prices of each keyboard model.
The third line contains space-separated integers , the prices of the USB drives.
Output Format
Print a single integer denoting the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.
My Algo
1. Take answer variable as 0, and max value initialize it with first element of keyboard + first element of usb drives
2. loop through keyboard, make an inner loop for usb
3. Compare keyboard[i] + drives[j], if greater than b, then return -1.
4. Else find the max value and assign it to answer
5. return answer
My logic is as simple as the requirements, but somehow fails for the cases which has a very large number of elements in the array.
Code
static int getMoneySpent(int[] keyboards, int[] drives, int b) {
int answer = 0, maxAmount = keyboards[0] + drives[0];
//This will compare the value of i+j throughout the loop and returns the max one
for(int i: keyboards){
for(int j: drives){
// Ofcourse if all i+j values will be greater than the max budget then -1
if((i+j) > b)
answer = -1;
else if((i+j) == b){
answer = i+j;
}else{
/*If the value is smaller than the max budget, the finding the max value we get after adding them and comparing with the maxAmount variable */
if((i+j) > maxAmount){
maxAmount = i+j;
answer = maxAmount;
}
}
}
}
return answer;
}
I'm having two cases which failed,, here they are :
Failed Test Case 1
Input =>
539855 818 628
380710 674456 878173 532602 868253 721585 806107 141310 790209 212031
304748 818920 80938 322601 403071 22899 173564 153826 695108 223665
346178 957539 975830 573171 641117 932941 822666 575293 132555 479463
862209 313799 922966 606508 487172 139230 606390 898464 764983 829520
174879 317603 502680 953013 398753 825387 146407 666457 367618 121790
68188 478342 25818 506222 135197 232604 963333 79984 549654 776899
966040 122063 432596 594425 311887 936661 506256 876303 439611 277816
105689 851641 640971 333 216087 17692 619728 602689 650348 364881
152060 386548 61364 564569 780938 191826 459905 211804 58177 484711
995091 754424 57794 619638 695192 297423 983901 430435 239234 170704
142282 74647 121413 782873 303344 265448 101069 177807 692318 691774
62306 618191 509537 633333 996922 228947 814154 232698 615359 220853
306323 173792 624037 655872 527161 848207 426180 724481 130740 792273
886804 404890 449886 654224 194667 354317 367843 525624 414224 481744
827725 176927 733780 387166 769479 964040 1{-truncated-}
Expected Output
539854
For full input data here is the link : Input Array Data Full
Failed Test Case 2
Input =>
374625 797 951
183477 732159 779867 598794 596985 156054 445934 156030 99998 58097
459353 866372 333784 601251 142899 708233 651036 20590 56425 970129
722162 832631 938765 212387 779 181866 992436 183446 617621 304311
611791 524875 7068 432043 23068 291295 524893 611991 399952 139526
46677 292211 973975 366445 232824 456173 90627 785353 618526 199719
382549 514351 983453 592549 466869 46461 860135 607682 680461 170563
450601 65067 13268 949100 942415 965850 563416 808580 385504 304683
15970 97695 230946 684388 241080 440252 683418 122066 610135 495289
833383 34397 173404 909526 391149 258839 182278 662672 755532 311782
425252 520186 207989 546834 567829 184897 31321 969804 842475 775308
449856 939711 395240 895029 926868 598035 727436 922082 326615 88513
570573 196028 520952 45238 961389 325404 844725 388765 747489 271411
539814 828925 586884 356834 965473 280998 607171 542819 276062 140956
296341 802378 165305 74568 15640 987110 423497 772419 394971 198761
293555 5524 14083 815646 198888 707017 711503 729172{-truncated-}
Expected Output
374625
For full input array data for this one follow this link : Failed Test Case 2 Full Input
I'm there almost but somehow I'm confused why my code is not working for long input array elements. Any help would be appreciated, as it will make me learn new thing in my future endeavor.
You misunderstood the question. Answer should be -1 if you can't buy any keyborad+usb. Not if there is one set unaffordable, but if they all are. With your current code, what would it return if the very last set is unaffordable?
Here is a code that should work. And comments to explain:
int answer = -1; // that's the default answer.
int maxAmount = 0; // what if first keyboard + first usb are unaffordable? let's put it to 0
//This will compare the value of i+j throughout the loop and returns the max one
for(int i: keyboards){
for(int j: drives){
if((i+j) > b) {
// do nothing, it's unaffordable (and remove this block)
}else if((i+j) == b){
answer = i+j;
return answer;// it can't be more, stop the loop and return the solution
} else if((i+j) > maxAmount){ // no need to put an else, then an if both conditions are related
maxAmount = i+j;
answer = maxAmount;
}
}
}
Of course, if you remove the first empty ifblock from the above code, you will have to change the last condition in order to check if it's below the max allowed:
if((i+j)>maxAmount && (i+j)<=b)
int getMoneySpent(int keyboards_count, int* keyboards, int drives_count, int* drives, int b) {
int price=-1;
for(int i=0;i<drives_count;i++)
{
for(int j=0;j<keyboards_count;j++)
{
if((drives[i]+keyboards[j]>price) && (drives[i]+keyboards[j]<=b))
{
price=drives[i]+keyboards[j];
}
}
}
return price;
}
Javascript Solution:
function getMoneySpent(keyboards, drives, b) {
const combos = [];
let maxCost = 0
keyboards.forEach(keyboard => {
drives.forEach(drive => {
let currentComboCost = keyboard+drive;
maxCost = ((currentComboCost <= b) && (currentComboCost > maxCost)) ? currentComboCost : maxCost;
})
})
return maxCost || -1;
}

keeping track of text based hangman game in an output file

Long story short, gameplayWord is a word that was randomly determined from a list of words for a hangman game read from (in this case the easy words file). easyContentList is an ArrayList of all the data in that file. The file is 2 columns, first col - the words that can be used, 2nd - a number representing how many times the word was used. (0 in the initial file) I need to keep track of this number based on each iteration of the game.
easyFileUpdateList is a String ArrayList declared at the class level.
Problem is this basically doesn't work:
public void updateEasyFile(String gameplayWord, ArrayList<String> easyContentList) {
Integer used = 0; // represents used word count
String strUsed = "";
for (int i = 0; i < easyContentList.size() - 1; i++) {
String oneLine;
oneLine = easyContentList.get(i);
tokenizer = new StringTokenizer(oneLine);
String firstToken = tokenizer.nextToken();
if (firstToken.equals(gameplayWord)) {
used = Integer.parseInt(tokenizer.nextToken());
used++;
strUsed = used.toString();
easyFileUpdateList.add(gameplayWord + " " + strUsed + " " + "TODO");
}
if (!firstToken.equals(tokenizer.nextToken())) // add the first token of every line except the first
easyFileUpdateList.add(oneLine);
}
try {
PrintWriter printWriter = new PrintWriter(new FileOutputStream(new File("hmeasy.txt")));
for (String oneLine : easyFileUpdateList) {
printWriter.println(oneLine);
}
printWriter.close();
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
Update
Thank you, I will look into hash sets. Let me clarify a little more, I'm still not following completely.
Correct, the file will be as you said, so if the words are dog, cat, and fog the file will look like:
dog 0
cat 0
fog 0
There is a 3rd column of zeros, which is what the TODO is for but I'll worry about that later.
You are correct the problem that I am having is it is just adding a new entry with the word and then a 1 in the 2nd column. So if fog is randomly picked 3 times in a row and this method is executed it will say
dog 0
cat 0
fog 1
dog 0
cat 0
fog 1
fog 1
dog 0
cat 0
fog 1
fog 1
fog 1
what I'm looking for is:
first round:
dog 0
cat 0
fog 1
2nd round:
dog 0
cat 0
fog 2
etc...
I need to update the number in the file each time the word is randomly chosen.
Near as I can tell if your hmeasy.txt file looks like this:
firstGamePlayWord 0
secondGamePlayWord 0
And if the first entry is played it will soon look like this:
firstGamePlayWord 0
secondGamePlayWord 0
firstGamePlayWord 1 TODO
Which, I suspect, is not what you want. It's doing this because you use this line:
easyFileUpdateList.add(gameplayWord + " " + strUsed + " " + "TODO");
since this is an ArrayList add() just tacks that line at the end.
I could tell you to instead use set() with the i you worked so hard to find but that would be encouraging a bad design. You should stop using ArrayList for this. It wasn't designed for lookups.
Instead I encourage you to look at using a LinkedHashSet<String, Integer>. No need to tokenize, lookups will be fast, and everything will be in the same order it was added.
When trying to find the right data structure in java I look at this:
Thank you, I will look into hash sets. Let me clarify a little more, I'm still not following completely.
Correct, the file will be as you said, so if the words are dog, cat, and fog the file will look like:
dog 0
cat 0
fog 0
There is a 3rd column of zeros, which is what the TODO is for but I'll worry about that later.
You are correct the problem that I am having is it is just adding a new entry with the word and then a 1 in the 2nd column. So if fog is randomly picked 3 times in a row and this method is executed it will say
dog 0
cat 0
fog 1
dog 0
cat 0
fog 1
fog 1
dog 0
cat 0
fog 1
fog 1
fog 1
what I'm looking for is:
first round:
dog 0
cat 0
fog 1
2nd round:
dog 0
cat 0
fog 2
etc...
I need to update the number in the file each time the word is randomly chosen.

How to assign indexes to values in CSV using different lengths. (Java)

I'm trying to align values in two different CSV files to like indexes. One CSV has a unix time stamp every second and the other every minute. Additionally I need to mark the indexes pn various lengths of the data.
So for example I would need to mark minutes 1 - 20 (and seconds 1 - 1200) with the index of 0, then minutes 21 - 25 (1260 - 1500) with index 1, minutes 26 - 42 (1560 - 2520) with index 2, etc. etc.
The length will vary depending on the data (possibly an array that holds the different values for the lengths) that I am using so I would like to do this programatically. I'm not sure how to attack this problem. Any help would be greatly appreciated.
Edit (hopefully this helps clarify some)
I have data in one CSV that has information about audio and another that has information about bio-metric data. They will both have a column that has a unix time stamp. The data in the audio CSV is for every second and the bio-metric data is for every minute.
I want to add an additional row to the CSV's that have the same index(or key) value so that the data has a common link between the two files. If I call index 1 I want to get the data from both files that have an index of 1.
The length of an audio file will determine where the keys start and stop. So if I had an audio file that was 2 minutes long, 2 rows in the bio-metric CSV will have a key of 0 and 120 rows of the audio CSV will have a key of 0.
If that audio file had been 3 minutes long the first 3 rows of the bio-metric CSV would have a key of 0 and the first 180 rows of the audio CSV would have the a key of 0.
You can open both files, read the first line to see what the timestamp is, then read lines from the file that has the earlier timestamp until it no longer has the earlier timestamp, or ends.
If this is by-minute.csv:
1394589660,minute 1
1394589720,minute 2
and this is by-second.csv:
1394589659,second -1
1394589660,second 0
1394589661,second 1
1394589662,second 2
1394589663,second 3
1394589664,second 4
…
1394589718,second 58
1394589719,second 59
1394589720,second 60
1394589721,second 61
then this Java code:
import java.io.*;
import java.text.*;
import java.util.*;
public class Foo {
public static void main(String[] args)
throws Exception
{
BufferedReader byMinute = new BufferedReader(
new InputStreamReader(
new FileInputStream("by-minute.csv")));
BufferedReader bySecond = new BufferedReader(
new InputStreamReader(
new FileInputStream("by-second.csv")));
String byMinuteLine = byMinute.readLine();
String bySecondLine = bySecond.readLine();
while (byMinuteLine != null || bySecondLine != null) {
/* If either file is done, print lines from the other file */
if (byMinuteLine == null) {
System.out.println(indicize(bySecondLine));
bySecondLine = bySecond.readLine();
} else if (bySecondLine == null) {
System.out.println(indicize(byMinuteLine));
byMinuteLine = byMinute.readLine();
} else {
/* Otherwise print the earlier entry */
long minuteTime = getTimeStamp(byMinuteLine);
long secondTime = getTimeStamp(bySecondLine);
if (secondTime < minuteTime) {
System.out.println(indicize(bySecondLine));
bySecondLine = bySecond.readLine();
} else {
System.out.println(indicize(byMinuteLine));
byMinuteLine = byMinute.readLine();
}
}
}
}
static long getTimeStamp(String line) {
return Long.valueOf(line.split(",")[0]);
}
static String indicize(String line) {
return ((getTimeStamp(line) - 1394589660) / 20)
+ line.substring(line.indexOf(","));
}
}
will print out:
0,second -1
0,minute 1
0,second 0
0,second 1
0,second 2
0,second 3
0,second 4
0,second 5
0,second 6
0,second 7
0,second 8
0,second 9
…
2,second 55
2,second 56
2,second 57
2,second 58
2,second 59
3,minute 2
3,second 60
3,second 61
Now I know that’s not exactly what you’re looking for—but I hope that’s enough to get you started!

Level Order Traversal of a tree

In order to do level order(BFS) traversal of a generic tree I wrote the following display function for the code mentioned in the link below. The problem is that each level is printed twice. Can someone tell me why.
Original Code without this function can be found in the link below in case someone need the entire implementation else just look at the displayBFS function below and tell me why are values repeating
Level Order traversal of a generic tree(n-ary tree) in java
Thanks!
void displayBFS(NaryTreeNode n)
{
Queue<NaryTreeNode> q = new LinkedList<NaryTreeNode>();
if(n!=null)
{
q.add(n);
System.out.println(n.data);
}
while(n!=null)
{
for(NaryTreeNode x:n.nary_list)
{
q.add(x);
System.out.println(x.data );
}
n = q.poll();
}
}
Current Tree Structure for reference:
root(100)
/ | \
90 50 70
/ \
20 30 200 300
Output:
100
90
50
70
90
50
70
20
30
200
300
20
30
200
300
The problem is that you process your root-node twice: you initially add it to your queue (in the line q.add(n)), then you process it before you first get to n = q.poll(), and then you get it off the queue and process it again.
Everything else is correct, which is why you only get two copies of each non-root node: the doubling only occurs once, at root.
To fix this, either remove the line q.add(n) (since you process the root node anyway, even without it), or else change this:
while(n!=null)
{
...
n = q.poll();
}
to this:
while((n = q.poll()) != null)
{
...
}
so that you don't process the root node that initial extra time.

Categories