This question already exists:
Generating a 4 digit number with an increment of 1 (java) [closed]
Closed 1 year ago.
trying to create a unique code and apart of the code format is generating a 4 digit sequence number. (increment of 1) so it would produce XX0001, XX0002.
was messing around more to do the sequence one but erm i cant seem to do it but this is what i have that doesn't work ;c
i did this but it generated xx0001 for all my items:
int number = 0;
String s = String.format("%04d", ++number);
stringBuilder.append(s);
return stringBuilder.toString();
Make number field static.
Since you are calling function it recreates it several times every time with number equal to zero.
While incrementing the value, you should do it in a loop.
for (int number = 0; number < 9999; number++) {
// not writing the code here intentionally, try to figure it out and you will do it.
// hint: append in the string builder
}
you can replace 9999 with your desired last value of the sequence.
Since you are always initializing number as 0, It will always be 1.
So the number should always be incremented by one, therefore you need to keep track of it when you access it in the function. So static variable is used. Check below the example.
class Main {
public static void main(String[] args) {
System.out.println(BuildCode());
System.out.println(BuildCode());
System.out.println(BuildCode());
}
static int number = 1; // Static variable, to keep track of latest number
public static String BuildCode() {
String code = String.format("%04d", ++number);
return code;
}
}
Note: you can create the function BuildCode and pass an int num argument which indicated the latest number used - This number can be obtained from the database, File, or a static variable - .
Related
I'm a beginner in java and this code was used in a book I'm reading, however I can't seem to figure out how it works.
The code:
public class NumberTriangleWhile {
public static void main(String[] args) {
int number = 0;
String output = "";
while (number < 10) {
output = output + number;
System.out.println(output);
number++;
}
}
}
The output:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
I don't understand why each number is printed and then somehow stored and reused in the next line, can someone explain this please?
output is a string variable. When you add something to it like this:
output = output + number;
It does not add the numerical value of the number, but instead just joins the number with the original string. For example, if output was originally 1 and number is 2, the above line will change output to 12, not 3.
The loop keeps looping until number is 10. In the first iteration, output changed from an empty string to 0. In the second iteration (number has now increased to 1), output changed to 01 (the original 0 joined with the current value of number - 1). In the third iteration, number is incremented to 2. 2 is then added to the end of output to form 012. This carries on until number is 10.
The misconception you have might be that you think output becomes empty after you print it. It does not. It will still hold the same value.
In every step inside while loop, output added with number, in Java adding something with String will result in String for example:
String str = "a" + 2;
results in str="a2";.
If we start our loop, in first step number = 0 and output="" hence output = "" + 0 that make output = "0" in second run number=1 hence output = "0" (Old output value) + 1 that make output = "01" and so on
The string output is defined outside of the while loop. It can be read from and written to inside of the while loop and its contents will be consistent in the next iteration.
If output would be defined inside of the while loop, for example:
while ( number < 10) {
String output = "";
output += number;
}
then your output would just be (with new line after each number)
0
1
2
3
4
5
6
7
8
9
Since the new number is consistent throughout each iteration of the while loop, it is "stored" as you say
Each number is getting printed because its getting concatenated.
When number=0,
And you are storing the value of number into the output as:
Output=output+number
Then the number which is an integer gets stored as a string in the output
Each time the loop runs the new incremented number gets concatenated with the previous value in the string output.
That's why all numbers are getting printed each time.
make this change in your code and you'll get your output
public static void main(String[] args)
{
int number=0;
String output="";
while(number <10)
{
output=output+number;
System.out.println(output);
number++;
output="";
}
}
Below is my code for the problem described on https://community.topcoder.com/stat?c=problem_statement&pm=14635. It keeps track of possible interleaves (as described in the problem description given) through a static variable countPossible.
public class InterleavingParentheses{
public static int countPossible = 0;
public static Set<String> dpyes = new HashSet<>(); //used for dp
public static Set<String> dpno = new HashSet<>(); //used for dp
public static void numInterleaves(char[] s1, char[] s2, int size1, int size2){
char[] result = new char[size1+size2];
numInterleavesHelper(result,s1,s2,size1,size2,0,0,0);
}
public static void numInterleavesHelper(char[] res, char[] s1, char[] s2, int size1, int size2, int pos, int start1, int start2){
if (pos == size1+size2){
if (dpyes.contains(new String(res))){
countPossible+=1;
}
else{
if(dpno.contains(new String(res))){
countPossible+=0;
}
else if (isValid(res)){
dpyes.add(new String(res));
countPossible+=1;
}
else{
dpno.add(new String(res));
}
}
}
if (start1 < size1){
res[pos] = s1[start1];
numInterleavesHelper(res,s1,s2,size1,size2,pos+1,start1+1,start2);
}
if (start2 < size2){
res[pos] = s2[start2];
numInterleavesHelper(res,s1,s2,size1,size2,pos+1,start1,start2+1);
}
}
private static boolean isValid(char[] string){
//basically checking to see if parens are balanced
LinkedList<Character> myStack = new LinkedList<>();
for (int i=0; i<string.length; i++){
if (string[i] == "(".charAt(0)){
myStack.push(string[i]);
}
else{
if (myStack.isEmpty()){
return false;
}
if (string[i] == ")".charAt(0)){
myStack.pop();
}
}
}
return myStack.isEmpty();
}
}
I use the scanner class to put in the input strings s1 = "()()()()()()()()()()()()()()()()()()()()" and s2 = "()()()()()()()()()()()()()()()()()" into this function and while the use of the HashSet greatly lowers the time because duplicate interleaves are accounted for, large input strings still take up a lot of time. The sizes of the input strings are supposed to be at most 2500 characters and my code is not working for strings that long. How can i modify this to make it better?
Your dp set is only used at the end, so at best you can save an O(n), but you've already done many O(n) operations to reach that point so the algorithm completexity is about the same. For dp to be effective, you need to be reducing O(2^n) operations to, say O(n^2).
As one of the testcases has an answer of 487,340,184, then for your program to produce this answer, it would need that number of calls to numInterleavesHelper because each call can only increment countPossible by 1. The question asking for the answer "modulo 10^9 + 7" as well indicates that there is a large number expected as an answer.
This rules out things like creating every possible resulting string, most string manipulation, and counting 1 string at a time. Even if you optimized it, then the number of iterations alone makes it unfeasible.
Instead, think of algorithms that have about 10,000,000 iterations. Each string has a length of 2500. These constraints were chosen on purpose so that 2500 * 2500 fits within this number of iterations, suggesting a 2D dp solution.
If you create an array:
int ways[2501][2501] = new int[2501][2501];
then you want the answer to be:
ways[2500][2500]
Here ways[x][y] is the number of ways of creating valid strings where x characters have been taken from the first string, and y characters have been taken from the second string. Each time you add a character, you have 2 choices, taking from the first string or taking from the second. The new number of ways is the sum of the previous ones, so:
ways[x][y] = ways[x-1][y] + ways[x][y-1]
You also need to check that each string is valid. They're valid if each time you add a character, the number of opening parens minus the number of closing parens is 0 or greater, and this number is 0 at the end. The number of parens of each type in every prefix of s1 and s2 can be precalculated to make this a constant-time check.
Queustion 1: Can we generate 8 digit unique 9-10 million numeric only strings?
Queustion 2: How do I generate 9 to 10 million unique 'numeric only' string in one program run? These keys will be uploaded to db to be used for next 6 months. I tried
Math.floor(Math.random() * 10000000) + 10000000;
in a loop, but produces lots of duplicates. To eliminate duplicates, I used HashSet, but I get Exception in thread "main" java.lang.OutOfMemoryError: Java heap space after ~140xxxx size in the set. Any other approach to generate this output?
The standard approach to creating a block of unique random numbers is to first create the numbers in order (for instance, in an array), then shuffle them.
You need to be careful in your choice of shuffling algorithms; I hear Fisher-Yates is pretty good.
If it is one time run just increase the heap by using command line option -Xmx2048M (2G is just and example).
Q1. Can we generate 8 digit unique 9-10 million numeric only strings?
yes you can generate 10000000 8 digit unique numeric only strings using 10 digits 1,2,3,4,5,6,7,8,9,0
If you are writing correct logic for all possible combination you will not get any duplicate but just to be in safe side you can use set.
As you are getting java.lang.OutOfMemoryError error that's because you are generating that many numbers and keeping it in memory. solution for this is you generate some small chunk of numbers and save it into the database and then clear the list and again fill with the next chunk of numbers and keep it repeating untill you saved all the numbers into the database.
Q2. How do I generate 9 to 10 million unique 'numeric only' string in one program run?
here is a combination code you can use it to achieve your goal
public class Combination{
public static int count = 0;
public static ArrayList<String> list;
public Combination(){
list = new ArrayList<String>();
}
public static void main(String[] args){
Combination c = new Combination();
Scanner sc = new Scanner(System.in);
String str = sc.next();
int num = sc.nextInt();
if(num>str.length()){
System.out.println("This combination is not possible");
System.out.println(num+" should be less than or equal to the length of the string "+str);
}else{
System.out.println("Processing....");
char[] array = new char[num];
c.fillNthCharacter(0,array,str);
System.out.println("Total combination = "+count);
}
}
public static void fillNthCharacter(int n,char[] array,String str){
for(int i=0;i<str.length();i++){
array[n]=str.charAt(i);
if(n<array.length-1){
fillNthCharacter(n+1,array,str);
}else{
count++;
//System.out.println(new String(array));
list.add(new String(array));
if(list.size()>100000){
//code to add into database
list.clear();
}
}
}
}
}
I simply increased the vm memory size and ran the application to generate 9 million coupons. Thank you everyone for taking interest in answering this.
You can store them in a database and put an index on the column where you store them (with obiouvsly a unique constraint and a loop to retry if a DuplicateKeyException occurs). Even better, you can write a stored procedure to do it and operate directly on the database. I use this approach when generating short codes for urls (that can lead to duplicates). If your time requirements are not stringent, this is a viable option.
This question already has answers here:
While loop doesn't run a indexOf search
(4 answers)
Closed 8 years ago.
I'm trying to find out how many times one string appears in another. For my testing, I'm using "ea" for wordOne and "Ilikedthebestontheeastbeachleast" for wordTwo. My output is returning 2 for my "appearance" variable, which should store how many times "ea" appears in wordTwo. It should return 3.
I've tried messing with variable initializations, and trying to think of the math differently, but I'm pretty much out of ideas.
Here's the relevant code section:
int wordTwoLength = wordTwo.length();
System.out.println(wordTwoLength);
while (wordTwoLength > 0)
{
positionCount = wordTwo.indexOf(wordOne, positionCount);
appearances++;
wordTwoLength = (wordTwoLength - positionCount);
}
System.out.println(appearances);
Thanks!
Edit: I forgot to add that I tried other test inputs and got crazy outputs. It would return numbers way higher than expected for some, and lower for others.
So now the problem is that .indexOf still returns the true index of "ea" in wordTwo - it doesn't take into account where you start from. Also, setting positionCount equal to where you find the word and then searching from that position again is just going to make you immediately find the same instance of that word, not the next one.
The index of the first instance of "ea" in wordTwo is 18, so wordTwoLength will be set to 32-18, or 14. Then you'll find the same instance of ea in wordTwo, and wordTwoLength will be set to 14-18, or -4. Then you'll exit the while loop, with appearances being 2.
for (int index = 0; (index = wordTwo.indexOf(wordOne, index)) > -1; index ++)
appearances ++;
Try this simpler code:
class Demo{
public static void main(String[] args){
String wordOne = "ea";
String wordTwo = "Ilikedthebestontheeastbeachleast";
String[] arr = wordTwo.split(wordOne);
int cnt = arr.length - 1;
System.out.printf("[%s] has occured for %s time(s) in [%s]", wordOne, cnt, wordTwo);
}
}
You can simplify your above work by "Converting String to Character array".Because it will be more Efficient(I think).I have provided a sample code here,
String wordOne="Ilikedthebestontheeastbeachleast";
String wordTwo="ea";
int count=0;
char[] arrayOne=wordOne.toCharArray();
char [] arrayTwo=wordTwo.toCharArray();
for(int i=0;i<=((arrayOne.length)-1);i++)
{
if(arrayTwo[0]==arrayOne[i]&&arrayTwo[1]==arrayOne[i+1])
count+=1;
}
System.out.println("Pattern found "+count+" times.");
This will suits your need but using For loop.
have to do an exercise called SpanishNumbers. Create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are:
1 uno, 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
package chapter7java;
import java.util.Scanner;
/**
*
* #author Eric
*/
public class SpanishNumbers {
public static void spanNum(int num, String word) {
for (int i = 1; i<= num; i++) {
if (num = 1) {
System.out.println("Uno");
}
}
}
public static void main (String [] args) {
for (int i = 1; i<=10; i++) {
System.out.println(i);
}
}
}
So before you freak out, I'm having trouble even starting this thing so maybe give me some tip hows I can do what it asks, not finish the work necessarily. What I posted was just crap so just let me know how I can go about starting this. Thanks in advance! This is beginner java so keep it simple.
The function spanNum needs only an int as a parameter. Remove the String parameter passed to it. Replace
public static void spanNum(int num, String word) {
with
public static void spanNum(int num) {
The spanNum function is supposed to print the Spanish for one number (the one passed in parameter num). So there should be no loop. Also = is an assignment statement, not a comparison operator. The comparison operator is ==. So the statement to test if num is equal to 1 would be if(num == 1).
In the main, you could call spanNum in the loop for all values of i.
You're going to want to create an array to hold your spanish numbers.
String[] numbers = {"uno", "dos", "tres", ......}
Declare that inside your spanNum method; you then just print out the value at index i to convert it into spanish. Just remember that array indices start at 0, so you'll need to shift
your index by one.
First of all, the line if(num = 1) should be if(num == 1) since = assigns and == compares. Second, when you are planning to take one number and do different things based on its value, a switch block may be more useful than multiple if...else if blocks. Third, in your main method, you are simply outputting the loop control variable, i, each time instead of calling spanNum().