从数组中取值后随机搭配求最大值
java写法
int arr[]={3,123,234}; Set<Integer> set=new HashSet<>(); while (true){ int index1=(int)(Math.random()*arr.length); String s1=String.valueOf(arr[index1]); int index2=(int)(Math.random()*arr.length); String s2=String.valueOf(arr[index2]); int index3=(int)(Math.random()*arr.length); String s3=String.valueOf(arr[index3]); if(!s1.equals(s2)&&!s1.equals(s3)&&!s2.equals(s3)){ String s=s1+s2+s3; set.add(Integer.valueOf(s)); } if(set.size()>=6){ break; } } Integer integer = set.stream().max(Integer::compareTo).get(); System.out.println(set); System.out.println(integer);
python写法:
import random # 从a中取出3个数,随机组合,并找出最大值 a=[3,123,234] b=[] while True: i=str(a[random.randint(0,2)]) j=str(a[random.randint(0,2)]) k=str(a[random.randint(0,2)]) if i==j or i==k or j==k: continue s=i+j+k if s not in b: b.append(int(s)) if len(b)>=6: break max=b[0] for i in range(0,5): if b[i]<b[i+1] and max<b[i+1]: max=b[i+1] print(max)
这种写法有明显的Bug 正确解法如下
import random l=[234,456,789] l2 = [] while True: num1=str(random.choice(l)) num2=str(random.choice(l)) num3=str(random.choice(l)) if num3==num2 or num2==num1 or num1==num3: continue s=num2+num1+num3 if s not in l2: l2.append(s) if len(l2)>=6: break print(l2) max=int(l2[0]) for i in range(0,6): print(l2[i]) if max<int(l2[i]): max=int(l2[i]) print("=============") print(max)