0

I need some hints on this: I have lets say a list or a sequence of years with

int startYear = 2010;
int endYear = 2050;

and i have an enum with letters and digits as year codes.

I need this for Barcode generation where i have a timestamp that need to be coded into 3 digits/letters, so i need to map year month and day to a code position.

What i need to do is to map the year sequence to the codes list into a HashMap of keys (the year numbers) and values (the year codes),

but obviously the codes list is not as long as the year sequence so i need to check when the last index is reached and if yes i need to reloop through the codes list until the end of the year sequence is reached.

what i need to achieve is this:

year    code
2012     C
2013     D
.
.
2030     Y
2031     1
.
.
2039     9
2040     A

and so on...

unfortunately i could not figure out a way how to do this, couse I'm pretty new to java so I'd appreciate if someone can give me some advice..

2
  • Are your codes stored in an enum or in a list? Commented Aug 11, 2016 at 10:01
  • the codes are stored in an enum where per function getCodes an ArrayList<String> is returned Commented Aug 11, 2016 at 10:22

4 Answers 4

1

Simply use the % operator to calculate the code index

List years = ...
List codes = ...
for (int i = 0, yearsSize = years.size(), codesSize = codes.size(); i < yearsSize; i++) {
     map.put(years.get(i), codes.get(i % codesSize));
}

See Remainder Operator (%).

Sign up to request clarification or add additional context in comments.

Comments

0

How about something like this?:
Assuming:

public enum Code {
    A, B, C, ... Z, 1, ... 9;
}
List<Integer> years;
HashMap<Integer,Code> map;

Just add an index for the code which will initialize if too big:

int i = 0;
for(Integer year : years) {
    map.push(year, Code.values()[i];
    i++;
    if(i >= Code.values().length) {
        i = 0;
    }
}

Comments

0

Before encoding the year, modulous the year so the %year% loops:

int yearToEncode = 2012 + ((year - 2012) % MyEnum.values().length);

Assuming that 2012 is "year zero".

Then you can use:

MyEnum encodedYear = MyEnum.values()[yearToEncode - 2012];

But your code would be a whole lot simpler if year zero was arbitrary:

MyEnum[] codes = MyEnum.values();
MyEnum encodedYear = codes[year % codes.length];

Comments

0

try this you can even change the start year and end year

int yStart = 2010;
int yEnd = 2050;
String s  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
int pos = 0;
for(int i = yStart; i < yEnd; i++){
    pos = (i - yStart)%s.length();
    map.put(i, s.substring(pos, pos+1));// put in map
    System.out.println(i + "  " + s.substring(pos, pos+1));

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.