You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于GetQuestion函数实现问卷系统随机抽取5个不重复问题?

实现LotusScript随机抽取5个不重复问卷问题的方案

核心思路

要实现随机抽取5个不重复问题,需要完成三个关键步骤:

  • 统计问卷视图中所有有效问题的总数
  • 生成5个范围在1~总问题数之间的不重复随机整数作为索引
  • 根据随机索引调用原GetQuestion函数获取对应问题,或直接从视图提取问题内容

代码实现

假设原GetQuestion函数通过问题序号从指定视图获取内容,以下是改造后的随机抽取函数实现:

原GetQuestion函数(参考结构)

Function GetQuestion(questionIndex As Integer) As String
    Dim ws As New NotesUIWorkspace
    Dim db As NotesDatabase
    Dim view As NotesView
    Dim doc As NotesDocument
    Set db = ws.CurrentDatabase
    Set view = db.GetView("vw_Questions") ' 替换为你的问题视图名称
    Set doc = view.GetNthDocument(questionIndex)
    
    If Not doc Is Nothing Then
        ' 拼接问题和答案,根据实际字段调整
        GetQuestion = doc.QuestionText(0) & Chr(13) & Chr(10) & doc.AnswerText(0)
    Else
        GetQuestion = ""
    End If
End Function

新增随机抽取函数GetRandomQuestions

Function GetRandomQuestions(targetCount As Integer) As Variant
    Dim ws As New NotesUIWorkspace
    Dim db As NotesDatabase
    Dim view As NotesView
    Dim totalQuestions As Integer
    Dim randomIndexes As New NotesIntegerArray
    Dim randomNum As Integer
    Dim resultList As Variant
    Dim i As Integer
    
    ' 初始化数据库和视图
    Set db = ws.CurrentDatabase
    Set view = db.GetView("vw_Questions")
    totalQuestions = view.AllEntries.Count
    
    ' 校验问题总数是否满足抽取需求
    If totalQuestions < targetCount Then
        Msgbox "可用问题数量不足,请检查问卷视图!"
        Exit Function
    End If
    
    ' 生成不重复的随机索引
    Randomize ' 初始化随机数生成器,保证每次结果不同
    Do While randomIndexes.Count < targetCount
        ' 生成1到总问题数之间的随机整数
        randomNum = Int((totalQuestions * Rnd) + 1)
        ' 检查索引是否已存在,避免重复抽取
        If Not randomIndexes.Contains(randomNum) Then
            Call randomIndexes.Add(randomNum)
        End If
    Loop
    
    ' 提取对应问题并返回
    ReDim resultList(0 To targetCount - 1)
    For i = 0 To targetCount - 1
        resultList(i) = GetQuestion(randomIndexes.Element(i))
    Next
    
    GetRandomQuestions = resultList
End Function

使用示例

调用函数获取5个随机问题,并遍历输出:

Dim randomQuestions As Variant
randomQuestions = GetRandomQuestions(5)

For Each qContent In randomQuestions
    Msgbox qContent ' 可替换为页面展示逻辑
Next

关键注意事项

  • 确保问题视图vw_Questions包含所有有效问卷问题,无额外分类或过滤条件,否则totalQuestions统计会偏差
  • NotesIntegerArray用于存储随机索引,方便快速判断重复;若使用低版本Notes不支持该类,可改用数组+循环判断的方式实现去重
  • Randomize语句必须放在随机数生成前,否则每次运行可能生成相同的随机序列

内容的提问来源于stack exchange,提问作者rexwang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:15:45