我如何洗牌字的信吗? [英] How can I shuffle the letters of a word?

查看:103
本文介绍了我如何洗牌字的信吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是洗牌一句话这是一个数组中的字母最简单的方法?我有一个数组一些话,我随机选择一个字,但我也想洗牌它的字母。

 公共静态无效的主要(字串[] args){
    的String [] =动物{狗,猫,恐龙};
    随机随机=新的随机();
    串词=动物[random.nextInt(animals.length)];    的System.out.println(字);
    //我只是想打乱单词的字母
}

我不应该使用该列表的事情。我想出了这样的事情,但这个code它打印随机字母不洗牌。也许我可以code类似,如果已经打印的信,不打印?

  //一些随机的信
的for(int i = 0; I< word.length();我++){焦C =(word.charAt(random.nextInt(word.length())));
System.out.print(C); }
  }


解决方案

真是没有必要收集和什么比接下来更多:

 公共静态无效的主要(字串[] args){    //创建一个随机对象
    随机R =新的随机();    串词=动物;    的System.out.println(之前:+字);
    字=争夺(R,字);
    的System.out.println(后+字);
}公共静态字符串争抢(随机随机字符串inputString)
{
    //将您的字符串转换成一个简单的字符数组:
    所以char a [] = inputString.toCharArray();    //使用的争夺标准的费雪耶茨洗牌的字母,
    的for(int i = 0; I<则为a.length-1;我++)
    {
        INT J = random.nextInt(则为a.length-1);
        //交换信件
        焦炭TEMP = a [i];一个由[i] = A [J]。一个研究[J] =温度;
    }    返回新的String(一);
}

What is the easiest way to shuffle the letters of a word which is in an array? I have some words in an array and I choose randomly a word but I also want to shuffle the letters of it.

public static void main (String[] args ) {
    String [] animals = { "Dog" , "Cat" , "Dino" } ;    
    Random random = new Random();
    String word = animals [random.nextInt(animals.length)];

    System.out.println ( word ) ;
    //I Simply want to shuffle the letters of word     
}

I am not supposed to use that List thing. I've come up with something like this but with this code it prints random letters it doesn't shuffle. Maybe I can code something like do not print if that letter already printed?

//GET RANDOM LETTER
for (int i = 0; i< word.length(); i++ ) {

char c = (word.charAt(random.nextInt(word.length())));
System.out.print(c); } 
  }

解决方案

Really no need for collection and anything more than what follows:

public static void main(String[] args) {

    // Create a random object
    Random r = new Random();

    String word = "Animals";

    System.out.println("Before: " + word );
    word = scramble( r, word );
    System.out.println("After : " + word );
}

public static String scramble( Random random, String inputString )
{
    // Convert your string into a simple char array:
    char a[] = inputString.toCharArray();

    // Scramble the letters using the standard Fisher-Yates shuffle, 
    for( int i=0 ; i<a.length-1 ; i++ )
    {
        int j = random.nextInt(a.length-1);
        // Swap letters
        char temp = a[i]; a[i] = a[j];  a[j] = temp;
    }       

    return new String( a );
}

这篇关于我如何洗牌字的信吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆