首页 > 解决方案 > ColdFusion - 生成随机文本(ID)答案列表

问题描述

我正在尝试创建随机测试答案。使用唯一 ID(文本)- 下面仅在我使用列表时随机化一次。如果我重新加载页面,它不会再次随机化。

另外 - 如果它是只有 2 个选择的真假答案。它不起作用。

大家有什么想法吗?或者有没有更简单的方法来做到这一点。我知道我可以很容易地用数字做到这一点,但我更喜欢文本中的唯一答案 ID)

      <cfset strList = "rttt,ddde,ffss,gggd" /> - works only once

      <cfset strList = "True,False" /> - doesn't work

      <!---
     Create a struct to hold the list of selected numbers. Because
     structs are indexed by key, it will allow us to not select
     duplicate values.
      --->

     <cfset objSelections = {} />

      <!--- Now, all we have to do is pick random numbers until our
     struct count is the desired size (4 in this demo).
      --->

      <cfloop condition="(StructCount( objSelections ) LT 4)">

     <!--- Select a random list index. --->
     <cfset intIndex = RandRange( 1, ListLen( strList ) ) />

     <!---
        Add the random item to our collection. If we have
        already picked this number, then it will simply
        overwrite the previous and the StructCount() will
        not be changed.
     --->
     <cfset objSelections[ ListGetAt( strList, intIndex ) ] = true />

      </cfloop>

      <cfoutput>
      <!--- Output the list collection. --->
      <cfset newlist = "#StructKeyList( objSelections )#">

      #newlist#

      </cfoutput>

标签: randomcoldfusioncfloop

解决方案


如果您希望返回一个随机的答案列表,您可以使用 Java 集合与您的 ColdFusion 列表进行交互(在将列表转换为数组之后)。

<cfscript>
  // Our original answer list.
  strlist1 = "rttt,ddde,ffss,gggd" ;

  // Convert our lists to arrays. 
  answerArray1 = ListToArray(strList1) ;

  // Create the Java Collection object. 
  C = CreateObject( "java", "java.util.Collections" ) ;

  // Java shuffle() our array.
  C.shuffle(answerArray1) ;

  // Output our shuffled array (as an array).
  writeDump(answerArray3) ;
  // Or convert it to a list for output.
  randomAnswerList = ArrayToList(answerArray3) ;
  writeoutput(randomAnswerList) ;
</cfscript>

https://trycf.com/gist/3a1157a11154575e705411814d10ea92/acf?theme=monokai

由于您使用的是小型列表,因此 Javashuffle()应该很快。对于大型列表,我相信它可能比构建一个随机函数来打乱列表效率低得多。这是因为 ColdFusion 数组自动也是 Java 数组。CF 与 Java 配合得非常好,尤其是对于这些类型的操作。

注意 1:Javashuffle()直接对其输入数组进行操作,因此您实际上是在更改数组本身。

注意 2:根据您要对列表执行的操作,将打乱的答案留在 Array 对象中并使用它可能会容易得多。此外,JavaCollection.shuffle()将与 Structs 一起使用。你是从查询中生成答案列表吗?这仍然有效,但取决于您之后如何使用查询,您可能不想shuffle()直接在查询对象上使用。


推荐阅读