2014-01-17 95 views
1

我想写一个代码,它将随机选择1到4个列表中的50个元素。我正在使用的名单是['nu', 'ne', 'na', 'ku', 'ke', 'ka']随机从列表中选择x个元素

所以基本上,我希望它输出类似

nukuna 
ke 
keka 
nuka 
nane 
nanenu 
nu 
nukekanu 
kunu 
... 

50倍

+0

什么脚本/编程语言,你使用? – Matt

+0

你使用哪种语言? – arshajii

+0

我正在使用Python – user3207653

回答

-1
int i=0; 
StringBuffer stb=new StringBuffer(); 
String[] arr= {"nu", "ne", "na", "ku", "ke", "ka"}; 
while(i<50){ 
int idx = new Random().nextInt(arr.length); 
stb.append(arr[idx]); 

i++; 
} 
+0

这与要求不符。它只发布了50个随机元素,而不是50个最多4个随机元素的字符串。 – Harald

+0

哦,这是java code>,因为你稍后提到了语言。 –

+0

我意识到了,但无论如何感谢 – user3207653

1

在Python:

import random 

input = [...] # Your input strings 
output = '' 

random.seed() # Seed the random generator 

for i in range(0,len(input)): 
    N = 1+random.randrange(4) # Choose a random number between 1 and 4 
    for j in range(0,N): # Choose N random items out of the input 
     index = random.randrange(len(input)-j) 
     temp = input[index] 
     input[index] = input[len(input)-j-1] 
     input[len(input)-j-1] = temp 
     output += temp 
    output += ' ' 

print output 

在C:

#include <stdlib.h> 
#include <string.h> 
#include <stdio.h> 
#include <time.h> 

char* input[NUM_OF_INPUT_STRINGS] = {...}; // Your input strings 
char output[MAX_SIZE_OF_OUTPUT+1]; 

// Seed the random generator 
srand((unsigned int)time(NULL)); 

for (int i=0; i<NUM_OF_INPUT_STRINGS; i++) 
{ 
    // Set the output string empty 
    output[0] = 0; 
    // Choose a random number between 1 and 4 
    int N = 1+(rand()%4); 
    // Choose N random items out of the input 
    for (int j=0; j<N; j++) 
    { 
     int index = rand()%(NUM_OF_INPUT_STRINGS-j); 
     char* temp = input[index]; 
     input[index] = input[NUM_OF_INPUT_STRINGS-j-1]; 
     input[NUM_OF_INPUT_STRINGS-j-1] = temp; 
     strcat(output,temp); 
    } 
    // Print the output 
    printf("%s ",output); 
} 
+0

谢谢,但我得到了Python中“列表索引超出范围”的错误。我该如何解决这个问题? – user3207653

+0

适合我的作品;你是否证实'input'数组包含'NUM_OF_INPUT_STRINGS'字符串? –

+0

更好的是 - 我用'len(input)'替换了'NUM_OF_INPUT_STRINGS',所以你可以在'input'数组中放入任意数量的字符串...... –

0

尝试用这个Python代码:

import random 

my_list = ['nu', 'ne', 'na', 'ku', 'ke', 'ka'] 

for i in xrange(0,50): 
    tmp_string = '' 
    count = random.randrange(1,4)  # choose a random between 1 and 4 
    for j in xrange(0, count): 
     # add a random member of the list to the temporary string 
     tmp_string = tmp_string + random.choice(my_list) 
    print tmp_string   # print each final string 
+0

我看到他编辑了你的文章,并对其进行了降级投票,就像他对我的投票一样。这个用户应该被禁止从这个网站。我正在投票,以便“赔偿”你的损失。 –

+1

是的,我也和你一样,谢谢! –

+0

谢谢。顺便说一句,除了你在评论中提到的他的回答(事实上,他发布的答案与它发布一年多之后的一个答案相同),你可能还想检查(也可能还原)他的编辑到你自己的答案。就我而言,他不仅投票回答了答案,而且还将其从工作代码更改为非工作代码。 –