Kotlin. Merge two list with alternating values [duplicate] - arrays

This question already has answers here:
How to combine two different length lists in kotlin?
(6 answers)
Closed 1 year ago.
Is there a ready-made solution for creating an list by alternating elements from two list. I understand how this can be done using loops and conditions, but perhaps there is a ready-made extension that will allow you to solve the problem concisely

You can use zip and flatMap result.
val list1 = listOf(1, 2, 3)
val list2 = listOf(4, 5, 6)
val result = list1.zip(list2).flatMap { pair -> listOf(pair.first, pair.second) }
note that this solution executes extra memory allocation for each pair so my recommendation is still to implement your own version.
fun <T> List<T>.mix(other: List<T>): List<T> {
val first = iterator()
val second = other.iterator()
val list = ArrayList<T>(minOf(this.size, other.size))
while (first.hasNext() && second.hasNext()) {
list.add(first.next())
list.add(second.next())
}
return list
}

Related

How to know how many time each element appears in an array? [duplicate]

This question already has answers here:
How to count occurrences of an element in a Swift array?
(16 answers)
Closed 2 years ago.
So far I have this:
func myFunc(arr: [Int]) {
var arr2 = arr
var count = 1
for i in 0..<arr.count {
for j in i + 1..<arr2.count {
if arr2[i] == arr2[j] {
count += 1
arr2.remove(at: j)
}
}
print("\(arr2[i])-\(count)")
count = 1
}
}
myFunc(arr: [5,6,5])
I want it to print (5 - 2)
(6 - 1)
I am getting a fatal error every time I want to remove the repeated element, can you explain why and how to solve this problem?
I will solve this problem by creating hash table or dictionary with keys of type the same as array elements and integers as values. This structure will store values from array. Walking through array you can:
Add element to dictionary is if it not already exists with value as "key" and 1 as "value".
If element already exists - increment "value" by one of element "Key| == element.
After walking whole array you will have dictionary with unique elements as dictionary keys and number of repetitions as values

When printing an array in Kotlin, instead of printing the integer, it prints a slew of other characters [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
package MiscellaneousProjects
import java.util.*
class Numbers(val numbers: Int){
}
fun ClosedRange<Int>.random() = Random().nextInt((endInclusive + 1) - start) + start // Function to randomly generate a number
fun main(args: Array<String>) {
var list = arrayListOf<Numbers>()
for(i in 1..10){
val random = Random()
list.add(Numbers((0..100).random())) // Adds the numbers to an array
}
var sortedList = list.sortedWith(compareBy({ it.numbers })) // Sorts the elements from least to greatest
for(element in sortedList){
println(element.numbers) // Prints the individual entries
}
println(sortedList)
}
The following piece of code picks a number from 0 to 100 and adds it to an array.
I am sorting the numbers from greatest to least using sortedWith and compareBy functions. However, when I print "sortedList," the following types of entries are seen: "MiscellaneousProjects.Numbers#30f39991, MiscellaneousProjects.Numbers#452b3a41."
However, whenever I print the individual elements in the array, it outputs the correct numbers.
Can someone tell me the error in my code?
Either use a data class for Numbers (which basically has a built-in toString() that will probably suffice your needs already) or just override toString() yourself in the Numbers class to return the numbers, e.g.
override fun toString() = numbers.toString()
The issue is that you're relying on the default implementation of toString for your Numbers class, which is inherited from Object and prints what you see (i.e., <class_name>#<hash_code>, as you can find here).
To print something more meaningful you can override the toString method (or fun in Kotlin) to return the String you're expecting

Creating A Substring | Swift 4 [duplicate]

This question already has answers here:
How does String substring work in Swift
(25 answers)
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
(33 answers)
Closed 4 years ago.
How do I substring a string in swift 4.
I would like to convert:
"Hello, World!"
Into:
"Hello"
Swift has no built in function to make this easy so I wrote a simple extension to get the same functionality as other languages such as python which have really easy substring functions.
Extension
Outside your class, add this extension for strings.
extension String {
func substring(start: Int, range: Int) -> String {
let characterArray = Array(self)
var tempArray:[Character] = []
let starting = start
let ending = start + range
for i in (starting...ending) {
tempArray.append(characterArray[i])
}
let finalString = String(tempArray)
return finalString
}
}
Usage
let myString = "Hello, World!"
print(myString.substring(start: 0, range: 4))
This prints:
"Hello"
How It Works
The extension works by turning the string into an array of separate characters then creates a loop which appends the desired characters into a new string which is determined by the function's parameters.
Thanks for stopping by. I hope apple add this basic functionality to their language soon! The above code is a bit messy so if anyone wants to clean it up then feel free!

Swift array for first object in array [duplicate]

This question already has answers here:
How to find index of list item in Swift?
(23 answers)
Closed 6 years ago.
I have this code in my Roman Numeral conversion algorithm...
for (a, r) in arabicToRomanArray where substring.hasPrefix(r) {
arabic += a
let index = substring.index(substring.startIndex, offsetBy: r.characters.count)
substring = substring.substring(from: index)
break
}
I was wondering if there is an easier way of doing this.
At the moment I am doing a conditional for loop and then breaking on the first entry. Is there a way to do a for first type block with the condition?
The only way I can think of doing it is to filter the array and then get the first object from the filtered array and use that. Seems clunkier than what I'm doing at the moment though.
Edit
After trying out the edit it also makes the algorithm much slower, which makes sense.
The for/break loop will have a best time of O(1) and worst time of O(n).
The filter and first method will have a best time of O(n).
Thanks to #MartinR's comment I found a much better way of doing the same thing.
It's equivalent in time to the for/break loop but less clunky.
The code I had previously...
for (a, r) in arabicToRomanArray where substring.hasPrefix(r) {
arabic += a
let index = substring.index(substring.startIndex, offsetBy: r.characters.count)
substring = substring.substring(from: index)
break
}
Is now...
let (a, r) = arabicToRomanArray[arabicToRomanArray.index(where:{string.hasPrefix($0.1)})!]
arabic += a
let index = substring(substring.startIndex, offsetBy: numCharacters)
substring = substring.substring(from: index)
Using the array function...
array.index(where: (Element) -> Bool)
like...
arabicToRomanArray.index(where:{string.hasPrefix($0.1)})
I also refactored out some of the code into functions once I'd done this so it's actually now...
let (a, r) = findPrefixedArabicToRoman(string: substring)
arabic += a
substring = remove(numCharacters: r.characters.count, fromString: substring)

Access element of MATLAB multi-dimensional array specified by another vector [duplicate]

This question already has answers here:
Use a vector as an index to a matrix
(3 answers)
Closed 7 years ago.
I have a MATLAB function which returns a 4-element vector, e.g. [1 2 3 4]. I would like to use that function output to access the corresponding element in an existing 4-dimensional vector, i.e. vec(1, 2, 3, 4). Is there a way to do this without storing the result and then explicitly accessing the elements, as in the following?
result = f(blah);
myElement = vec(result(1), result(2), result(3), result(4));
In my (Python-influenced) head, the answer looks something like this:
result = f(blah);
myElement = vec(*result); % or vec(toSubscripts(result)); or similar
The * operator in Python expands a list into comma-separated arguments. Is there an analogous operator or function in MATLAB that will help solve my problem?
There is something like *result in matlab, it's called comma separated list. Unfortunately you can not create a comma separated list from a array, thus conversion to a cell is first required:
result=(num2cell(f(blah)));
myElement=v(result{:});

Resources