Writing a method in Java about ArrayList (getting the first match among similar length) - arraylist

I am new to java and I am writing a method that returns the longest song from a playlist(ArrayList) using only the minutes. if multiple songs have the same longest length, it will return the first encountered song. How to ensure it returns the first longest song and not the last longest song.
public Song getLongestSong() {
if (this.songs.isEmpty()) {
return null;
}
Song longestSong = this.songs.get(0);
for (Song songs: this.songs) {
if (songs.getMinutes() >= longestSong.getMinutes()) {
longestSong = songs; `
}
}
return longestSong;
}

This looks like a homework assignment, so I'm not going to give an exact answer https://cs.millersville.edu/~autolab/161-f21/mutunesobject/.
Think about the check in the if (songs.getMinutes() >= longestSong.getMinutes() statement. If there is already a value set for longestSong and another song comes in with the same length, what will happen? How do you avoid that?

Related

Counting how many times specific character appears in string - Kotlin

How one may count how many times specific character appears in string in Kotlin?
From looking at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/ there is nothing built-in and one needs to write loop every time (or may own extension function), but maybe I missed a better way to achieve this?
Easy with filter {} function
val str = "123 123 333"
val countOfSymbol = str
.filter { it == '3' } // 3 is your specific character
.length
println(countOfSymbol) // output 5
Another approach
val countOfSymbol = str.count { it == '3'} // 3 is your specific character
println(countOfSymbol) // output 5
From the point of view of saving computer resources, the count decision(second approach) is more correct.

How to properly iterate over arrays in kotlin

I am currently learning kotlin and therefore following the kotlin track on exercism. The following exercise required me to calculate the Hamming difference between two Strings (so basically just counting the number of differences).
I got to the solution with the following code:
object Hamming {
fun compute(dnaOne: String, dnaTwo: String): Int {
if (dnaOne.length != dnaTwo.length) throw IllegalArgumentException("left and right strands must be of equal length.")
var counter = 0
for ((index, letter) in dnaOne.toCharArray().withIndex()) {
if (letter != dnaTwo.toCharArray()[index]) {
counter++
}
}
return counter
}
}
however, in the beginning I tried to do dnaOne.split("").withIndex() instead of dnaOne.toCharArray().withIndex() which did not work, it would literally stop after the first iteration and the following example
Hamming.compute("GGACGGATTCTG", "AGGACGGATTCT") would return 1 instead of the correct integer 9 (which only gets returned when using toCharArray)
I would appreciate any explanation
I was able to simplify this by using the built-in CharSequence.zip function because StringimplementsCharSequence` in Kotlin.
According to the documentation for zip:
Returns a list of pairs built from the characters of this and the [other] char sequences with the same index
The returned list has length of the shortest char sequence.
Which means we will get a List<Pair<Char,Char>> back (a list of pairs of letters in the same positions). Now that we have this, we can use Iterable.count to determine how many of them are different.
I implemented this as an extension function on String rather than in an object:
fun String.hamming(other: String): Int =
if(this.length != other.length) {
throw IllegalArgumentException("String lengths must match")
} else {
this.zip(other).count { it.first != it.second }
}
This also becomes a single expression now.
And to call this:
val ham = "GGACGGATTCTG".hamming("AGGACGGATTCT")
println("Hamming distance: $ham")

Find a subsequence in a list

Lets assume that we are looking for a sequence in a list and this sequence should satisfy some conditions, for example I have a series of numbers like this:
[1,2,4,6,7,8,12,13,14,15,20]
I need to find the largest sequence so that its consecutive elements have a difference of 1, So what I expected to get is:
[12,13,14,15]
I'm curious if there is any way to get in Kotlin Sequence or inline functions like groupBy or something else.
PS: I know how to create sequences, the question is how to evaluate and extract some sequences with given conditions.
There is no built in functionality for this "sequence" recognition, but you could solve it with the fold operation:
val result = listOf(1, 2, 3, 12, 13, 14, 15)
.distinct() // remove duplicates
.sorted() // by lowest first
.fold(mutableListOf<Int>() to mutableListOf<List<Int>>()) { (currentList, allLists), currentItem ->
if (currentList.isEmpty()) { // Applies only to the very first item
mutableListOf(currentItem) to allLists
} else {
if (currentItem - currentList.max()!! == 1) { // Your custom sequence recognition 'difference of 1'
currentList.apply { add(currentItem) } to allLists
} else {
mutableListOf(currentItem) to allLists.apply { add(currentList) } // Next
}
}
}
.let { it.second.apply { add(it.first) } } // Add last list
.maxBy { it.size } // We need the longest pattern - which will take first of the stack - it could be multiple.
// If you need more precise list, sort them by your criteria

Count number of JSON objects - Objective-C

Example JSON:
{ "image" : "http:\/\/www.domain.com\/blah\/blah\/blah\/5yph0gbfj3ip41a.jpg",
"0" : { "thing1" : "Hello",
"thing2" : "06\/21\/2013"
},
"1" : { "thing1" : "Goodbye",
"thing2" : "06\/28\/2013"
}
}
How can I count the number of times the "0" : {whatever} appears? They'd be increasing by one. Like for the above example, I want it to return 2.
I'm reading JSON from an id : [zoneJSONobject objectForKey:#"thing1"];
One approach would be to use the - [NSDictionary count] method (see docs) for the total number of keys, and then subtract what you don't want to count if it's present (like "image" for example.)
Another approach would be to iterate through the keys like:
int keyCount = 0;
for (NSString *key in myDict)
if (/* the string is a number */ )
keyCount++;
(There are plenty of separate SO articles on testing if a string is a number.)
However, the best approach would be to modify the JSON object to return these dictionaries to you inside an array, that way you don't have to count them before you start iterating. I'm not sure if that option is available to you.
It seems that there's one leading entry for the image, then all the items you want to count. Then you can use the subtraction operator:
int n = dictionary.count - 1;
you want to count the root keys? Use the buit-in NSJSONserialization class to create NSObjects from it. In this case you will get an NSDictionary. Call its allKeys property and then that's count property!

How can I search symbian descriptor for multiple words match

I have a descriptor and I want to search it for multiple words to see if one of these words are exist or not, How can I do this ?
_LIT(KText,"Good Bad Wrong Right False True Now Later What How");
TBuf<100> buf(KText);
Now I want to search "buf" to see it has (Fasle, Now, Bad) words or at least one of them.
This is the code below I use, But I don't feel it is sufficient :
_LIT(KText,"Good;Bad;Now;Later;Why;What");
TBuf<100>buf(KText);
_LIT(KWord,"Good;Now");
TBuf<100>g_Word(KWord);
TPtrC ptr;
TChar delimiter;
delimiter = TChar(';');
for(TInt ii = 0; ii < 100; ii++)
{
if(KErrNone == TextUtils::ColumnText(ptr,ii,&g_Word,delimiter))
{
TBuf<100> temp;temp.Copy(ptr);temp.LowerCase();
if(KErrNotFound != buf.Find(temp))
{
// here I'm gonna do something if there is a match with one or more words in the "buf"
}
}
else
{
break;
}
}
Many thanks in advance.
TDesC has a lot of useful functions.
http://library.forum.nokia.com/index.jsp?topic=/S60_3rd_Edition_Cpp_Developers_Library/GUID-CEE609D8-50E3-422D-8FF9-42C25D669E59_cover.html
_LIT16(KFind1,"bad");
TInt index = str.Find(KFind1); /*Will return index if found else returns KErrNotFound*/