i'm try to make a random or unique code to payment method, for example the user must pay for Rp. 10.000 and then the user checkout and the system give the total payment with unique code in last three number.
For example user should pay for Rp. 10.000 and then the system showing Rp. 10.123
for other example, user pay for 1.000.000 and then system showing the total is 1.000.562 just unique or random in last three number
how i can make like this in java for android ?
UPDATE
i've been try this code
int someNumber = 10.000;
int lastThree = someNumber % 1000;
but when the last 3 number is '0' it return 0, when i'm change the last 3 number like 10.234 it return into 234, now how i can get the last three number when the value is like 10.000
That's because your 'lastThree' is an integer and there is no way to have an integer like 000. if you need last three number, you can use something like this:
int someNumber = 10.000;
String temp = Integer.toString(someNumber);
String lastThree = temp.substring(temp.length() - 3);
Now if you pass 10000, lastThree will be '000'.
Related
Good time of the day
I have to implement some functions on my site.
When a user enters the website, he has to enter a number of errors that should be occurred in some string. If he chooses 0, the original string will be displayed without error. If the user enters 1 in the error field, the string should be displayed with 1 error. For instance, the word "programming" should be displayed like "rrograming" or "prugramming", or adding/deleting one character to/from the string. Consequently, if the error is 2, the mistakes also should be 2.
In addition, the result should be the same every time. Someone told me to use seeds in Random class, but now I don't have idea.
I am programming in Java and some JS
Please, if you faced the same problem or experience, give me some ideas or resources to learn.
Random with a seed results in the same sequence of values every time, so use the same random every time.
The trick is using a random seed based on the word content. Otherwise you would end up doing the same mutilation pattern on all words.
The likeliness of changing a letter can be in the order of the length of the word.
And inserting twice as much as removing, both rare.
String mutilateWord(String word, int times) {
//Random random = new Random(42);
// Or better (as different words get differently mixed up:
Random random = new Random(word.hashCode());
for (int t = 0; t < times; ++t) {
int chars = word.length;
// If a letter modification has the same likeliness:
int choices = chars + 2 + 1; // change some letter + (twice) add + remove
word = switch (random.nextInt(choices)) {
case 0 -> removeRandomLetter(word, random);
case 1, 2 -> insertRandomLetter(word, random);
default -> changeRandomLetter(word, random);
};
}
return word;
}
Since java 12 one can use a switch expression as above.
The above will also mutilate the mutilations, so you might prefer to first have a times loop changing random letters (or not), and then a second times loop adding/removing letters.
Your friend's idea is correct, setting the random number seed to the same value each time will yield same results. However, you can cache the result everytime you compute it in a map for example. Setting the keys as the error number and the value as the string result. On each function call you check if the error number is cached, if that's the case you return it without computing it else you compute the result then cache it and finally return it.
Currently each time I place an order with
order.m_action = "BUY";
order.m_totalQuantity = 1;
order.m_lmtPrice = 4.00;
order.m_orderType = "LMT";
order.m_account = "U123123";
int randomNum = ThreadLocalRandom.current().nextInt(1, 5564 + 1)
m_s.placeOrder(randomNum, c, order);
I am getting the error:
1041 103 Duplicate order id
Any ideas on generating a new id for new entry orders?
Thanks.
Your orderId's shouldn't be random numbers. They have to be increasing numbers all the time. last id used +1 is the best algorithm. Duplicate order id can actually mean "not an increasing order Id".
Note that when the socket connection is started, IB returns the next valid id in the nextValidId callback, so you always know which number to start on.
Some people (me included) use number ranges for certain requests so that errors with an id can be associated with the request type. eg. I use numbers < 1000 for reqMktData type requests. Once you call placeOrder with a number > 1000, IB will never let you use a lower number for orders.
You can actually reset the orderId sequence, but I've never done that and won't until I run out of ints.
I am providing the user with two random videos for each category they have selected.
I have an ArrayList of strings for the user preferences.
I also have an ArrayList of all of the videos in the database.
So I am trying to search through each of those category preferences one by one and find two random videos that fit into it those category.
I have implemented a solution that works (On a small dataset). But I am not sure it is optimal method considering there will soon be 500 videos, 50 categories and the user will be able to select 5 category preferences:
This is how I worked it out:
//Create a new array to store the videos
ArrayList<Video> videos = new ArrayList<>();
// Create counter for the position in the user preference array
int userPrefernceArrayIndex = 0;
// Create counter for number of successful category guesses
int numberOfSuccessfulGuesses = 0;
// Keep running until we have 2 videos for each of the user preferences
while (videos.size() < MainActivity.userPrefrencesStaticArraylist.size() * 2){
// Generate a random integer to get an entry random integer from the database array
Random rand = new Random();
int randomAlarmVidInt = rand.nextInt(MainActivity.allVideosFromDatabaseStaticArray.size());
// Find the category of the random video that was chosen
String categoryForRandomGuess = MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt).getVideoCategory();
// Find the current user video category we are testing for
String currentCategoryPreference = MainActivity.userPrefrencesStaticArraylist.get(userPrefernceArrayIndex);
// Check if category of the random video we got is the same as the category user
// preference we are testing for
if (categoryForRandomGuess.equals(currentCategoryPreference)){
// If it the the preference and the random video categories match add it to the video array
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
numberOfSuccessfulGuesses++;
// If the number of successful guesses is divisible by two then we have added two correct videos
// for that category so iterate to the next category
if (numberOfSuccessfulGuesses % 2 == 0){
userPrefernceArrayIndex++;
}
}
Because of the possibility for problems I hardly ever use a while loop or random unless necessary. I also see that guessing the number may not be the best solution memory wise. So I just want to make sure I am doing it the best way to avoid issues.
Thanks for your help
Yes you can optimize your solution as following:
Currently your iterations of while loop are getting wasted: Say categoryForRandomGuess and currentCategoryPreference both are equal to "Category 1".
So numberOfSuccessfulGuesses becomes 1, but userPrefernceArrayIndex stays 0. So if in next iteration if categoryForRandomGuess is "Category 4", the iteration will be wasted even if currentCategoryPreference can become equal to "Category 4" for some other value of userPrefernceArrayIndex, that is value other than 0.
I would Suggest using a HashMap<String,Integer> where String stores the video category and Integer stores the index of first video found in database of the category.
if the Integer value is -1, it will mean we have 2 videos and we are done with the category.
Now you can eliminate the variable userPrefernceArrayIndex and your code will be a lot shorter
So your code would be:
HashMap<String,Integer> mymap = new HashMap<>();
while (videos.size() < MainActivity.userPrefrencesStaticArraylist.size() * 2)
{
// Generate a random integer to get an entry random integer from the database array
Random rand = new Random();
int randomAlarmVidInt = rand.nextInt(MainActivity.allVideosFromDatabaseStaticArray.size());
// Find the category of the random video that was chosen
String categoryForRandomGuess = MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt).getVideoCategory();
//check if the hashmap has the category
if(mymap.get(categoryForRandomGuess) == null)
{
mymap.put(categoryForRandomGuess,randomAlarmVidInt);
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
}
else
{//-1 means we already have 2 videos of the category.
if(mymap.get(categoryForRandomGuess) == -1)
continue;
//if following condition is true, then its a duplicate video
if(mymap.get(categoryForRandomGuess) == randomAlarmVidInt)
continue;//skip the rest of loop and get new value of randomAlarmVidInt
else
{
mymap.put(categoryForRandomGuess,-1);//second video added
videos.add(MainActivity.allVideosFromDatabaseStaticArray.get(randomAlarmVidInt));
}
}
}
I have this piece of code, array of 7 days, the user enter which day and how many tickets per day.
the loop will continue untill the number is greater than 50(of total tickets).
I want to pick the most wanted day, and the less one.
This is the code:
int ticketCounter=0;
final int MAX_TICKET=50;
int[] dayOfTicket=new int[7];
int mostWantedDay=dayOfTicket[0];
int LessWantedDay=dayOfTicket[0];
int indexOfWantedDay=0;
int indexOfLessWantedDay=0;
while(ticketCounter<=MAX_TICKET){
System.out.println("Enter the day number (1-7) and the number of tickets:");
int whichDay=s.nextInt();
int numberOfTicket=s.nextInt();
if(whichDay>0 && whichDay<8){
dayOfTicket[whichDay-1]+=numberOfTicket;
ticketCounter+=numberOfTicket;
}else{
System.out.println("Invalid input.\n");
}
}
}
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f+1;
}
System.out.printf("The day with max tickets is: %d \nThe day with min tickets is: %d \n\n",indexOfWantedDay, indexOfLessWantedDay);
it is picking wrong most wanted day, and always print 0 as less wanted day.
I have some problems with this checking method on the last for loop.
I will aprriciate your help.
thanks
EDIT: I took out the for loop outside the WHILE ( it was my copy paste mistake)
Part of the problem is when you initialize LessWantedDay, you initially set it to 0.
Initialize this value to the maximum possible by using
int LessWantedDay=Integer.MAX_VALUE;
Furthermore, you need to update the logic within your check to filter out 0's (assuming you want to print a day that doesn't have 0 tickets), and to update your max/min values as you parse the dayOfTicket array.
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
mostWantedDay = dayOfTicket[f];
}
if(dayOfTicket[f]<LessWantedDay && dayOfTicket[f] > 0){
indexOfLessWantedDay=f+1;
LessWantedDay = dayOfTicket[f]
}
}
Tested output:
Enter the day number (1-7) and the number of tickets:
1 10
Enter the day number (1-7) and the number of tickets:
3 5
Enter the day number (1-7) and the number of tickets:
5 20
Enter the day number (1-7) and the number of tickets:
4 15
Enter the day number (1-7) and the number of tickets:
6 10
The day with max tickets is: 5
The day with min tickets is: 3
This code is almost completely correct.
In your loops, where you say:
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f+1;
}
}
You should not set the index to "f+1", that would be the index after where we are in the loop, and we want where we actually are.
Also, this will overwrite the highest day with the last day that is more than the variable "mostWantedDay" and vise versa for "lessWantedDay. What you need to do is after you find a number of tickets that is higher than your current high, or lower than your current low, set it to that.
This way, when testing, you test against the highest or lowest one yet. As of right now, you are continuously testing against the first index's number because that is stored in most/lessWantedDay and is never changed.
After changes, your code will look like:
for(int f=0;f<dayOfTicket.length;f++){
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f;
mostWantedDay = dayOfTicket[f];
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f;
LessWantedDay[f] = dayOfTicket[f];
}
}
The reason your less wanted day is always printing 0 is because that's most likely lower than the input being entered in.
An alternative would be to set the lessWantedDay value to INTEGER.MAX_VALUE, or just the max ticket value, or another arbitrary random large number, like 9001, 100000, something like that.
An alternative alternative (in case you can't use a basic thing mentioned above) is that you can set the LessWantedDay and mostWantedDay to be the first element of the array after you get the input from the user.
int mostWantedDay;
int LessWantedDay;
<snipped out input logic/>
mostWantedDay = dayOfTicket[0];
LessWantedDay = dayOfTicket[0];
Whenever you find a most and least day, you need to update the values of mostWantedDay and LessWantedDay with the values you found
so your if statements would look like this:
if(dayOfTicket[f]>mostWantedDay){
indexOfWantedDay=f+1;
mostWantedDay = dayOfTicket[f];
}
if(dayOfTicket[f]<LessWantedDay){
indexOfLessWantedDay=f+1;
LessWantedDay = dayOfTicket[f];
}
Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.