Example search name by a specific number - string

Example
I would like to compare the SDK number with a value and display the name of the value example sdk 25 = nougat
String sdks = Build.VERSION.SDK;
int Alpha = 1;
int Beta = 2;
int CupCake = 3;
int Donut = 4;
int Eclair= 5-7;
int Froyo = 8;
int GingerBread = 9-10;
int HoneyComb = 11-13;
int IceCreamSandwich = 14-15;
int JellyBean = 16-18;
int KitKat = 19-20;
int Lollipop = 21-22;
int MarshMellow = 23;
int Nougat = 24-25;
int Oreo = 26-27;
int Pie = 28;
resultview.setText(sdks);

I think a Map solution would be simple to implement given its a small range
public static void main(String []args){
Map<Integer,String> sdkMap = new HashMap<Integer,String>();
//populate other fields similarly
HelloWorld.populateRange("24-25","Nougat",sdkMap);
System.out.println(sdkMap.get(24));
}
public static void populateRange(String range,String name, Map<Integer,String> sdkMap){
String[] splitNumbers = range.split("-");
int low = Integer.parseInt(splitNumbers[0]);
int high = Integer.parseInt(splitNumbers[1]);
for(int i=low;i<=high;i++){
sdkMap.put(i,name);
}
}
Working example

Related

Map value is not getting increased when it finds duplicate key. Please advise

I am new to Java.. Please help me to get required output for the below code.
Map value has to be counted when month value is repeated
Issue occurs due to 2 sublist which is executing on a different threads. Please advise if there is any modification needs to be done in this code in order to rectify map value to get counted.
int size = inputList.size();
int listSize = size/numberOfThreads;
List<String> tmplist1 = inputList.subList(0, listSize);
int count = listSize;
for (int i=0;i<numberOfThreads;i++)
{
if(listSize <= size) {
t1 = new TotalOrderThread();
t1.setInput(tmplist1);
Thread thread = new Thread(t1);
thread.start();
thread.join();
if(listSize < size)
tmplist1 = inputList.subList(listSize, listSize+count);
listSize=listSize+count;
}
*
Input:
123,03/04/2005
234,04/05/2005
567,03/04/2005
789,01/01/2005
Output:(month 4 is repeated twice but the value is not getting counted as 2). Please help to find out the mistake. Also, Is there anyway to print the month value as "MMM" format while iterating map?
4 1
5 1
1 1
4 1
*
Map<Integer,Integer> orderMap = new HashMap<>();
for(int i=0;i<this.input.size();i++)
{
String details = input.get(i);
String[] detailsarr = details.split(",");
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate id = LocalDate.parse(detailsarr[1], f);
int month = id.getMonthValue();
if(orderMap.containsKey(month))
{
int count = orderMap.get(month);
orderMap.put(month, count+1);
}
else
{
orderMap.put(month, 1);
}
}
for(Map.Entry<Integer,Integer> entry : orderMap.entrySet())
{
int month3 = entry.getKey();
int value = entry.getValue();
System.out.println(month3+ " " +value);
}
}
I tried your code like below. This one works.
Map<Integer,Integer> orderMap = new HashMap<>();
String[] input = {"123,03/04/2005", "234,04/05/2005", "567,03/04/2005", "789,01/01/2005"};
for(int i=0;i<input.length;i++)
{
String details = input[i];
String[] detailsarr = details.split(",");
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate id = LocalDate.parse(detailsarr[1], f);
int month = id.getMonthValue();
if(orderMap.containsKey(month))
{
int count = orderMap.get(month);
orderMap.put(month, count+1);
}
else
{
orderMap.put(month, 1);
}
}
for(Map.Entry<Integer,Integer> entry : orderMap.entrySet())
{
int month3 = entry.getKey();
int value = entry.getValue();
System.out.println(month3+ " " +value);
}

How to incorporate mod in rolling hash of Rabin Karp algorithm?

I am trying to implement the Rabin Karp algorithm with mod. The hash function which i am using is:
H1= c1*a^k-1 + c2*a^k-2 +c3*a^k-3 +…+ck*a^0
Here cx is the ASCII value of the character. And to roll it I first drop the first term by subtracting it, then multiply by a and add the new term by multiplying it with a^0.
Now the problem is to deal with large values i have used mod operations but doing that i am not able to roll it correctly. My code is as follows:
public class RabinKarp {
private static final int base = 26;
private static final int mod = 1180637;
public static void main(String[] args) {
String text = "ATCAAGTTACCAATA";
String pattern = "ATA";
char[] textArr = text.toCharArray();
char[] patternArr = pattern.toCharArray();
System.out.println(getMatchingIndex(textArr, patternArr));
}
public static int getMatchingIndex(char[] textArr, char[] patternArr) {
int n = textArr.length;
int m = patternArr.length;
int patternHash = getHashForPatternSize(patternArr, m);
int textHash = getHashForPatternSize(textArr, m);
for(int i = 0; i < n-m; i++) {
if(patternHash == textHash && checkMatch(textArr, patternArr, i, m))
return i;
textHash = rollingHash(textArr, textHash, i, m);
}
return -1;
}
public static boolean checkMatch(char[] textArr, char[] patternArr, int i, int m) {
for(int j = 0; j < m; j++,i++) {
if(textArr[i] != patternArr[j])
return false;
}
return true;
}
public static int rollingHash(char[] textArr, int textHash, int i, int m) {
return (textHash * base - modularExponentiation(base, m, mod) * (int)textArr[i] + (int) textArr[i+m])%mod;
}
public static int getHashForPatternSize(char[] arr, int m) {
int hash = 0;
for(int i = 0, p = m; i < m; i++, p--) {
hash = (hash%mod + calcHash(arr[i], p)%mod)%mod;
}
return hash;
}
public static int calcHash(char alphabet, int p) {
return (((int) alphabet)%mod * modularExponentiation(base, p, mod)%mod)%mod;
}
public static int modularExponentiation(int base, int p, int mod) {
if(p == 0)
return 1;
if(p%2 == 0)
return modularExponentiation((base*base)%mod, p/2, mod);
else
return (base*modularExponentiation((base*base)%mod, (p-1)/2, mod))%mod;
}
}
Problem is that textHash and patternHash do not match at any point. I am sure that the problem is with the mod operations. Can anyone tell how to have mod as well as to use the rolling hash correctly. I would be very thankful.
The usual way to compute a Rabin-Karp rolling hash is to consider the characters in big-endian order, rather than your little-endian solution. This makes the arithmetic much easier since it avoids division. Modular division is non-trivial and you cannot simply implement it as (p/q)%b.
If we take the rolling hash as
H0…k-1 = (c0*ak-1 + c1*ak-2 + c2*ak-3 …+… ck-1*a0) mod b
Then the next term is:
H1…k = ( c1*ak-1 + c2*ak-2 …+… ck-1*a1 + ck*a0) mod b
And we can easily see that
H1…k = (a * H0…k-1 - c0*ak + ck) mod b
If we then precompute m == ak mod b, that becomes:
H1…k = (a * H0…k-1 - m * c0 + ck) mod b
which is much less work on each iteration, and does not depend on division at all.

JXL Get Cell Address

I am using the Java jxl api v2.6.16 to generate Excel Spread Sheet. Like the above title puts it, how do get an address of a Cell or More specifically Writable cell that I am writing to if all I have is the cell's column and row? Or do I have to write an algorithm which can generate that?
Thanks in advance.
You can use this code. Hope this help. You can use it in this way:
cellAddress(cell.getRow() + 1, cell.getColumn()) if cell is defined like Cell cell = someCell;
private String cellAddress(Integer rowNumber, Integer colNumber){
return "$"+columnName(colNumber)+"$"+rowNumber;
}
private String columName(Integer colNumber) {
Base columns = new Base(colNumber,26);
columns.transform();
return columns.getResult();
}
class Base {
String[] colNames = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");
String equalTo;
int position;
int number;
int base;
int[] digits;
int[] auxiliar;
public Base(int n, int b) {
position = 0;
equalTo = "";
base = b;
number = n;
digits = new int[1];
}
public void transform() {
if (number < base) {
digits[position] = number;
size();
} else {
digits[position] = number % base;
size();
position++;
number = number / base;
transform();
}
}
public String getResult() {
for (int j = digits.length - 2; j >= 0; j--) {
equalTo += colNames[j>0?digits[j]-1:digits[j]];
}
return equalTo;
}
private void size() {
auxiliar = digits;
digits = new int[auxiliar.length + 1];
System.arraycopy(auxiliar, 0, digits, 0, auxiliar.length);
}
}
the Address is made up of the Column and Row.
In A1 Notation it is written like: Range("A1") where the column 1 is rtepresented by the letter "A" and the row is 1
In R1C1 Notation it would be written like this: R1C1 where the column is 1 and the row is 1
They would be used like this:
Cells(1,1).font.bold=true ' row 1, column 1
range("A1").font.bold=true
to get the address from a Reference, retrieve the Address property of the Cells or Range object as below:
sAddress=cells(1,1).address
which would return A$1$
and in JXL, String rangeAddress = range.getAddress();
You can get the column by it's alpha index by using one of the methods below. he simple method just casts an integer to a ASCII character. The second method allows the use of a custom alphabet.
Simple Method
public class LookupUtil {
public static String cellAddress(int row, int col) {
return String.format("$%s$%d", columnName(col), row);
}
public static String columnName(int index) {
int div = index + 1;
StringBuffer result = new StringBuffer();
int mod = 0;
while (div > 0) {
mod = (div - 1) % 26;
result.insert(0, (char) (65 + mod));
div = (int) ((div - mod) / 26);
}
return result.toString();
}
}
Advanced Method
public class LookupUtil {
private static final char[] ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
public static String cellAddress(int row, int col) {
return String.format("$%s$%d", columnName(col, ALPHA), row);
}
public static String columnName(int index, char[] alphabet) {
int div = index + 1;
StringBuffer result = new StringBuffer();
int mod = 0;
while (div > 0) {
mod = (div - 1) % alphabet.length;
result.insert(0, alphabet[mod]);
div = (int) ((div - mod) / alphabet.length);
}
return result.toString();
}
}

j2me drawChar abnormal character spacing?

I write some code to draw a text on a j2me canvas without using drawString.
For some reasons I can't use drawString method.
So, when I run my program, I deal with abnormal character spacing.
Please help me to solve the problem. This is my code:
public void paint(Graphics g) {
...
String str = ... ;
int x0 = 10;
int y0 = getHeight() - 50;
Font f = g.getFont();
int charWidth = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
charWidth = f.charWidth(ch);
x0 += charWidth;
g.drawChar(ch, x0, y0, 0);
}
...
}
instead use this:
public void paint(Graphics g) {
...
String str = ... ;
int x0 = 10;
int y0 = getHeight() - 50;
Font f = g.getFont();
int lastWidth = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
g.drawChar(ch, x0 + lastWidth, y0, 0);
lastWidth += f.charWidth(ch);
}
...
}
In your drawChar method,you use 0(it is equal to Graphics.TOP|Graphics.LEFT) so you would increase "lastWidth" after draw current char,or use another anchor(for example Graphics.TOP|Graphics.RIGHT) for drawChar.

c# : selecting a variable from several, randomly

I have several independant int variables in my program. Is there a way I can feed randomly the value of one of them into a new int variable or an int array ? Thanks in Advance.
EDIT:
here's a pseudocode to demonstrate:
int A1 = 1;
int A2 = 3;
int RESULT = 0;
Random rand = new Random();
Result = rand.Next(0, A1 || A2)]; //Result holds the value/variable name of A1 or A2
You could put all the ints you want to choose from in a new array and then select a random value from it. For example:
int value1 = 3;
int anotherValue = 5;
int value2 = 1;
int[] selectableInts = new int[3] { value1, anotherValue, value2 };
Random rand = new Random();
int randomValue = selectableInts[rand.Next(0, selectableInts.Length)];
How about this:
// create an array of your variables
int[] A = new int[] {1,3};
// Instantiate Random object.
Random rand = new Random();
// Get a value between 0 and the lenght of your array.
// This is equivalent to select one of the elements of the array.
int index = rand.Next(0,A.Length);
// Get the value from the array that was selected at random.
int Result = A[index];
I had some trouble myself and found this thread, but its code is for Ints only, so I was stuck for some time to make it work for other than ints.
I think #David gave me some idea how to make it work.
This is my version for using types other than ints.
Vector2 down = new Vector2(0, 1);
Vector2 left = new Vector2(-1, 0);
Vector2 right = new Vector2(1, 0);
List<Vector2> possibleDirections = new List<Vector2>()
{
down,
left,
right
};
Random random = new Random();
Vector2 selectedRandomDirection = possibleDirections[random.Next(0, possibleDirections.Count)];
// this is the result
Vector2 direction = selectedRandomDirection;

Resources