-1

I am having trouble figuring out the programming logic.How do you get the array of strings to print asteriks at random indexes. Note that the 3 is the number of asterisk to be generated in the array.

so the output can be [a,b*,c*,d,e*,f,g,h] or [a*,b,c,d,e,f,g*,h*]

public class Generate
    {
      public static void main(String[] args)
      {
        String[] list = {"a","b","c","d","e","f","g","h"};

        for(int i =0; i <list.length; i++)
        {
          System.out.print("   " + list[i]);
          generateAsterisk(list);
        }
        System.out.println();

      }

      public static void generateAsterisk(String[] list)
      {
        for(int i = 0; i < 3; i++)
        {
          int index = (int)(Math.random()*i);

        }
              System.out.print("*");
      }
    }
Aurora_Titanium
  • 472
  • 1
  • 8
  • 23

2 Answers2

3

You can do it like that:

import java.util.Random;

public class Generate {

public static void main(String[] args) {
    String[] list = { "a", "b", "c", "d", "e", "f", "g", "h" };

    //do it 3 times or change to as many times you want to add an asteriks
    for (int i = 0; i < 3; i++) {
        addRandomAsteriks(list);
    }

    //print the array
    for (int i = 0; i < list.length; i++) {
        System.out.print("   " + list[i]);
    }
    System.out.println();

}

    public static void addRandomAsteriks(String[] list) {
      Random rand = new Random();
      int randomNumber = rand.nextInt(list.length - 1);
      String string = list[randomNumber]; //get the string at the random index
      if (!string.contains("*")) {
          // add the asteriks
          list[randomNumber] = string.concat("*"); 
      }else {
          //if it had already an asteriks go through the 
          //add-method again until you find one that has no asteriks yet.
          addRandomAsteriks(list);
      }
    }

This is a more object oriented point of view than YassinHH's answer.

This solution works and has only arrays in use.

SWiggels
  • 2,159
  • 1
  • 21
  • 35
  • 1
    Is there a way to eliminate random number duplicates? :) Seems to be a problem when u use .random class lol – Aurora_Titanium Sep 24 '15 at 12:11
  • When a random number is generated again, we check for an already added asterisk. So it does not hurt. But if there are a lot of collisions (same number) or even in the worst case we never get an "free place" the code runs infinite. Not getting collisions is nearly impossible... using arrays and Random only – SWiggels Sep 24 '15 at 12:15
  • Have a look at this article: [Article no duplicates in random generation](http://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates) – SWiggels Sep 24 '15 at 12:17
0

You can call the generateAsteriks method only once, with the number of asteriks you want:

String[] list = {"a","b","c","d","e","f","g","h"};

generateAsterisks(list, 3);
...

And change your generateAsteriks method to this:

public static void generateAsterisks(String[] list, int numAsteriks)
{
    for(int i = 0; i < numAsteriks && i < list.length; i++)
    {
        int index = (int)(Math.random()*list.length);

        //check if already added *
        if(list[index].lastIndexOf('*') != list[index].length()-1) {
            list[index] = list[index] + "*";
        } else {
            //don't count this loop iteration
            i--;
        }
    }
}
Ron C
  • 1,176
  • 9
  • 12
  • This can end in a possible array out of bound exception. Same problem as yassinHH's answer when using the actual number of elements as maximum. Arrays index start at 0 but an 8 is possibly using your strategy. – SWiggels Sep 24 '15 at 12:02
  • 1
    Array index out of bounds exception can't happen because I always access the array with the `index` variable, and it's range is between 0 to `list.length-1`. But if the 'numAsteriks' is bigger then `list.length`, the loop will become endless loop. I'll fix that. – Ron C Sep 24 '15 at 12:10
  • 1
    hey i have a question. it is possible to use this code on an array of strings. What if you create a class Object and use an Object array, will the code work? – Aurora_Titanium Sep 25 '15 at 09:01
  • `int index = (int)(Math.random()*list.length);` `int = 8 <-- possible ` `list[8].length()-1 <-- arrayoutof bound.` You shorten the lenght of the string by one not the index. Means you still can get an array out of bound exception. – SWiggels Sep 25 '15 at 09:12
  • `(int)(Math.random()*list.length)` returns integer between 0 to `list.length-1`, so if the length of the array is 8, the maximum index will be 7. `ArrayIndexOutOfBoundsException` cannot occur. – Ron C Sep 25 '15 at 09:36
  • @Aurora_Titanium I don't sure if I understands your question but if you are using `Object[]`, then where you are generating asterisk, the object in that index will be replaced with a `String` object with the value `list[index].toString()+"*"`. – Ron C Sep 25 '15 at 09:47
  • So say you have an Object array of size 30.. (Calender Object). Is it possible to make it in such a way where you can place an asterik beside the number like 1 - 30 where at random locations in 1 to 30 range.. there will be asterisk – Aurora_Titanium Sep 25 '15 at 10:13
  • Do you want to replace the `Object` with `String` with asterisk or change the `Calendar ` object so it will contain asterisk? – Ron C Sep 25 '15 at 10:27
  • Basically so that inside the calendar object, it will have the object itself together with the asterisk. so 1 2 3 4* 5 ...... 27* ... 30 – Aurora_Titanium Sep 25 '15 at 10:32
  • It's hard to say without seeing the `Calendar` class but you basically need to add the asterisk to the filed you want inside the object (the field must be a string). Or you can add boolean field (e.g 'marked') with default value `false` and if you generate asterisk for it you change the value to `true` (you can add the `*` sign in the `toString()` method) – Ron C Sep 25 '15 at 10:47
  • I will try to fix it.. If i have trouble can I type it here if its ok? :) Thats how everyone learns lol – Aurora_Titanium Sep 25 '15 at 10:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90618/discussion-between-aurora-titanium-and-ron-c). – Aurora_Titanium Sep 25 '15 at 12:37