Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays I';正在获取数组地址(输出:[I@59494225)在scala中——在下面的代码中,我希望输出为(2,1)_Arrays_Scala - Fatal编程技术网

Arrays I';正在获取数组地址(输出:[I@59494225)在scala中——在下面的代码中,我希望输出为(2,1)

Arrays I';正在获取数组地址(输出:[I@59494225)在scala中——在下面的代码中,我希望输出为(2,1),arrays,scala,Arrays,Scala,这里的要求是比较数组元素a(i)和b(i),并更新 如果a[i]>b[i],则a得1分如果b[i]>a[i],则b 得1分 对象MyWizard扩展应用程序{ def compareTriplets(a:Array[Int],b:Array[Int]):Array[Int]={ var aCount=0 var bCount=0 对于(i使用toString()方法,因为它被解释为它的数据地址,而不是数据的字符串格式。 这是一个简单的Geeksforgeks示例:这是一个更高效、更惯用、更通用、

这里的要求是比较数组元素a(i)和b(i),并更新

如果a[i]>b[i],则a得1分
如果b[i]>a[i],则b 得1分

对象MyWizard扩展应用程序{
def compareTriplets(a:Array[Int],b:Array[Int]):Array[Int]={
var aCount=0
var bCount=0
对于(i使用toString()方法,因为它被解释为它的数据地址,而不是数据的字符串格式。

这是一个简单的Geeksforgeks示例:

这是一个更高效、更惯用、更通用、更简单的算法实现

// This works for any type as long as we know how to compare instances of it.
def compareTriplets[T : Ordering](as: List[T], bs: List[T]): (Int, Int) = {
  import Ordering.Implicits._ // Provides the comparison operators.

  (as lazyZip bs).foldLeft((0, 0)) {
    case ((aCount, bCount), (a, b)) =>
      if (a > b) (aCount + 1, bCount)
      else if (a < b) (aCount, bCount + 1)
      else (aCount, bCount)
  }
}
//这适用于任何类型,只要我们知道如何比较它的实例。
def compareTriplets[T:Ordering](as:List[T],bs:List[T]):(Int,Int)={
import Ordering.Implicits.\提供比较运算符。
(作为懒汉)foldLeft((0,0)){
案例((a账户,b账户),(a,b))=>
如果(a>b)(a账户+1,b账户)
如果(a
pritnln
总是调用
toString
问题在于,由于Java天才的存在,数组的
toString
打印的是它的地址而不是它的值。这就是数组的打印方式。您可以使用
Array.mkString(“[”,“,”,“])
获取数据的良好字符串表示形式。或者不要使用数组*+而是使用**列表,这是Scala中更高级、更惯用的数据结构。此外,我建议您不要使用可变性和循环,而是使用高阶函数或递归。此外,如果结果始终有两个元素,则不要返回集合。但是tuple。另外,您似乎对Scala不太熟悉,我建议您学习一些教程。谢谢您的帮助。但是lazyZip即使在导入导入导入顺序后也会抛出编译错误。@KrishnaKumar啊,对不起,
2.13
中添加了
laxyZip
,如果您使用的是较旧的版本,只需使用
zip
.
// This works for any type as long as we know how to compare instances of it.
def compareTriplets[T : Ordering](as: List[T], bs: List[T]): (Int, Int) = {
  import Ordering.Implicits._ // Provides the comparison operators.

  (as lazyZip bs).foldLeft((0, 0)) {
    case ((aCount, bCount), (a, b)) =>
      if (a > b) (aCount + 1, bCount)
      else if (a < b) (aCount, bCount + 1)
      else (aCount, bCount)
  }
}