How to generate random numbers so that every number only occurs once? - android

I want to generate random numbers when clicking a button and every random number only occurs once. Now, I have an array in which I store all the generated numbers so I can check whether or not this number has been previously generated. However, when this is the case I want it to generate another number which has not been previously generated. I have been struggling but can't find the right code for this.
var arraylist = ArrayList<Int>()
nextnumberbutton.setOnClickListener {
val rand = java.util.Random().nextInt(75)
if (arraylist.contains(rand)) {
kotlin.run { nextnumberbutton }
} else {
numbertextview.text = rand.toString()
}
arraylist.add(rand)
}

run { nextnumberbutton } doesn't do anything. It's a lambda that will simply return Unit.
Supposing you did call the click listener again when a repeated number is found, you would still be adding the number to the list again, since you don't return from the function early. So you would end up with duplicates in your list.
Your strategy could be done with a while loop instead of calling the whole function again when a duplicate is picked. e.g. you could use while (rand !in arrayList) rand = Random.nextInt(75). However, this has the potential to take longer and longer to pick the number as you approach the limit of values because it is simply guessing numbers and has to try again if the number is already picked.
A better strategy would be to start with a set of all the numbers and remove from this set as you go. You also need to handle the case of when all numbers are picked, perhaps by showing a message to the user.
val unpickedNumbers = (0..75).toMutableSet()
nextnumberbutton.setOnClickListener {
if (unpickedNumbers.isEmpty()) {
Toast.makeText(context, "All numbers already picked", Toast.LENGTH_LONG).show()
return
}
val rand = unpickedNumbers.random()
numbertextview.text = rand.toString()
unpickedNumbers.remove(rand)
}

Related

LiveMutableData and copies update to same value?

I have a MutableLiveData variable in my AppRepository which is updated and contains my data. This I have no issues with. I also have the following observable to trigger a UI update with the data it holds in my onCreateView function:
viewModel.projectWithContent.observe(viewLifecycleOwner, {
pwc = it
counterList = it.counterList
})
When I tap either to increase or decrease the counter count and then try to push the update to my Room database, it skips it. I have the following check currently:
if(counterList != null) {
try {
for(counter: Counter in counterList!!) {
if(counter.counter_count != pwc?.counterList!![
pwc?.counterList!!.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
It'll always go to Goodbye.
Now. If I put the following just below try
Log.i(LOG_TAG, "PWC: ${pwc?.counterList!![0].counter_count}, " +
"CPWC: ${counterList!![0].counter_count}," +
"VMPWC: ${viewModel.projectWithContent.value?.counterList!![0].counter_count}")
It provides the following output:
PWC: 70, CPWC: 70,VMPWC: 70
Is this a side effect of what I'm doing or?
Thanks
Like #Tenfour04 says, your condition is actually checking they don't match, so "Goodbye" is the output when they do match.
If you don't mind (this is a little long), I just want to recommend some stuff because I feel like you're making life hard for yourself with all the null-checking that's going on - the logic of the code was really hard to read, and I'm guessing that's why you didn't notice the flipped logic too!
First: the ? null safety stuff (and !! which is the opposite of safe, never use it unless you know you have good reason) is there because you have nullable variable types. Normally the IDE would smart cast them to non-null once you've done a null check (like on your first line) - but because they're vars, they can be changed at any time.
That means that a variable that wasn't null before could be now, so you're forced to null-check every single time you access it. But even if the types weren't nullable, because they're vars, they can still change, and the thing you were looking at a moment ago is something different now.
The simple solution is to just make a new variable:
val counters = counterList
if (counters != null) {
...
}
// or if you want to use one of kotlin's scope functions
counterList?.let { counters ->
...
}
Because that new one is a val, it's not going to change what it's pointing at! Once it's null-checked, it's always going to be non-null, so you don't need to use ? anymore.
You have a couple of variables to make - you want to make sure pwc isn't null, and also their counterLists. A quick way to do that is with pwc?.counterList - if pwc is null, it will return null. Otherwise it will move to the next step, and return counterList, which may be null. (Using !! is saying that it definitely never will be null, in which case it shouldn't be nullable at all!)
And you don't actually care about pwc anyway - you're just comparing its counterList to the other, so why don't we pare it back to just those?
val counters = counterList
val pwcCounters = pwc?.counterList
if (counters != null && pwcCounters != null) {
try {
for(counter: Counter in counters) {
if(counter.counter_count != pwcCounters[
pwcCounters.indexOf(counter)
].counter_count) {
Log.i(LOG_TAG, "Hello")
} else {
Log.i(LOG_TAG, "Goodbye")
}
}
} catch(e: IndexOutOfBoundsException) {
e.printStackTrace()
}
}
There's more we could do here, but just by cleaning up those nulls and using the specific variables we want to work with, does that feel easier to read? And more importantly, easier to understand what's happening and what could happen?
Might be worth throwing it in a function too, stops the call site getting cluttered with these temp variables:
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// do the stuff
}
// when you want to do the thing:
doThing(counterList, pwc?.counterList)
So all your null checking is out of the way, your "temp variables" are the fixed parameters passed to the function, it's all nice and neat.
I know this is a long post for such a short bit of code, but it's a good habit to get into - if you're writing code where you're working with nullable vars and you're wrestling with the null safety system, or you keep repeating yourself to access a particular variable nested inside another object, you can make things a lot easier for yourself! You can imagine how wild this could all get for more complex code.
Also if you care, this is how I'd personally write it, if it helps!
fun doThing(counters: List<Counter>?, pwcCounters: List<Counter>?) {
if (counters == null || pwcCounters == null) return
// for (counter in Counters) is fine too I just like this version
counters.forEach { counter ->
// find returns the first item that matches the condition, or null if nothing matches,
// so no need to handle any exceptions, just handle the potential null!
// (this is a really common Kotlin pattern, lots of functions have a "returns null on failure" version)
val pwcCounter = pwcCounters.find { it == counter }
// remember pwcCounter can be null, so we have to use ? to access its count safely.
// If it evaluates to null, the match just fails
if (counter.count == pwcCounter?.count) Log.i(LOG_TAG, "Hello")
else Log.i(LOG_TAG, "Goodbye")
}
}
I also renamed counter_count to just count since it's a property on a Counter anyway. I feel like counter.count is easier to read than counter.counter_count, y'know? It's the little things

get last arraylist position before streak gets interrupted

https://www.google.com/search?q=message+image+on+last&sxsrf=ALeKk01qNrLQ61yRXCMSPRxyNaoI0MF_kA:1605295893515&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjj2veboYDtAhWeIbcAHebnB4QQ_AUoAXoECAwQAw&biw=1366&bih=657#imgrc=wzgnznL_g7kUsM
I want to show profile image like shown in above link only at last message of every consecutive messages from same person. Please help me with this.
I have tried many ways but I don't know to hide visibility of top images
if (position > 0) {
if (messageList.get(i).getFrom.equalsIgnoreCase(messagesList.get(position - 1).getFrom()))
{
viewHolder.mProfileImage.setVisibility(View.INVISIBLE);
}
else
{
viewHolder.mProfileImage.setVisibility(View.VISIBLE);
}
}
else
{
viewHolder.mProfileImage.setVisibility(View.VISIBLE);
}
I have used above code and get this result which is shown in this http://i.stack.imgur.com/92SUb.jpg link. With this code I am able to hide all the images other than the first one image. can you please show me the way to hide top message image and not the last one of streak.
I have to assume few things in my answer.
i.e.
messageList is the list of all messages. not the list of only consecutive/streak messages.
you need to show profile images for both sender and receiver.
And you want to only show the profileImage of last consecutive message.
So, here what you should do.
int length = messageList.lenght; //getTotalLenght;
String fromCurrent = messageList[position].getFrom(); //getFrom of current message being painted or shown
String fromNext = fromCurrent; //next message is set to current by default, to avoid error
if(length > postition+1) {
fromNext = messageList[position+1].getFrom(); //if there is next message then get its sender but if it is the last message then nextSender and currentSender are same as I set its default value to the currentSender.
}
console.log("TAG", "FromNext: " + fromNext);
console.log("TAG", "FromCurrent: " + fromCurrent);
if(!fromCurrent.equals(fromNext)) { //checking if last message or not
viewHolder.mProfileImage.setVisibility(View.VISIBLE);
}
else {
viewHolder.mProfileImage.setVisibility(View.INVISIBLE);
}

How to make case REMOVED fire when the last element is removed from Firestore?

I'm trying to listen for real-time updates and I'm using the following code in onEvent:
override fun onEvent(querySnapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
if (e != null) return
if (!querySnapshot!!.isEmpty) {
for (change in querySnapshot.documentChanges) {
value = when (documentChange.type) {
Type.ADDED -> change.document.toObject<Item>(Item::class.java)
Type.MODIFIED -> change.document.toObject<Item>(Item::class.java)
Type.REMOVED -> vchange.document.toObject<Item>(Item::class.java)
}
}
} else {
logErrorMessage("querySnapshot.isEmpty")
}
}
Let's assume we have 2 elements added in a collection. For each addition, case Type.ADDED is triggered. If I remove one of them, Type.REMOVED is triggered. The problem comes, when I try to remove the last item. Instead of having case Type.REMOVED triggered for the last time, I get an empty querySnapshot. So the Type.REMOVED case is not triggered anymore. How can I be notified when the last element is removed?
The problem could be that your code is only looking for document changes if the query results are not empty. If the results become empty, you're just not checking to see if there was a change that made it empty. Remove the check for !querySnapshot!!.isEmpty and just list each change regardless.
If your querySnapshot is empty then you won't satisfy the if condition, therefore, you won't enter any of the cases on your when statement.
Also, since your snapshot is empty, there is no data to map to your Item.class

kotlin: How to get if EditText has setError enabled?

How can I validate if EditText has setError enabled ?
I want to disable a button if EditText has an error.
Any other way to achieve this.
It kinda works when I put view.calcbutton.setEnabled(false) inside the validateEditText-function, but I use the validateEditText-function to validate multiple EditTexts and only the last function-call disables the button.
if the first function-call disables the button, the second enables it again, and vice versa.
But I want do it outside this function because if one of the multiple EditTexts has setError the button should be disabled.
//global var blockcalcbutton
var blockcalcbutton = 0
//function to validate EditTexts and set blockcalcbutton=1 if setError
validateEditText(view.input_volt, view, getString(R.string.invalid_volt))
if(blockcalcbutton == 1) {
view.calcbutton.setEnabled(false)
view.calcbutton.setText(getString(R.string.calcbutton_disabled))
view.calcbutton.setBackgroundResource(R.color.buttonDisabled)
} else {
view.calcbutton.setEnabled(true)
view.calcbutton.setText(getString(R.string.calcbutton_enabled))
view.calcbutton.setBackgroundResource(R.color.buttonBackground)
}
fun validateEditText(editText: EditText, message: String) {
val myEditText = editText
myEditText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
if(myEditText.text.toString() == "" || myEditText.text.toString() == "." || myEditText.text.toString() == "0") {
//setError
myEditText.setError(message)
//var to disable Button
blockcalcbutton = 1
} else {
//delete setError
myEditText.setError(null)
//var to enable Button
blockcalcbutton = 0
}
}
You can create a callback to notify when you set an error or delete it.
interface EditTextErrorListener {
fun onErrorSet()
fun onErrorDeleted()
}
Here you can notify:
if(myEditText.text.toString() == "" || myEditText.text.toString() == "." || myEditText.text.toString() == "0") {
//setError
myEditText.setError(message)
---> listener.onErrorSet()
//var to disable Button
blockcalcbutton = 1
} else {
//delete setError
myEditText.setError(null)
---> listener.onErrorDeleted()
//var to enable Button
blockcalcbutton = 0
}
Try approaching the problem from further away; when you look at this issue, you have multiple inputs (all the fields in your form) and one boolean output:
All fields are OK -> Enable the button
One or more fields are NOT Ok -> disable the button.
Additionally, you have local validation on each field (to display the error, etc.).
I'd argue that the local validation on each field, is to be done at the callback from the edit text (onAfterText, etc.etc.). You are already doing this.
A way to ensure the final validation (of the form as a whole) is fast, you could use a reference counter. E.g.:
Each edit text, validates with afterTextChanged. Each one performs whatever validation you think is right (can be a shared one if they are all the same).
If validation fails, you keep a reference to the failed field.
This will not have side-effects because nothing happens whether the item is or is not on the list.
This is some pseudo-code:
// keep a list of fields (this is just a way to do it, there are many others)
var errorFields = MutableHashSet<EditText>
later in your "validation" (afterTextChanges for example):
if (xxx && yyy && zzz) { //your validations for the individual editText
//setError
myEditText.setError(message)
// Store the reference of the editField in error.
errorFields.add(theEditTextThatHasAFailure).
} else {
myEditText.setError(null)
// If the validation is ok, you remove it:
errorFields.remove(theEditTextThatHasFailure)
}
// The form may have changed, update the global button state.
updateButtonState();
All this method needs to do, is something like:
button.enabled = errorFields.isEmpty()
This will only be empty if there are no error fields.
This is just an idea you may need to combine with callbacks for further control, but remember this one thing:
EditTexts (or any other widget) is and should not be responsible for the business logic that drives the whole "Form"; they are merely individual pieces of a larger puzzle, and as such, it's incorrect to give them the responsibility to drive your Form's validations; they can (and should) however, validate themselves and handle their own error state (like you're doing), but that's as far as it should go.
They can inform of a state change (e.g. via the listener onAfterText, or after gaining/losing focus, etc.) but shouldn't make business logic decisions. EditTexts are designed to take user input and display it on screen, that's all.
Last but not least, don't forget to remove the references when you destroy your views
onDestroy() {
errorFields.clear()
}

Get an event triggered when text change unity?

Here the Text Area is constantly changing in terms of number and I want to trigger an event when the Text Area gets a particular number example I have tried this -
public void myfunction45(Canvas Panel)
{
if (Indicator = 45) {
Panel.enabled = false;.
}
} //(indicator- www.progress).
But it does not work(it does not read it nothing happens). how do I match the condition as the number is to be specific. please give an example for explanation. Thanks in advance.
That if statement would cause you problems.
You would want:
if(Indicator == 5)
instead. At the moment you're assigning the value without checking it, this would cause a compiler error. If it's just a typo, then update your answer, slightly confusing otherwise.
With regards to checking the text value. You'd have to grab the text value, for that you need a reference to the Text area. This approach assumes that the text area has it's value set by a user. Currently you're not grabbing any text values to compare, as a result, the if statement won't know what to compare.
Here's one approach:
public void myfunction5(Canvas Panel)
{
float result;
string textValue = yourTextArea.text;
if(Single.TryParse(textValue, out result))
{
if(result == Indicator)
{
Panel.enabled = false;
}
}
}
You use TryParse to avoid any potential exceptions that would be thrown if the user entered something that wasn't a number. This method will take the value from your text area, how you get your text area is up to you, and try to parse the text value into a float. The method will return true if the parse was a success, false otherwise.
Here's the reference for the TryParse stuff:
https://msdn.microsoft.com/en-us/library/26sxas5t(v=vs.110).aspx
If you wanted to parse it to an int, then you'd be using the Int32's version of TryParse, https://msdn.microsoft.com/en-us/library/system.int32_methods(v=vs.110).aspx
I'd also recommend having a peak at the Input Field documentation: https://docs.unity3d.com/Manual/script-InputField.html
You can subscribe your method to the Input-fields On Value Changed event, your function will need to tweaked slightly though:
public void myfunction5(string text)
{
float result;
if(Single.TryParse(text, out result))
{
if(result == Indicator)
{
CachedPanel.enabled = false;
}
}
}
Don't forget to store a reference to the panel you want to disable.
Hopefully this is what you're after.
Panel is already a Canvas type, it doesn't make any sense to GetComponent<Canvas> on the same type.
Try using Panel.enabled = false;.
For the rest, we don't know how you get the Indicator reference, or how you built the UI hierarchy, so we can't assess if the problem is there.
Edit: I could I miss the single = baffles me lol. I should avoid answering questions when I'm tired.

Categories

Resources