I'm developing multiple choice question game. It has four integer choices. Options are stored in an array list. I want to display the choices with the elements in the array in random order with no repetition each time. Please give me the solution.
int ans[] = new int[] { sum, sum + 1, sum + 2, sum - 1 };
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i : number) {
number.add(ans[i]);
}
Collections.shuffle(number);
but1.setText("" + number.get(0));
but2.setText("" + number.get(1));
but3.setText("" + number.get(2));
but4.setText("" + number.get(3));
makeRandomArray returns an random int array between your size input. So if you pass size = 4, it returns an random array from 0 to 3, then handle your problem with random output. Hope this help!
/**
* Make an int random array with value from 0 to max
* #param size: size = max + 1
* #return result: an int array
*/
private int[] makeRandomArray(int size) {
int result[] = new int[size];
List<Integer> ascesdingArray = new ArrayList<>();
for (int i = 0; i < size; i++) {
ascesdingArray.add(i);
}
for (int i = 0; i < size; i++) {
int randomValue = random(ascesdingArray);
result[i] = randomValue;
}
return result;
}
/**
* Get random value in input array
* #param ascesdingArray
* #return randomValue: random element from input array
*/
private int random(List<Integer> ascesdingArray) {
int max = ascesdingArray.size() - 1;
int randomValue = 0;
if (max > 0) {
// get random index and it's value
int index = new Random().nextInt(max);
randomValue = ascesdingArray.get(index);
// remove value got from array so it will not be duplicated
ascesdingArray.remove(index);
} else if (max == 0) {
randomValue = ascesdingArray.get(0);
}
return randomValue;
}
First of all, your code will produce an IndexOutOfBoundsException due to you are iterating over an empty list making the result list empty and next your are picking four items from that empty list.
Finally, answering your question for your specific situation the next code will work:
It's a simplified and corrected working version of your code (tested):
List<Integer> number = Arrays.asList(sum, sum + 1, sum + 2, sum - 1);
Collections.shuffle(number);
but1.setText("" + number.get(0));
but2.setText("" + number.get(1));
but3.setText("" + number.get(2));
but4.setText("" + number.get(3));
Hope it helps
Related
I want to get 4 random value(different from each other) 1 to 4 in Android.
I wrote a code like this. But the values aren't different from each other.
Random random = new Random();
int number, idSearch[]=new int[4];
number = random.nextInt(4);
idSearch[0] = number;
for (int i = 1; i < 4; i++)
{
number = (int) random.nextInt(4);
for (int j = 0; j <= i; j++)
{
if (idSearch[j] == number) {
number = random.nextInt(4);
}
}
idSearch[i] = number;
}
Where is error? Can you help me?
I reckon the easiest way of generating a List<Integer> with values from 1 to 4 (inclusive) in a random order would be to first create a List<Integer> with the initial values and shuffle it:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Collections.shuffle(list);
System.out.println(list);
>> [4, 1, 3, 2]
Keep in mind that this list cannot be added to or removed from.
If you would like it to be mutable, simply pass it to the constructor of an ArrayList:
List<Integer> mutableList = new ArrayList<>(list);
Remember to import java.util.*
If you are using JDK1.8 then you can generate numbers from 1 to 4 in random order, you can use new Random().ints() as shown below:
int[] randoms = new Random().ints(1,5).distinct().limit(4).distinct().toArray();
If you are using JDK1.7 or earlier, you need to use Collections.shuffle() rather than you re-inventing the shuffling the logic.
You have to create new object Random and pls use second for behind fist for.
I am not a Android developer, but my team members required the same thing I did on the web. I required a function to which I pass any three colors (e.g. red,blue,green), and I will pass a count, e.g. 100.
Definition of function
function getColorArray(mincolor,midcolor,maxcolor,100){
return colorarray;
}
When I have to call function:
getColorArray(red,yellow,green,100)
So it will give a array of 100 colors from a red,blue,green color scale.
I did it in Javascript. Here is the fiddle link.
I want the same output in Android.
This code does a simple line interpolation (c1 - c2, c2 - c3) . Your example JS code has richer options than this simple example (non linear interpolations), but I think this should help you get started.
You should probably define some custom colors if you're going to let the users name the colors - the default range of system colors is pretty limited (at least with java.awt.Color predifined colors, that is).
import java.awt.*;
import javax.swing.*;
import java.lang.reflect.Field;
public class ColorTest {
public static void main(String[] args) {
int n = args.length > 0 ? Integer.parseInt(args[0]) : 5;
Color[] test = getColorArray("red", "green", "blue", n);
for(Color c : test) {
System.out.println(c);
}
}
public static Color[] getColorArray(String c1, String c2, String c3, int n) {
Color[] inputColors = new Color[3];
try {
Field field1 = Color.class.getField(c1);
Field field2 = Color.class.getField(c2);
Field field3 = Color.class.getField(c3);
inputColors[0] = (Color) field1.get(null);
inputColors[1] = (Color) field2.get(null);
inputColors[2] = (Color) field3.get(null);
} catch (Exception e) {
System.err.println("One of the color values is not defined!");
System.err.println(e.getMessage());
return null;
}
Color[] result = new Color[n];
int[] c1RGB = { inputColors[0].getRed(), inputColors[0].getGreen(), inputColors[0].getBlue() };
int[] c2RGB = { inputColors[1].getRed(), inputColors[1].getGreen(), inputColors[1].getBlue() };
int[] c3RGB = { inputColors[2].getRed(), inputColors[2].getGreen(), inputColors[2].getBlue() };
int[] tmpRGB = new int[3];
tmpRGB[0] = c2RGB[0] - c1RGB[0];
tmpRGB[1] = c2RGB[1] - c1RGB[1];
tmpRGB[2] = c2RGB[2] - c1RGB[2];
float mod = n/2.0f;
for (int i = 0; i < n/2; i++) {
result[i] = new Color(
(int) (c1RGB[0] + i/mod*tmpRGB[0]) % 256,
(int) (c1RGB[1] + i/mod*tmpRGB[1]) % 256,
(int) (c1RGB[2] + i/mod*tmpRGB[2]) % 256
);
}
tmpRGB[0] = c3RGB[0] - c2RGB[0];
tmpRGB[1] = c3RGB[1] - c2RGB[1];
tmpRGB[2] = c3RGB[2] - c2RGB[2];
for (int i = 0; i < n/2 + n%2; i++) {
result[i+n/2] = new Color(
(int) (c2RGB[0] + i/mod*tmpRGB[0]) % 256,
(int) (c2RGB[1] + i/mod*tmpRGB[1]) % 256,
(int) (c2RGB[2] + i/mod*tmpRGB[2]) % 256
);
}
return result;
}
}
I have a string like
This is a very nice sentence
I break it into separate words and store in String[] with:
String[] words = s.split(" ");
How can I take a specific percentage on the total number of words (lets say 2 of 6 words) and substitute these 2 words with something else. My code so far:
//Indexes in total
int maxIndex = words.length;
//Percentage of total indexes
double percentageOfIndexes = 0.20;
//Round the number of indexes
int NumOfIndexes = (int) Math.ceil( maxIndex * (percentageOfIndexes / 100.0));
//Get a random number from rounded indexes
int generatedIndex = random.nextInt(NumOfIndexes);`
First, calculate how many words you want to replace:
int totalWordsCount = words.length;
double percentageOfWords = 0.20;
int wordsToReplaceCount = (int) Math.ceil( totalWordsCount * percentageOfWords );
Then, knowing how many words you want to replace, get that many random indexes, and just swap words at those indexes:
for (int i=0; i<wordsToReplaceCount; i++) {
int index = random.nextInt(totalWordsCount);
//and replace
words[index] = "Other"; // <--- insert new words
}
NOTE: Just remember that the smaller the number of words, the bigger discrepancy between your percentage, and actual number of words to replace, eg. 20% from 6 words is 1.2 word, which becomes 2 after Math.ceil(), and 2 is 33.33% from 6.
Suppose I have an EditText:
Editable e = editText.getEditableText(); // length == 2
// ...attach a span start=0, end=2 to e...
int index = e.nextSpanTransition(0, 2, Object.class);
According to this: http://developer.android.com/reference/android/text/Spanned.html
index should be 0, since it says
Return the first offset greater than or equal to start where a markup object of class type begins or ends
But index is 2. Is this a bug or am I missing something?
Or am I even misinterpreting the docs, since it could mean "greater than start where a markup object begins, OR, equal to start where a markup object ends"?
The documentation also says:
or limit if there are no starts or ends greater than or equal to start but less than limit
Where limit is the second parameter (2 in your case). Your span does not satisfy less than limit because it is equal to it. So it returns limit.
Here is the source code that explains it:
/**
* Return the next offset after <code>start</code> but less than or
* equal to <code>limit</code> where a span of the specified type
* begins or ends.
*/
public int nextSpanTransition(int start, int limit, Class kind) {
int count = mSpanCount;
Object[] spans = mSpans;
int[] starts = mSpanStarts;
int[] ends = mSpanEnds;
int gapstart = mGapStart;
int gaplen = mGapLength;
if (kind == null) {
kind = Object.class;
}
for (int i = 0; i < count; i++) {
int st = starts[i];
int en = ends[i];
if (st > gapstart)
st -= gaplen;
if (en > gapstart)
en -= gaplen;
if (st > start && st < limit && kind.isInstance(spans[i]))
limit = st;
if (en > start && en < limit && kind.isInstance(spans[i]))
limit = en;
}
return limit;
}
Look at the last 2 if-sentences, in your case st=0, start=0, en=2, limit=2. The first if is false, the second if is false too. At the end it returns the unchanged limit parameter.
Im trying to use grid but I need to change direction of inserting children from ( left to right ) to ( right to left ). is there any way to do so , simple example would help me more.
Thanks in advance.
I wrote this. I think solve your problem
/** Returns inverted list by step that take. for example if our list is {1, 2, 3, 4, 5, 6,
* 7 ,8 ,9} and step is 3 inverted list is this: {3, 2, 1, 6, 5, 4, 9, 8, 7}
*/
public static <E> ArrayList<E> invert(List<E> source, int step){
List<E> inverted = new ArrayList<E>();
for(int i = 0; i < source.size(); i++){
if((i + 1) % step == 0){
for(int j = i, count = 0; count < step; j--, count++){
inverted.add(source.get(j));
}
}
}
//
// When (source.size() % step) is not 0 acts.this is for last of list. add last part
// of the source that wasn't add.
//
int remainder = source.size() % step;
if((remainder) != 0 ){
for (int j = source.size() - 1, count = 0; count < (remainder); j--, count++) {
inverted.add(source.get(j));
}
}
return (ArrayList<E>) inverted;
}
i guess the only way is creating a custom gridview, overriding the onLayout() method.
take a look here.
or maybe you can invert items for each row in the list adapter? like for a 3-columns grid, instead of
[1 2 3][4 5 6][7 8] -->
[3 2 1][6 5 4][null 8 7].
(i admit i never used gridview)
i have face same problem but finally solved using reset Array
Here change only u r column no = 3
ArrayList<String> tb_ith_sections_list = new ArrayList<String>;
tb_ith_sections_list = dbhelper.getArrayList();
int sectionCount = tb_ith_sections_list.size();
if(sectionCount > 0){
int rowCount =sectionCount/4;
int colCount ;
if(sectionCount > 4){
colCount=4;
}else{
colCount = sectionCount;
}
if(colCount>sectionCount){
colCount=sectionCount;
}
int k=colCount;
int m=0;
for(int j=0;j<rowCount;j++){
m=(j*colCount);
k=m+colCount;
if(k>sectionCount){
k=(sectionCount-(j*colCount));
}
for(int i=m;i<k;i++){
TB_IVN_SECTIONS tb_Temp=new TB_IVN_SECTIONS();
TB_IVN_SECTIONS tb_ithFirst=tb_ith_sections_list.get(i);
TB_IVN_SECTIONS tb_ithSecond= tb_ith_sections_list.get(k-1);
tb_Temp=tb_ithFirst;
tb_ith_sections_list.set(i, tb_ithSecond);
tb_ith_sections_list.set(k-1,tb_ithFirst);
k--;
}
}