Make randoms be different - android

I have this randoms:
final Random rand2 = new Random();
int number1 = rand2.nextInt(10) + 1;
final Random rand3 = new Random();
int number2 = rand3.nextInt(10) + 1;
final Random rand4 = new Random();
int number3 = rand4.nextInt(10) + 1;
final Random rand5 = new Random();
int number4 = rand5.nextInt(10) + 1;
final Random rand6 = new Random();
int number5 = rand6.nextInt(10) + 1;
final Random rand7 = new Random();
int number6 = rand7.nextInt(10) + 1;
My problem is, im setting text's to:
1.number1+number2
2.number3+number4
3.number5+number6.
What I need is to make sure text1 will be different from text2, and text3 will be different from text1, and text2 will be different from text3, it means:
(number1 + number2) != (number3 + number4)
&& (number3 + number4) != (number5 + number6)
&& (number5 + number6) != (number1 + number2)
How can I do it?

Don't create a new Random object for each new number. Call rand.nextInt() on the first Random object repeatedly instead.
Random rand = new Random();
int number1 = rand.nextInt();
int number2 = rand.nextInt();
...etc
To verify uniqueness, put each generated number in a Hashtable, and use the contains() method to see if it's already been used.

Related

How to compare 2 textview value and loop the code if they are the same in Android Studio

I'm new to programming and trying to write my first app in which show 2 numbers on top and bottom. The number on bottom will keep randomizing every second and you need to click on it when the number match with the number on top.
int min = 1, max = 10;
TextView ques = (TextView) findViewById(R.id.NumQues);
Random r = new Random();
int Rnum = r.nextInt(max - min + 1) + min;
ques.setText("" + Rnum);
final Handler h = new Handler();
final Runnable run = new Runnable() {
int count = 0;
#Override
public void run() {
int min = 1, max = 10;
TextView ans = (TextView) findViewById(R.id.NumAns);
Random r = new Random();
int Rnum = r.nextInt(max - min + 1) + min;
ans.setText("" + Rnum);
h.postDelayed(this, 1000);
}
};
h.postDelayed(run, 1000);
}
This is my layout code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="101dp"
android:layout_alignParentTop="true"
android:id="#+id/NumQues"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="170dp"
android:onClick="Compare"
android:id="#+id/NumAns" />
</RelativeLayout>
The problem that i encountered is i cannot compare the two number. I tried to use
`if (ques.getText().toString().equals(ans.getText().toString()))`
but there are an error "Cannot resolve symbol ans"
Try this:
The problem is you are comparing the value, before you initialize the ans text view.
int min = 1, max = 10;
TextView ques = (TextView) findViewById(R.id.NumQues);
TextView ans = (TextView) findViewById(R.id.NumAns);
//add your comparing if clause after this
Random r = new Random();
int Rnum = r.nextInt(max - min + 1) + min;
ques.setText("" + Rnum);
final Handler h = new Handler();
final Runnable run = new Runnable() {
int count = 0;
#Override
public void run() {
int min = 1, max = 10;
Random r = new Random();
int Rnum = r.nextInt(max - min + 1) + min;
ans.setText("" + Rnum);
h.postDelayed(this, 1000);
}
};
h.postDelayed(run, 1000);
}
Declare your TextView ans after the TextView ques . What you have done is not preferred way of initializing a view .

display multiplication table in TextView

I am trying to generate a multiplication table,where the 1st EditText takes the actual number while 2nd EditText takes the actual range of multiplication table. When I run the project , the result is only number * range..
can anyone help me in the loop or code below mentioned Or,any alternatives to display the table in GridLayout or TableLayout rather than TextView.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_table);
number = (EditText)findViewById(R.id.numberTable);
range = (EditText)findViewById(R.id.numberRange);
click = (Button)findViewById(R.id.click);
result = (TextView)findViewById(R.id.display);
final String x = range.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= 10; i++)
{
for(int j = 1 ; j <= 10; j++)
{
int res = a * b;
result. setText(a +" * " + b + " = " + res);
}
}
return;
}
});
}
}
you are calling setText() for every row, but setText() will reset the text of the TextView, you might want to use append() instead
result.setText("");
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= b; i++){
int res = a * i;
result.append(a +" * " + i + " = " + res + "\n");
}
or maybe use StringBuilder
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
StringBuilder builder = new StringBuilder();
for(int i = 1 ; i <= b; i++){
int res = a * i;
builder.append(a +" * " + i + " = " + res + "\n");
}
result.setText(builder.toString())

How to use any existing variable value in Spinner selection?

want to use the the value of variable b in spinner selection. See the code .
button.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View view) {
String name = editText.getText().toString();
if (yes.isChecked()) {
int age = Integer.parseInt(ageText.getText().toString());
int l;
l = 80 ;
int y ;
y = l - age ;
c = y - 7;
final int z;
b = 2016 + c;
editText3.setText((name + " you might die in the year ")+ b + "");
} else {
if (no.isChecked()) {
int age = Integer.parseInt(ageText.getText().toString());
int c;
int l;
l = 80;
int y;
y = l - age;
c = y + 10;
b = 2016 + c;
editText3.setText(name + (" you might die in year ") + b + "");}}} // this is button code //
now comes the spinner code .
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
final List<String> list = new ArrayList<String>();
list.add("none,i am healthy");
list.add("Diabetes");
list.add("cancer");
list.add("HIV/AIDS");
list.add("Tuberculosis");
list.add("Coronary Artery");
list.add("respiratory disease");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item, list);
String disease = spinner1.getSelectedItem().toString();
spinner1.setAdapter(dataAdapter);
if (disease.equals("Diabetes")) {
int x = b-5;
int j = 2016+ x ;
String name = editText.getText().toString();
editText3.setText(name + (" you might die in year ") + j + ""); }
else if (disease.equals("none,i am healthy")) {
String name = editText.getText().toString();
int x = b + 7 ;
int j = 2016 + x ;
editText3.setText(name + ( "you might die in year ") + j + "");
}
};});
};};
this app is executing without an error yet it is not giving me the desired output . How do i use the value of b in spinner ( i have already defined it global)

Random different numbers android

#Override
public void onClick(View v) {
List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(i);
}
long seed = System.nanoTime();
Collections.shuffle(list, new Random(seed));
int number1 = list.remove(0);
int number2 = list.remove(0);
int number3 = list.remove(0);
int number4 = list.remove(0);
int number5 = list.remove(0);
int number6 = list.remove(0);
math.setText(number1 + "+" + number2);
buttona.setText("" + (number1 + number2));
buttonb.setText("" + (number3 + number4));
buttonc.setText("" + (number5 + number6));
}
I have this code, 6 different numbers between 1 to 10, but my problem is, I need the buttons text will be different, my code doesn't do it, for example:
Number1 = 3 , Number2 = 4, (7) ..
Number3 = 5 , Number4 = 2, (7) ..
How can I make all the texts be different?
You can try to set a random value to the shuffle function. Add a seed at the random and the output will be probably different :).
Try :
long seed = System.nanoTime();
Collections.shuffle(list, new Random(seed));

FSK Demodulation Code (Android)

I am intending to perform FSK demodulation and came across the Androino Project(https://code.google.com/p/androino/source/browse/wiki/AndroinoTerminal.wiki), which reads in data from the Adruino into the phone's audio jack, which is pretty darn cool.
I am trying to go through the code but I can't make sense of some impt values. :((
Why is the bit-high = 22 peaks, bit-low = 6 peaks, private static int HIGH_BIT_N_PEAKS = 12 and private static int LOW_BIT_N_PEAKS = 7?? And why is it 136 samples per encoded bit?
Am I also right to say that the FSK rate of the Adruino is set at 315Hz?
I have attached the hardware(softTerm) codes as well: https://code.google.com/p/androino/source/browse/trunk/arduino/SoftTerm/SoftModem/SoftModem.h and the cpp file is in there as well. Dun have enough reputation points to post both links.
/** Copyright (C) 2011 Androino authors
Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.androino.ttt;
import android.util.Log;
public class FSKModule {
// Experimental results
// Arduino sends "a" character (97) 1100001
// The generated message is 0110.0001
// 136 samples per encoded bit
// total message = 166 bits: 155(high)+1(low)+8bit+stop(high)+end(high)
private static int SAMPLING_FREQUENCY = 44100; //Hz
private static double SAMPLING_TIME = 1.0/SAMPLING_FREQUENCY; //ms
// reading zero+155(high)+1(low)+8bit+stop+end+zero
private static int FREQUENCY_HIGH = 3150;
private static int FREQUENCY_LOW = 1575;
//high: 7 samples/peak
//low : 14 samples/peak
// 1492 samples/message low+8bits+stop+end
// 136 samples/bit (=1492/11)
private static int SAMPLES_PER_BIT = 136;
private static int ENCODING_SAMPLES_PER_BIT = SAMPLES_PER_BIT/2; // 68
// bit-high = 22 peaks
// bit-low = 6 peaks
private static int HIGH_BIT_N_PEAKS = 12;
private static int LOW_BIT_N_PEAKS = 7;
private static int SLOTS_PER_BIT = 4; // 4 parts: determines the size of the part analyzed to count peaks
private static int N_POINTS = SAMPLES_PER_BIT/SLOTS_PER_BIT; // 34=136/4
private static double PEAK_AMPLITUDE_TRESHOLD = 60; // significant sample (not noise)
private static int NUMBER_SAMPLES_PEAK = 4; // minimum number of significant samples to be considered a peak
private static int MINUMUM_NPEAKS = 100; // if lower it means that there is no signal/message
private static final int BIT_HIGH_SYMBOL=2;
private static final int BIT_LOW_SYMBOL=1;
private static final int BIT_NONE_SYMBOL=0;
private static final int CARRIER_MIN_HIGH_BITS=12;
private static final int SOUND_AMPLITUDE = 31000;
private static final String TAG = "FSKModule";
private FSKModule(){
}
private static void debugInfo(String message){
//System.out.println(">>" + message);
Log.w(TAG, "FSKDEC:"+ message);
}
//-----------------------------------------
// DECODING FUNCTIONS
//-----------------------------------------
public static boolean signalAvailable(double[] sound){
FSKModule m = new FSKModule();
int nPoints = N_POINTS;
int nParts = sound.length / nPoints;
int nPeaks = 0;
int startIndex = 0;
int i = 0;
do {
int endIndex = startIndex + nPoints;
int n = m.countPeaks(sound, startIndex, endIndex);
nPeaks += n;
i++;
startIndex = endIndex;
if (nPeaks > MINUMUM_NPEAKS) return true;
} while (i<nParts);
if (nPeaks >3)
debugInfo("signalAvailable() nPeaks=" + nPeaks);
return false;
}
public static int decodeSound(double[] sound){
FSKModule m = new FSKModule();
// processing sound in parts and
//Log.w(TAG, "ENTRO EN processSound");
int[] nPeaks = m.processSound(sound);
if (nPeaks.length == 0) // exit: no signal detected
return -1;
//debugInfo("decodeSound nPeaks=" + nPeaks.length);
// transform number of peaks into bits
//Log.w(TAG, "ENTRO EN parseBits");
int[] bits = m.parseBits(nPeaks);//-------------------------> OK!!
//debugInfo("decodeSound nBits=" + bits.length);
// extract message from the bit array
int message = m.decodeUniqueMessage(bits, sound, nPeaks);
debugInfo("decodeSound(): message="+message + ":" + Integer.toBinaryString(message));
return message;
}
private int decodeUniqueMessageCorrected(int[] nPeaks, int startBit){
int message = 0;
// process nPeaks starting from the end
int index = (startBit+12)*SLOTS_PER_BIT;
// find zero -> non zero transition
for (int i = 0; i < index; i++) {
int i2 = nPeaks[index-i];
int i1 = nPeaks[index-i-1];
debugInfo("zero->nonzero index=" + (index-i) + ": i2=" + i2 + ":i1=" + i1);
if ( (i1-i2)>2) {
index = index-i-1;
break;
}
}
debugInfo("zero->nonzero index=" + index);
int[] bits = new int[2+8+1+2];
for (int i = 0; i < bits.length; i++) {
int peakCounter = 0;
for (int j = 0; j < 4; j++) {
peakCounter += nPeaks[index-j];
}
debugInfo("decode corrected: peakCounter="+i + ":" + peakCounter);
if (peakCounter > 7) { //LOW_BIT_N_PEAKS)
bits[i] = BIT_LOW_SYMBOL;
}
if (peakCounter > 12) { //LOW_BIT_N_PEAKS)
bits[i] = BIT_HIGH_SYMBOL;
message += Math.pow(2, i);
}
debugInfo("bit=" + bits[i] + ":" + message);
index = index -4;
}
debugInfo("decode corrected: message="+message + ":" + Integer.toBinaryString(message));
message = 0;
for (int i = 2; i < 10; i++) {
if ( bits[i] == BIT_HIGH_SYMBOL) {
message+= Math.pow(2, 7-(i-2));
}
}
return message;
}
private int decodeUniqueMessage(int[] bits, double[] sound, int[] nPeaks){
// start bit
int index = findStartBit(bits, 0);
debugInfo("decodeUniqueMessage():start bit=" + index);
if (index == -1) return -1; // no start-bit detected
if (index + 8 + 2 > bits.length)
throw new AndroinoException("Message cutted, start bit at " + index, AndroinoException.TYPE_FSK_DECODING_ERROR);
// debugging information
int number = 16; // n bits to debug
for (int i = index-5; i < index-5+number; i++) {
debugInfo("decodeUniqueMessage(): bits=" + i +":" + bits[i] );
}
for (int i = 0; i < number*SLOTS_PER_BIT; i++) {
int position = i + (index-5)*SLOTS_PER_BIT ;
debugInfo("decodeUniqueMessage(): npeaks=" + position+ ":" + nPeaks[position] );
}
// 8bits message
int value = 0;
for (int i = 0; i < 8; i++) {
int bit = bits[index+i];
if (bit==BIT_HIGH_SYMBOL) value+=Math.pow(2, i);
}
// stop bit: do nothing
// end bit: do nothing
debugInfo("MESSAGE =" + Integer.toBinaryString(value) + ":" + value);
*/
int correctedMessage = decodeUniqueMessageCorrected(nPeaks,index);
debugInfo("MESSAGE corrected=" + Integer.toBinaryString(correctedMessage) + ":" + correctedMessage);
return correctedMessage;
}
private int findStartBit(int[] bits, int startIndex){
// find carrier and start bit
int index = startIndex;
int highCounter = 0;
boolean startBitDetected = false;
do {
int bit = bits[index];
switch (bit) {
case BIT_HIGH_SYMBOL:
highCounter++; // carrier high bit
break;
case BIT_LOW_SYMBOL:
if (highCounter>CARRIER_MIN_HIGH_BITS) { // start-bit detected
startBitDetected = true;
}
else highCounter = 0; // reset carrier counter
break;
case BIT_NONE_SYMBOL:
highCounter = 0;// reset carrier counter
break;
}
index++;
if (index>=bits.length) return -1;
} while (!startBitDetected);
return index;
}
private int[] parseBits(int[] peaks){
// from the number of peaks array decode into an array of bits (2=bit-1, 1=bit-0, 0=no bit)
//
int i =0;
int lowCounter = 0;
int highCounter = 0;
int nBits = peaks.length /SLOTS_PER_BIT;
int[] bits = new int[nBits];
//i = findNextZero(peaks,i); // do not search for silence
i = findNextNonZero(peaks,i);
int nonZeroIndex = i;
if (i+ SLOTS_PER_BIT >= peaks.length) //non-zero not found
return bits;
do {
//int nPeaks = peaks[i]+peaks[i+1]+peaks[i+2]+peaks[i+3];
int nPeaks = 0;
for (int j = 0; j < SLOTS_PER_BIT; j++) {
nPeaks+= peaks[i+j];
}
int position = i/SLOTS_PER_BIT;
bits[position] = BIT_NONE_SYMBOL;
debugInfo("npeaks:i=" + i + ":pos=" + position+ ": nPeaks=" + nPeaks);
if (nPeaks>= LOW_BIT_N_PEAKS) {
//Log.w(TAG, "parseBits NPEAK=" + nPeaks);
bits[position] = BIT_LOW_SYMBOL;
lowCounter++;
}
if (nPeaks>=HIGH_BIT_N_PEAKS ) {
bits[position] = BIT_HIGH_SYMBOL;
highCounter++;
}
//if (nPeaks>5) bits[position] = 1;
//if (nPeaks>12) bits[position] = 2;
i=i+SLOTS_PER_BIT;
} while (SLOTS_PER_BIT+i<peaks.length);
lowCounter = lowCounter - highCounter;
debugInfo("parseBits nonZeroIndex=" + nonZeroIndex);
debugInfo("parseBits lows=" + lowCounter);
debugInfo("parseBits highs=" + highCounter);
return bits;
}
private int findNextNonZero(int[] peaks, int startIndex){
// returns the position of the next value != 0 starting form startIndex
int index = startIndex;
int value = 1;
do {
value = peaks[index];
index++;
} while (value==0 && index<peaks.length-1);
return index-1;
}
private int[] processSound(double[] sound){
// split the sound array into slots of N_POINTS and calculate the number of peaks
int nPoints = N_POINTS;
int nParts = sound.length / nPoints;
int[] nPeaks = new int[nParts];
int startIndex = 0;
int i = 0;
int peakCounter = 0;
do {
int endIndex = startIndex + nPoints;
int n = this.countPeaks(sound, startIndex, endIndex);
nPeaks[i] = n;
peakCounter += n;
i++;
startIndex = endIndex;
} while (i<nParts);
//} while (startIndex+nPoints<sound.length);
debugInfo("processSound() peaksCounter=" + peakCounter);
if (peakCounter < MINUMUM_NPEAKS) {
nPeaks = new int[0];
}
return nPeaks;
}
private int countPeaks(double[] sound, int startIndex, int endIndex){
// count the number of peaks in the selected interval
// peak identification criteria: sign changed and several significant samples (>PEAK_AMPLITUDE_TRESHOLD)
int index = startIndex;
int signChangeCounter = 0;
int numberSamplesGreaterThresdhold = 0;
int sign = 0; // initialized at the first significant value
do {
double value = sound[index];
if (Math.abs(value)>PEAK_AMPLITUDE_TRESHOLD)
numberSamplesGreaterThresdhold++; //significant value
// sign initialization: take the sign of the first significant value
if (sign==0 & numberSamplesGreaterThresdhold>0) sign = (int) (value / Math.abs(value));
boolean signChanged = false;
if (sign <0 & value >0) signChanged = true;
if (sign >0 & value <0) signChanged = true;
if (signChanged & numberSamplesGreaterThresdhold>NUMBER_SAMPLES_PEAK){
signChangeCounter++; // count peak
sign=-1*sign; //change sign
}
index++;
//debugInfo(">>>>>>>index=" + index + " sign=" + sign + " signChangeCounter=" + signChangeCounter + " value=" + value + " numberSamplesGreaterThresdhold=" + numberSamplesGreaterThresdhold);
} while (index<endIndex);
return signChangeCounter;
}
}

Categories

Resources