I have dogs list and I need to Add Cat object in 2nd position in between every 6 dogs. What is the efficient way to do this?
fun main(args: Array<String>) {
insertCatBetweenDogs()
}
fun insertCatBetweenDogs() {
val dogs = mutableListOf<String>()
for (i in 1..14) {
dogs.add("Dog$i")
}
val chunkedDogs = dogs.chunked(6)
val dogsWithcat = mutableListOf<String>()
chunkedDogs.map { sixDogs ->
sixDogs.mapIndexed { index, chunkedDog ->
if (index!= 0 && index / 2 == 0) {
dogsWithcat.add("Cat")
}
dogsWithcat.add(chunkedDog)
}
}
dogsWithcat.mapIndexed { i, it ->
println(it)
if ((i+1) % 7 == 0) {
println("______________")
println("")
}
}
}
OutPut:
Dog1 Cat Dog2 Dog3 Dog4 Dog5 Dog6
______________
Dog7 Cat Dog8 Dog9 Dog10 Dog11 Dog12
______________
Dog13 Cat Dog14
This will do it
interface Animal
data class Dog(val name: String) : Animal
data class Cat(val name: String) : Animal
val dogs: List<Animal> = List(20) { Dog(it.toString()) }
val cats: List<Animal> = List(4) { Cat(it.toString()) }
val result = dogs
.chunked(6)
.mapIndexed { index, dogs -> dogs.toMutableList().apply { add(1, cats[index]) } }
.flatten()
This prints
[Dog(name=0), Cat(name=0), Dog(name=1), Dog(name=2), Dog(name=3), Dog(name=4), Dog(name=5), Dog(name=6), Cat(name=1), Dog(name=7), Dog(name=8), Dog(name=9), Dog(name=10), Dog(name=11), Dog(name=12), Cat(name=2), Dog(name=13), Dog(name=14), Dog(name=15), Dog(name=16), Dog(name=17), Dog(name=18), Cat(name=3), Dog(name=19)]
Related
How can I pass a list of objecs from main to a class, as parameter?
I need to pass a list of employees to PayrollSystem class as a parameter.
Could someone help, please?
var index = 0
val employees = mutableListOf(SalaryEmployee(index, "blablabla", 0))
val x: String = "0"
while(true) {
print("Please enter employee name (0 to quit):")
var input = readLine()!!.toString()
if (input != x) {
index++
print("Please enter salary:")
var wage = readLine()!!.toInt()
employees.add(SalaryEmployee(index, input, wage))
}
else {
employees.removeAt(0)
employees.forEach {
SalaryEmployee(it.id, it.name, it.monthly_salary).print()
}
break;
}
}
}
class PayrollSystem(list: MutableList<employee>) {
val temp = list
fun calculatePayroll(){
}
}
class SalaryEmployee(id: Int, name: String, val monthly_salary: Int) : Employee(id, name){
override val id = id
override val name = name
fun print() {
println("Id: $id Name: $name Salary: $monthly_salary")
}
}
open class Employee(open val id: Int, open val name: String) {
}```
Here you are missing val keyword in constructor params.
You can make as var if you are reassigning the list again.
In kotlin constructor, if you don't define it would be a property of the particular class. So its not possible to access outside constructor.
class PayrollSystem(val list: MutableList<Employee>) {
fun calculatePayroll(){
//You can access it with list.someThing()
}
}
Just in case someone will face similar task..
fun main(args: Array<String>) {
var index = 0
val employees = mutableListOf(SalaryEmployee(index, "blablabla", 0))
val x: String = "0"
while(true) {
print("Please enter employee name (0 to quit):")
var input = readLine()!!.toString()
if (input != x) {
index++
print("Please enter salary:")
var wage = readLine()!!.toInt()
employees.add(SalaryEmployee(index, input, wage))
}
else {
employees.removeAt(0)
PayrollSystem(employees).calculatePayroll()
break;
}
}
}
class PayrollSystem(val list: MutableList<SalaryEmployee>) {
val temp = list
fun calculatePayroll(){
temp.forEach{
println("Employee Payroll\n================")
println("Payroll for: ${it.id} - ${it.name}\n- Check amount: ${it.monthly_salary}\n")
}
}
}
class SalaryEmployee(id: Int, name: String, val monthly_salary: Int) : Employee(id, name){
fun calculateSalary(): Int {
return monthly_salary
}
}
open class Employee(open val id: Int, open val name: String) {
}```
I have a method that take a list as a parameter that performs some operation on it and returns the new list. However, in my for..loop I would to keep passing in the updated list until the for..loop has completed.
Is there a way to do this?
fun main(args: Array<String>) {
val listOfSeatRows = (1..127).toList()
// Just loop until all the listOfPass has completed.
listOfPass.forEach { seatPass ->
val seat = Seat.valueOf(seatPass.toString())
// I want to pass in the new updated list not the same list
getListOfSeatRows(listOfSeatRows, seat)
}
}
This method takes the list and return a updated list. However, in the for..loop above I would like to pass in the list that is returned from this method
private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
return when(seatPosition) {
Seat.F, Seat.L -> {
listOfSeat.windowed(listOfSeat.count() / 2).first()
}
Seat.B, Seat.R -> {
listOfSeat.windowed(listOfSeat.count() / 2).last()
}
}
}
enum class Seat(seat: Char) {
F('F'),
B('B'),
L('L'),
R('R')
}
Either you mutate the variable:
fun main(args: Array<String>) {
var listOfSeatRows = (1..127).toList()
// Just loop until all the listOfPass has completed.
listOfPass.forEach { seatPass ->
val seat = Seat.valueOf(seatPass.toString())
// I want to pass in the new updated list not the same list
listOfSeatRows = getListOfSeatRows(listOfSeatRows, seat)
}
}
or you mutate the list:
fun main(args: Array<String>) {
var listOfSeatRows = (1..127).toMutableList()
// Just loop until all the listOfPass has completed.
listOfPass.forEach { seatPass ->
val seat = Seat.valueOf(seatPass.toString())
// I want to pass in the new updated list not the same list
reduceListOfSeatRows(listOfSeatRows, seat)
}
}
private fun reduceListOfSeatRows(listOfSeat: MutableList<Int>, seatPosition: Seat) {
val half = listOfSeat.size / 2
when(seatPosition) {
Seat.F, Seat.L -> {
while (listOfSeat.size > half) listOfSeat.removeLast()
}
Seat.B, Seat.R -> {
while (listOfSeat.size > half) listOfSeat.removeFirst()
}
}
}
If you stick with mutating the property, your function can be simplified (and avoid wasteful creation of multiple intermediate lists) using take/takeLast:
private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
return when(seatPosition) {
Seat.F, Seat.L -> {
listOfSeat.take(listOfSeat.size / 2)
}
Seat.B, Seat.R -> {
listOfSeat.takeLast(listOfSeat.size / 2)
}
}
}
recursion
maybe that's will help with some enhancement depending on your code:
var ss = 1
val listOfPass = listOf<Char>('F', 'L','B','R')
fun main(args: Array<String>) {
val listOfSeatRows = (1..127).toList()
val answer = getListOfSeatRows(
listOfSeatRows,
listOfSeatRows.count() / 2,
Seat.valueOf(listOfPass[0].toString())
)
println(answer)
}
private fun getListOfSeatRows(listOfSeat: List<Int>, count: Int, seatPosition: Seat): List<Int> {
val tempList: List<Int> = when (seatPosition) {
Seat.F, Seat.L -> {
listOfSeat.windowed(count).first()
}
Seat.B, Seat.R -> {
listOfSeat.windowed(count).last()
}
else -> listOfSeat
}
if(count == 0 || count == 1) return listOfSeat
if (listOfPass.size > ss) {
val seat = Seat.valueOf(listOfPass[ss++].toString())
return getListOfSeatRows(tempList, count / 2, seat)
}
return listOfSeat
}
<Team Side="Home" TeamRef="ref123">
<Goal PlayerRef="p1111" Time="10" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p4444" Time="11" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="13" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="17" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
</Team>
public void GetScorer(string side, string OCompetition, string OSeason, string OGameId)
{
try
{
var xDoc = XDocument.Load(test);
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == side
from d in q.Elements("Goal")
select new
{
TeamRef = q.Attribute("TeamRef").Value,
PlayerRef = d.Attribute("PlayerRef").Value,
Time = d.Attribute("Time").Value
};
var count = 0;
foreach (var qq in query)
{
if (side == "Home")
{
if (HomeSlateScorerList[count].PlayerRef != qq.PlayerRef)
{
HomeSlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OSeason, OCompetition, OGameId) });
}
else
{
HomeSlateScorerList[count].Time = HomeSlateScorerList[count].Time + "' ";
}
}
if (side == "Away")
{
AwaySlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OCompetition, OSeason, OGameId) });
}
count++;
}
}
catch (Exception)
{
// ignored
}
}
I would like to edit a player in a list of players
HomeSlateScorerList = new List<Scorer>();
AwaySlateScorerList = new List<Scorer>();
what I would like to achieve is for e.g. there are two players with the ref of "p7777" so in the list of object I would like to have one player with the playerref of "p7777" so if the player exist the format will be
playerref = "p7777"
Time = 13' 17'
or if one player its
Time = 13'
or if another goal is added to the xml its
Time = 13' 17' 25'
HomeSlateScorerList = HomeSlateScorerList
.GroupBy(s => s.PlayerRef)
.Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
.ToList();
Thanks to: #SergeyS SergeyS
Pattern (def.+?}) matches the first Scala method :
object defvaltest {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
val str = "object t extends App { def one = { } def two = { } //Examples one two }"
//> str : String = object t extends App { def one = { } def two = { } //Example
//| s one two }
val Pattern = "(def.+?})".r //> Pattern : scala.util.matching.Regex = (def.+?})
Pattern.findFirstIn(str).get //> res0: String = def one = { }
}
How to match all Scala methods as List[String]
So instead of
res0: String = def one = { }
return
res0: List[String] = List("def one = { }" , "def two = { }")
You are looking for just one match with findFirstIn. To look for multiple matches, you need findAllIn:
val str = "object t extends App { def one = { } def two = { } //Examples one two }"
val Pattern = "(def.+?})".r
val res = Pattern.findAllIn(str)
res.foreach {m =>
println(m)
}
Output of the demo:
def one = { }
def two = { }
Eventually I want to be able to input a string like "\mycard{front1}{back1} \mycard{front2}{back2} \mycard{front3}{back3}" and return the front and back of each card.
I found this website on NSRegularExpression, but I'm having a hard time adjusting it to my problem.
Here is what I have so far.
import Foundation
func rangeFromNSRange(nsRange: NSRange, forString str: String) -> Range<String.Index>? {
let fromUTF16 = str.utf16.startIndex.advancedBy(nsRange.location, limit: str.utf16.endIndex)
let toUTF16 = fromUTF16.advancedBy(nsRange.length, limit: str.utf16.endIndex)
if let from = String.Index(fromUTF16, within: str), let to = String.Index(toUTF16, within: str) {
return from ..< to
}
return nil
}
do {
// let input = "My name is Taylor Swift"
// let regex = try NSRegularExpression(pattern: "My name is (.*)", options: NSRegularExpressionOptions.CaseInsensitive)
let input = "mycard{front}{back}"
let regex = try NSRegularExpression(pattern: "mycard{(.*)}{(.*)}", options: NSRegularExpressionOptions.CaseInsensitive)
let matches = regex.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count))
if let match = matches.first {
let range = match.rangeAtIndex(1)
if let swiftRange = rangeFromNSRange(range, forString: input) {
let name = input.substringWithRange(swiftRange)
}
}
} catch {
// regex was bad!
}
As stated in my comment you need to escape the { and }. That results in the following regex: mycard\\{(.*)\\}\\{(.*)\\}.
You then might want to change your match logic a little bit to output the expected results:
if let match = matches.first {
for i in 1..<match.numberOfRanges {
let range = match.rangeAtIndex(i)
if let swiftRange = rangeFromNSRange(range, forString: input) {
let name = input.substringWithRange(swiftRange)
print(name)
}
}
}
Which outputs
front
back
If you want to match multiple cards use the following regex:
mycard\\{([^{]*)\\}\\{([^{]*)\\}
Then iterate over the matches
for match in matches {
for i in 1..<match.numberOfRanges {
let range = match.rangeAtIndex(i)
if let swiftRange = rangeFromNSRange(range, forString: input) {
let name = input.substringWithRange(swiftRange)
print(name)
}
}
}
For the input mycard{front}{back} mycard{front1}{back1} the output correctly is
front
back
front1
back1
I gave up on regex. I just don't think it will do the trick here. I came up with another solution.
import Foundation
extension String {
subscript (r: Int) -> Character? {
var cur = 0
for char in self.characters {
if cur == r {
return char
}
cur += 1
}
return nil
}
subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
}
func parseBrackets () -> [String]? {
var list: [String] = []
var level = 0
var start = 0
for var i=0; i < self.characters.count - 1; i++ {
if self[i] == "{" {
level += 1
if level == 1 {
start = i + 1
}
} else if self[i] == "}" {
if level == 1 {
list.append(self[start..<i])
}
level -= 1
}
}
if list.count > 0 {
return list
} else {
return nil
}
}
}
let testString = "mycard{f{}ront}{termins{x}{n}} mycard{front1}{back1} mycard{front2}{back2}"
let list = testString.parseBrackets()
for a in list! {
print(a)
}
Which gives the desired output
f{}ront
termins{x}{n}
front1
back1
front2