Scala : Playing with scala list collection

Hi,

In this blog we will learn some operations on Scala Lists  as i am going to write the program for it having  comments which shows the operation we are going to perform on lists

here is the programm :-

object lists extends App {

var list1=List(1,2,5,4,10,9,11,34)

println(“last element of list”)
def last(lst:List[Int]):Int=
{
return lst.last
}
print(last(list1))

println(” \n Find the last but one element of a list”)
print(list1(list1.length-2))

println(“\nFind the nth element of a list”)
def kelement(lst:List[Int],n:Int):Int=
{
return(lst(n))

}
println(kelement(list1,3))

println(“number of elements in list”)
print(list1.length)

print(“\nReverse a list \n”)
def reverse(lst:List[Int]):List[Int]=
{
var newlist=List[Int]()
for(i<-0 to lst.length-1)
{
newlist::=lst(i)

}
return newlist
}
println(reverse(list1))

println(“Eliminate consecutive duplicates of list elements.\n”)
println(“\n list is as follows: List[1,2,4,11,4,4,5,7,1,10]\n”)
val list2=List(1,2,2,2,4,4,4,4,4,4,11,4,4,5,7,1,10)
def eliminatecnsdup(lst:List[Int]):List[Int]=
{
var listn=List[Int]()
for(i<-(0 to lst.length-2))
{
if(lst(i)==lst(i+1))
{

}
else
{
listn::=lst(i)
}
}
if(lst(lst.length-2)==lst(lst.length-1))
{

}
else
{
listn::=lst(lst.length-1)
}

return listn
}
println(eliminatecnsdup(list2))
println((reverse(eliminatecnsdup(list2))))

var s1=”hello how are you”.split(” “)
var s2=”how are you”.split(” “)
var diff=s1.diff(s2)
//print(diff)
// for(i<-0 to diff.length-1)
// {
// print(diff(i) + “\n”)
// }
//
def arraydiff(ar1:Array[String],ar2:Array[String]):Array[String]=
{
var temparr=new Array[String](ar1.length)
var str=” ”
var count=0
for(i<-0 to ar1.length-1)
{
for(j<-0 to ar2.length-1 )
{
if(ar1(i)==ar2(j))
{
count=count+1
}

}
if(count>=1)
{

}
else
{
str=str + ar1(i) + ” ”
}
count=0

}
return str.replace(“Null”,” “).split(” “)
}

var main=(arraydiff(s1,s2))
for(i<-0 to main.length-1)
{
print(main(i) + “\n”)
}

Please share , like and comment

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s