简体   繁体   English

如何将数组转换为不带逗号/括号的字符串格式,并添加括号作为值

[英]How to convert an array to String format without commas/brackets and add parentheses as values

I want to take the array of random values I've generated and print the aforementioned array with parentheses outside the longest run of the same number. 我想获取我生成的随机值数组,并在括号中的相同数字的最长游程之外打印上述数组。 For example, if the array was [0,1,1,1,2,4,7,4] I'd like to receive 0(111)2474 as an output. 例如,如果数组为[0,1,1,1,2,4,7,4],我想接收0(111)2474作为输出。

This is my code thus far. 到目前为止,这是我的代码。

import java.util.Random;
import java.util.Arrays;

/**
 * Write a description of class ArrayRunner1 here.
 * 
 * @author Ibrahim Khan
 * @version (a version number or a date)
 */
public class ArrayRunner1 {

    /**
     * This method will generate my random numbers for my array. 
     * @param min minimum random value wanted
     * @param max maximum random value wanted
     * @return randomNum a random number between 1 and 6 inclusive
     */
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }

    public static void main(String[] args) {
        System.out.println("\f");


        //Part 1 - Generate a random array of length 40 with random 1-6 inclusive
        int[] array1 = new int[40];
        for (int i = 0; i < array1.length; i++) {
            array1[i] = randInt(1, 6);
        }
        System.out.println(Arrays.toString(array1));

        //Counts and RETURN: reports how many times each number is present
        int counter1 = 0;
        int counter2 = 0;
        int counter3 = 0;
        int counter4 = 0;
        int counter5 = 0;
        int counter6 = 0;
        for (int i = 0; i < array1.length; i++) {
            if (array1[i] == 1) {
                counter1++;
            }
            if (array1[i] == 2) {
                counter2++;
            }
            if (array1[i] == 3) {
                counter3++;
            }
            if (array1[i] == 4) {
                counter4++;
            }
            if (array1[i] == 5) {
                counter5++;
            }
            if (array1[i] == 6) {
                counter6++;
            }
        }

        System.out.println("There are " + counter1 + " ones.");
        System.out.println("There are " + counter2 + " twos.");
        System.out.println("There are " + counter3 + " threes.");
        System.out.println("There are " + counter4 + " fours.");
        System.out.println("There are " + counter5 + " fives.");
        System.out.println("There are " + counter6 + " sixes.");

        //Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.   
        //RETURN: The repeated number and the length of the run is then printed
        int counter = 1;
        int runMax = 1;
        int runMin = 0;
        int variableNum = 0;
        int startCounter = 0;
        int endCounter = 0;

        for (int i = 0; i < array1.length - 1; i++) {

            if (array1[i] == array1[i + 1]) {
                counter++;

                if (counter >= runMax {
                    runMax = counter;
                    runMin = i - counter + 1;
                    variableNum = array1[i];
                    startCounter = i - counter + 2;
                    endCounter = i + counter - 1;
                }
                } else {
                    counter = 1;

                }


            }
            System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
            System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);




            //Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one. 
        }
    }

try this code: 试试这个代码:

import java.util.Arrays;
import java.util.Random;

public class Snippet {
    /**
     * This method will generate my random numbers for my array.
     * 
     * @param min
     *            minimum random value wanted
     * @param max
     *            maximum random value wanted
     * @return randomNum a random number between 1 and 6 inclusive
     */
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }

    public static void main(String[] args) {
        System.out.println("\f");

        // Part 1 - Generate a random array of length 40 with random 1-6
        // inclusive
        int[] array1 = new int[40];
        for (int i = 0; i < array1.length; i++) {
            array1[i] = randInt(1, 6);
        }
        System.out.println(Arrays.toString(array1));

        // Counts and RETURN: reports how many times each number is present
        int counter1 = 0;
        int counter2 = 0;
        int counter3 = 0;
        int counter4 = 0;
        int counter5 = 0;
        int counter6 = 0;
        for (int i = 0; i < array1.length; i++) {
            if (array1[i] == 1) {
                counter1++;
            }
            if (array1[i] == 2) {
                counter2++;
            }
            if (array1[i] == 3) {
                counter3++;
            }
            if (array1[i] == 4) {
                counter4++;
            }
            if (array1[i] == 5) {
                counter5++;
            }
            if (array1[i] == 6) {
                counter6++;
            }
        }

        System.out.println("There are " + counter1 + " ones.");
        System.out.println("There are " + counter2 + " twos.");
        System.out.println("There are " + counter3 + " threes.");
        System.out.println("There are " + counter4 + " fours.");
        System.out.println("There are " + counter5 + " fives.");
        System.out.println("There are " + counter6 + " sixes.");

        // Counts the longest run of the same number. A run continues only when
        // consecutive numbers have the same value.
        // RETURN: The repeated number and the length of the run is then printed
        int counter = 1;
        int runMax = 0;
        int runMin = 0;
        int variableNum = 0;
        int startCounter = 0;
        int endCounter = 0;

        for (int i = 0; i < array1.length - 1; i++) {

            if (array1[i] == array1[i + 1]) {
                counter++;

                if (counter >= runMax) {
                    runMax = counter;
                    startCounter = i - counter +2;
                    // runMin = i-counter+1;
                    variableNum = array1[i];
                    endCounter = i+1;
                }
            } else {
                counter = 1;

            }

        }
        System.out.println("The longest run is " + runMax
                + " times and the number is " + variableNum + ". ");
        System.out.println("The run starts at " + startCounter
                + " and ends at " + endCounter);

        for (int i = 0; i < array1.length; i++) {
            if (i==startCounter) {
                System.out.print("(");
            }
            System.out.print(array1[i]);
            if (i==endCounter) {
                System.out.print(")");
            }
        }
        System.out.println();

        // Prints the array with parentheses outside the longest run, if there
        // is more than one max run, use the last one.
    }
}

Okay. 好的。 I think I have this. 我想我有这个。 The first answer was close, but if you run the program a few times, you discover issues. 第一个答案很接近,但是如果您多次运行该程序,则会发现问题。 There is a logic error somewhere in your above code, but I have a work around. 您上面的代码中某处存在逻辑错误,但我可以解决。 I think it is how you get the endCounter. 我认为这是您获取endCounter的方式。 It seems to count odd. 看来很奇怪。 But I got the program to work as far as I can tell. 但据我所知,该程序可以运行。 Try this out. 试试看 I have run it several times and it seems consistent. 我已经运行了好几次,它似乎是一致的。

import java.util.Random; 导入java.util.Random; import java.util.Arrays; 导入java.util.Arrays;

/** * Write a description of class ArrayRunner1 here. / ** *在此处编写ArrayRunner1类的描述。 * * @author Ibrahim Khan * @version (a version number or a date) */ public class ArrayRunner1 { * * @作者Ibrahim Khan * @版本(版本号或日期)* /公共类ArrayRunner1 {

/**
 * This method will generate my random numbers for my array. 
 * @param min minimum random value wanted
 * @param max maximum random value wanted
 * @return randomNum a random number between 1 and 6 inclusive
 */
public static int randInt(int min, int max) {
    Random rand = new Random();
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

public static void main(String[] args) {
    System.out.println("\f");


    //Part 1 - Generate a random array of length 40 with random 1-6 inclusive
    int[] array1 = new int[40];
    for (int i = 0; i < array1.length; i++) {
        array1[i] = randInt(1, 6);
    }
    System.out.println(Arrays.toString(array1));

    //Counts and RETURN: reports how many times each number is present
    int counter1 = 0;
    int counter2 = 0;
    int counter3 = 0;
    int counter4 = 0;
    int counter5 = 0;
    int counter6 = 0;
    for (int i = 0; i < array1.length; i++) {
        if (array1[i] == 1) {
            counter1++;
        }
        if (array1[i] == 2) {
            counter2++;
        }
        if (array1[i] == 3) {
            counter3++;
        }
        if (array1[i] == 4) {
            counter4++;
        }
        if (array1[i] == 5) {
            counter5++;
        }
        if (array1[i] == 6) {
            counter6++;
        }
    }

    System.out.println("There are " + counter1 + " ones.");
    System.out.println("There are " + counter2 + " twos.");
    System.out.println("There are " + counter3 + " threes.");
    System.out.println("There are " + counter4 + " fours.");
    System.out.println("There are " + counter5 + " fives.");
    System.out.println("There are " + counter6 + " sixes.");

    //Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.   
    //RETURN: The repeated number and the length of the run is then printed
    int counter = 1;
    int runMax = 1;
    int runMin = 0;
    int variableNum = 0;
    int startCounter = 0;
    int endCounter = 0;

    for (int i = 0; i < array1.length - 1; i++) {

        if (array1[i] == array1[i + 1]) {
            counter++;

            if (counter >= runMax ){

                runMax = counter;
                runMin = i - counter ;// was plus one I cahnged this.
                variableNum = array1[i];
                startCounter = i - counter + 2;
                endCounter = i + counter -1;
            }
            } else {
                counter = 1;

            }


        }
        System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
        System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);




        //Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one. 
        String output = "";// added this
        for(int x = 0; x < array1.length; x++)
        {
              if( x == startCounter)
              {
                    output += "("+array1[x];
              }
              else if( x == startCounter + runMax )
              {
                    else if( x == startCounter + runMax )
              {
                    if(x == array1.length-1)
                    {
                          output += ")";
                    }
                    else
                    {
                          output += ")"+array1[x];
                    }
              }
              else
              {
                    output += array1[x];
              }
        }
        System.out.print("\n"+output);
       }
}

Here's a shorter, more generic solution. 这是一个更短,更通用的解决方案。 This method takes any array of ints and prints parenthesis around the longest run of numbers. 此方法采用任何整数数组,并在最长的数字行周围打印括号。 If there are two runs of the same lengths it prints it around the first one. 如果有两个长度相同的行程,则将其打印在第一个行程的周围。

public String makeString(int[] ints) {
  if (ints.length == 0) return ""; // Quit early if there's nothing to do.

  // Initialize variables.
  int lastNumber = ints[0];
  // We keep track of the all time best run. Defaults to first int found.
  int bestStart = 0;
  int bestRun = 1;
  // ... as well as the current run.
  int currentStart = 0;
  int currentRun = 1;
  String s = ""+ints[0];

  // Starting from the second int, we check if the current run is continuing.
  for (int i = 1; i < ints.length; i++) {
    int current = ints[i];
    // If the current run continues, we update currentStart/currentRun, else we reset it.
    if (current == lastNumber) {
      currentRun++;
    } else {
      currentStart = i;
      currentRun = 1;
    }

    // Now we check if the currentRun is better than the best.
    // If so, we update bestStart/bestRun.
    if (currentRun > bestRun) {
      bestStart = currentStart;
      bestRun = currentRun;
    }

    lastNumber = current;
    s += current;
  }

  // Now that we've found it, we insert parenthesis aaaaaaand we're done!
  return s.substring(0, bestStart)
      +"("+s.substring(bestStart, bestStart+bestRun)+")"
      +s.substring(bestStart+bestRun);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM