How to check array integer value in kotlin? [closed] - kotlin

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i want to make check value function like below code.
enabled is true only if the integer array contains 5 or 16, otherwise enabled is false.
Anyone can help?

Use the default IntArray.any(predicate: (Int) -> Boolean) : Boolean function to check it. Example:
#Test
fun intArray_containsElement() {
val arrayTest = intArrayOf(1, 10, 50, 5, 6, 4, 3)
val isEnable = arrayTest.any { it == 5 || it == 16 }
assertEquals(true, isEnable) // Successfully
}

edit: As Duc Thang pointed out, using any is better because it only iterates the array once:
val IntArray.enabled: Boolean get() = any { it == 5 || it == 16 }
Previous less efficient version:
val IntArray.enabled: Boolean get() = contains(5) || contains(16)
Test:
fun main() {
println(intArrayOf(0).enabled)
println(intArrayOf(0, 5).enabled)
println(intArrayOf(1, 16).enabled)
println(intArrayOf(5, 16).enabled)
println(intArrayOf(19, 1000, 4).enabled)
}
Output:
false
true
true
true
false

Related

In the rust test, I don't care about the sequence of vec![]. What should i do? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
enter image description here
Is there any disorderd arrays Or Do not judge the order when asserting?
What I do is sort both sides in the assert call itself. This only works if T implements Ord.
let result = my_function();
my_function.sort();
let target = vec![];
target.sort();
assert_eq!(result, target);
If your datatype does not support Ord, you can use sort_by with a FnMut that returns an instance of Ordering.
Note that this can have issues when there isn't one specific way a vector can be sorted.
Convert the Vec(s) to HashBag(s) that contains references to the items in the Vecs. That will disregard the order of items when asserting for equality:
[dependencies]
hashbag = "0.1.9"
#[test]
fn two_vecs_equal_independent_of_item_order() {
use hashbag::HashBag;
let actual = vec![1, 2, 3, 3];
let expected_fail = vec![3, 2, 1];
assert_ne!(
actual.iter().collect::<HashBag<&i32>>(),
expected_fail.iter().collect::<HashBag<&i32>>()
);
let expected_pass = vec![3, 2, 1, 3];
assert_eq!(
actual.iter().collect::<HashBag<&i32>>(),
expected_pass.iter().collect::<HashBag<&i32>>()
);
}

Kotlin - how to use sort function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
Hallo Ladys and Gentleman,
i strugle with a function.
I want convert a given String to a MutableMap.
String:
var testString = "hshhfzrt" + "hszrhhtnt"
function to use:
charMap.toList().sortedByDescending { (_, value) ->
value }.toMap()
Final Output should be a Sorted Char in a new String.
Output example(Not related to testString is just example):
hhh, lll, aaa,
I hope you can help me.
Thx for reading this and your time.
val testString = "hshhfzrt" + "hszrhhtnt"
val result = testString
.toList()
.sorted()
.groupBy { it }
.map { it.value.joinToString("") }
.joinToString(", ")
println(result) // Output: "f, hhhhhh, n, rr, ss, ttt, zz"

Kotlin compare two lists - if ids match overwrite it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have two lists of Object. Both objects have an id val. I need to check both lists by the id val, if the id is the same take the object from list B and overwrite it in list A. Is there a simple up to date way to achieve this outcome in kotlin?
Ive been searching through the kotlin docs and other comparing list questions on here but I havent found anything in the docs or on here that matches my usecase
Not sure about how efficient this is but it works...
Sample Class
data class SomeClass(val id: Int, val someString: String) {
}
fun transformList(firstList: List<SomeClass>, secondList: List<SomeClass>): List<SomeClass> {
return firstList.map { firstClass ->
val tempItem = secondList.firstOrNull { it.id == firstClass.id }
tempItem ?: firstClass
}
}
basically, the function takes both the lists and compares each item with each other, and returns items from list 2 if the id is the same.
fun main() {
val listOne = listOf<SomeClass>(
SomeClass(0, "I am 0, from list 1"),
SomeClass(1, "I am 1, from list 1"),
)
val listTwo = listOf<SomeClass>(
SomeClass(0, "I am 0, from list 2"),
SomeClass(1, "I am 1, from list 2"),
)
println(transformList(listOne, listTwo))
}
Output
[SomeClass(id=0, someString=I am 0, from list 2), SomeClass(id=1, someString=I am 1, from list 2)]

How do I pull entries from an ArrayList at random in Kotlin?

This is my first Kotlin project. I am learning as I go and I have reached a roadblock.
I have an ArrayList of questions that I want to pull into that app in a random order. I've tried assigning the .random to the point where the question is assigned (right now it is set to CurrentPosition-1) but that only randomized the question and didn't pull the correct answers along with the questions.
How do I either bundle the answers to the question or is there a better way to get the questions to shuffle in order? I plan on having 50+ questions but only 10 will show each time the test is taken. I don't want the same 10 questions showing each time the user opens the test.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz_questions)
mQuestionsList=Constants.getQuestions()
setQuestion()
}
private fun setQuestion(){
val question = mQuestionsList!![mCurrentPosition-1]
defaultOptionsView()
if(mCurrentPosition == mQuestionsList!!.size){
submitBtn.text = "Finish"
}else{
submitBtn.text = "Submit"
}
progressBar.progress = mCurrentPosition
tv_progress.text = "$mCurrentPosition" + "/" + progressBar.max
tv_question.text = question!!.question
test_image.setImageResource(question.image)
tvOptionOne.text = question.optionOne
tvOptionTwo.text = question.optionTwo
tvOptionThree.text = question.optionThree
tvOptionFour.text = question.optionFour
}
private fun defaultOptionsView(){
val options = ArrayList<TextView>()
options.add(0, tvOptionOne)
options.add(1, tvOptionTwo)
options.add(2, tvOptionThree)
options.add(3, tvOptionFour)
Here is my Array
object Constants{
const val TOTAL_QUESTIONS: String = "total_questions"
const val CORRECT_ANSWERS: String = "correct_answers"
fun getQuestions(): ArrayList<Question>{
val questionsList = ArrayList<Question>()
val q1 = Question(
R.drawable.questionmark,
1,
"Who is Regional Manager of\n Dunder Mifflin Scranton?",
"Michael",
"Jim",
"Pam",
"Dwight",
1,
)
I appreciate any help at all. Thank you in advance.
list.shuffled().take(10) And make your mQuestionsList property type List instead of ArrayList since you don’t need to modify it after retrieval. You should also probably make it lateinit or initialize it at its declaration site so you won’t have to make the type nullable and have to resort to !!, which is generally a code smell. So I would declare it as var mQuestionsList: List<Question> = emptyList() and whenever you want new values do mQuestionsList = Constants.getQuestions().shuffled().take(10).

Clarification on ending a while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am currently working with a while loop and was confused as to why I couldn't end the loop.
I played around with it for a little while and for some reason the following code works and ends the while loop:
boolean keepGoing = true;
while (keepGoing != false)
{
//execute code
}
System.out.println("Would you like to continue? Enter Y for yes or N for no.");
String keepGoingYesOrNo = input.nextLine();
if (keepGoingYesOrNo.equals("Y"))
{
keepGoing = true;
matchCount=0;
guessCount=0;
}
else
{
System.out.println("Goodbye!");
keepGoing = false;
But the alternative doesn't end the while loop:
boolean keepGoing = true;
while (keepGoing = true)
{
//execute code
}
System.out.println("Would you like to continue? Enter Y for yes or N for no.");
String keepGoingYesOrNo = input.nextLine();
if (keepGoingYesOrNo.equals("Y"))
{
keepGoing = true;
matchCount=0;
guessCount=0;
}
else
{
System.out.println("Goodbye!");
keepGoing = false;
Shouldn't while (keepGoing = true) and while (keepGoing != false) be the same thing. I got the code to work but I was hoping to get some clarification on why one works and the other doesn't.
One thing to look out for is that (keepGoing = true) and (keepGoing == true) are not the same. If you want to check if keepGoing is true, you should use ==. When you use the single =, you're assigning true to keepGoing, so every time you're trying to check if it's true, you're actually setting it to true.
Also, because while loops are already checking if the condition is true, you could simplify your while statement to just while (keepGoing) {}.