Ejemplo n.º 1
1
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   int m = scanner.nextInt();
   assert 1 <= m && m <= 100 : "out of range, m: " + m;
   int s = scanner.nextInt();
   assert 0 <= s && s <= 900 : "out of range, s: " + s;
   if (s > 9 * m || (s == 0 && m > 1)) {
     System.out.println("-1 -1");
     return;
   }
   if (m == 1 && s == 0) {
     System.out.println("0 0");
     return;
   }
   StringBuilder sb = new StringBuilder();
   int l = 0;
   for (int i = 0; i < m; i++) {
     int d = (s >= 9) ? 9 : s;
     sb.append(d);
     s -= d;
     if (d != 0) {
       l = i;
     }
   }
   String large = sb.toString();
   if (sb.charAt(m - 1) == '0') {
     sb.setCharAt(l, (char) (sb.charAt(l) - 1));
     sb.setCharAt(m - 1, '1');
   }
   String small = sb.reverse().toString();
   System.out.printf("%s %s", small, large);
 }
Ejemplo n.º 2
1
  /**
   * Static method that removes path and filetype from pathname.
   *
   * @param inString <code>String</code> containing filename with possible extension
   */
  static String toStubName(String inString) {

    File F = new File(inString);
    String name = F.getName(); // strips pathname from filename

    StringBuilder buf = new StringBuilder(name);
    String stubName;

    stubName = null;

    int dotIndex = buf.length(); // point to last char
    while (dotIndex > 0) {
      dotIndex--;
      if (buf.charAt(dotIndex) == '.') // look for file type sep
      {
        break;
      }
    }

    if (dotIndex > 0) {
      stubName = buf.substring(0, dotIndex);
    }

    return stubName;
  }
Ejemplo n.º 3
1
  /**
   * Appends a json encoded key/value pair to the given string builder.
   *
   * @param json
   * @param key
   * @param value
   * @throws UnsupportedEncodingException
   */
  private static void appendJSONPair(StringBuilder json, String key, String value)
      throws UnsupportedEncodingException {
    boolean isValueNumeric = false;

    try {
      if (value.equals("0") || !value.endsWith("0")) {
        Double.parseDouble(value);
        isValueNumeric = true;
      }
    } catch (NumberFormatException e) {
      isValueNumeric = false;
    }

    if (json.charAt(json.length() - 1) != '{') {
      json.append(',');
    }

    json.append(escapeJSON(key));
    json.append(':');

    if (isValueNumeric) {
      json.append(value);
    } else {
      json.append(escapeJSON(value));
    }
  }
Ejemplo n.º 4
1
 /**
  * Replace given characters in a given string builder.
  * The number of characters to replace has to match to number of
  * characters serving as a replacement.
  *
  * @param sb string builder containing a string to be modified
  * @param from characters to replaced
  * @param to replacement characters
  * @return original string builder with replaced characters.
  */
 public static StringBuilder replace(StringBuilder sb, CharSequence from, CharSequence to) {
   assert from.length() == to.length();
   for (int i=0; i<sb.length(); i++)
     for (int j=0; j<from.length(); j++)
       if (sb.charAt(i)==from.charAt(j)) sb.setCharAt(i, to.charAt(j));
   return sb;
 }
 public static void main(String[] args) {
   String input = "AliveisAwesome";
   StringBuilder input1 = new StringBuilder();
   input1.append(input);
   input1 = input1.reverse();
   for (int i = 0; i < input1.length(); i++) System.out.print(input1.charAt(i));
 }
Ejemplo n.º 6
1
  @Contract("null, _, _ -> null")
  private static String toCanonicalPath(
      @Nullable String path, char separatorChar, boolean removeLastSlash) {
    if (path == null || path.isEmpty()) {
      return path;
    } else if (".".equals(path)) {
      return "";
    }

    path = path.replace(separatorChar, '/');
    if (path.indexOf('/') == -1) {
      return path;
    }

    int start = pathRootEnd(path) + 1, dots = 0;
    boolean separator = true;

    StringBuilder result = new StringBuilder(path.length());
    result.append(path, 0, start);

    for (int i = start; i < path.length(); ++i) {
      char c = path.charAt(i);
      if (c == '/') {
        if (!separator) {
          processDots(result, dots, start);
          dots = 0;
        }
        separator = true;
      } else if (c == '.') {
        if (separator || dots > 0) {
          ++dots;
        } else {
          result.append('.');
        }
        separator = false;
      } else {
        if (dots > 0) {
          StringUtil.repeatSymbol(result, '.', dots);
          dots = 0;
        }
        result.append(c);
        separator = false;
      }
    }

    if (dots > 0) {
      processDots(result, dots, start);
    }

    int lastChar = result.length() - 1;
    if (removeLastSlash && lastChar >= 0 && result.charAt(lastChar) == '/' && lastChar > start) {
      result.deleteCharAt(lastChar);
    }

    return result.toString();
  }
Ejemplo n.º 7
1
 private static String prs(String str, boolean rotate) {
   StringBuilder val = new StringBuilder(str);
   for (int i = 0; i < val.length(); ) {
     int c = val.charAt(i);
     if (c < 48 || c > 57) {
       val.deleteCharAt(i);
     } else i++;
   }
   return (rotate ? val.reverse() : val).toString();
 }
Ejemplo n.º 8
1
Archivo: Macro.java Proyecto: bramk/bnd
  int process(CharSequence org, int index, char begin, char end, StringBuilder result, Link link) {
    StringBuilder line = new StringBuilder(org);
    int nesting = 1;

    StringBuilder variable = new StringBuilder();
    outer:
    while (index < line.length()) {
      char c1 = line.charAt(index++);
      if (c1 == end) {
        if (--nesting == 0) {
          result.append(replace(variable.toString(), link));
          return index;
        }
      } else if (c1 == begin) nesting++;
      else if (c1 == '\\' && index < line.length() - 1 && line.charAt(index) == '$') {
        // remove the escape backslash and interpret the dollar
        // as a
        // literal
        index++;
        variable.append('$');
        continue outer;
      } else if (c1 == '$' && index < line.length() - 2) {
        char c2 = line.charAt(index);
        char terminator = getTerminator(c2);
        if (terminator != 0) {
          index = process(line, index + 1, c2, terminator, variable, link);
          continue outer;
        }
      } else if (c1 == '.' && index < line.length() && line.charAt(index) == '/') {
        // Found the sequence ./
        if (index == 1 || Character.isWhitespace(line.charAt(index - 2))) {
          // make sure it is preceded by whitespace or starts at begin
          index++;
          variable.append(domain.getBase().getAbsolutePath());
          variable.append('/');
          continue outer;
        }
      }
      variable.append(c1);
    }
    result.append(variable);
    return index;
  }
 /** Return next string in the sequence "a", "b", ... "z", "aa", "ab", ... */
 static String getNextDirName(String old) {
   StringBuilder sb = new StringBuilder(old);
   // go through and increment the first non-'z' char
   // counts back from the last char, so 'aa'->'ab', not 'ba'
   for (int ii = sb.length() - 1; ii >= 0; ii--) {
     char curChar = sb.charAt(ii);
     if (curChar < 'z') {
       sb.setCharAt(ii, (char) (curChar + 1));
       return sb.toString();
     }
     sb.setCharAt(ii, 'a');
   }
   sb.insert(0, 'a');
   return sb.toString();
 }
Ejemplo n.º 10
1
  public static long solution1() {
    TreeSet<Long> triangleNums = Util.getTriangleNumbersByCount(1000);
    HashSet<String> triangleWords = new HashSet<String>();
    FileInputStream fileStream;
    try {
      fileStream = new FileInputStream("src/main/resources/words.txt");
      DataInputStream dataStream = new DataInputStream(fileStream);
      BufferedReader bufferedReader =
          new BufferedReader(new InputStreamReader(dataStream, "UTF-8"));
      String line = bufferedReader.readLine();
      if (null != line) {
        String[] words = line.split(",");
        dataStream.close();

        for (String word : words) {
          StringBuilder tempName = new StringBuilder(word);
          tempName.deleteCharAt(0);
          tempName.deleteCharAt(tempName.length() - 1);
          long score = 0;
          for (int i = 0; i < tempName.length(); i++) {
            // Assuming the names contains only A-Z
            score = score + (tempName.charAt(i) % 'A') + 1;
          }
          if (score > triangleNums.last()) {
            System.out.println(word + "\t" + score);
          }
          if (triangleNums.contains(Long.valueOf(score))) {
            triangleWords.add(word);
          }
        }
      }
      bufferedReader.close();
      dataStream.close();
      fileStream.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
    }
    return triangleWords.size();
  }
Ejemplo n.º 11
1
 /*
  * create method, that read from a txt file and read the MySQL language and write to the database.
  */
 public void createDB() {
   try {
     BufferedReader br = new BufferedReader(new FileReader("db_schema.txt"));
     String line = null;
     StringBuilder sb = new StringBuilder();
     while ((line = br.readLine()) != null) {
       sb.append(line);
       if (sb.length() > 0
           && sb.charAt(sb.length() - 1) == ';') { // see if it is the end of one line of command
         statement.executeUpdate(sb.toString());
         sb = new StringBuilder();
       }
     }
     br.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 12
0
  /**
   * Static method that turns punctuated sentence into filename.
   *
   * <p>Creates acceptable filename by
   *
   * <ul>
   *   <li>converting whitespace to single underscores
   *   <li>removing commas and periods
   *   <li>limiting result to 32 chars (arbitrary)
   * </ul>
   *
   * @param inString contains sentence or phrase to convert
   */
  static String toFileName(String inString) {
    int limit = 32; // max file name length

    StringBuilder buf = new StringBuilder(inString);
    StringWriter fileName = new StringWriter(limit);

    for (int i = 0; (i < buf.length()) && (fileName.getBuffer().length() < limit); i++) {
      char c = buf.charAt(i);
      switch (c) {
        case '.':
        case ',':
        case ';':
        case ':':
        case '\'':
        case '"':
        case '(':
        case ')':
        case '[':
        case ']':
        case '{':
        case '}':
          break;
        case ' ': // ignore whitespace (space & tab)
        case '\t':
          fileName.write('_');
          break;
        default:
          fileName.write(c);
      }
    }
    return fileName.toString();
  }
Ejemplo n.º 13
0
 private String trimLeadingSlash(String path) {
   StringBuilder builder = new StringBuilder(path);
   while (builder.length() > 0) {
     if (builder.charAt(0) == '/') {
       builder.deleteCharAt(0);
     } else {
       break;
     }
   }
   return builder.toString();
 }
Ejemplo n.º 14
0
  /**
   * Advances to the next sequence in the database file and returns true unless there is no more
   * sequences in the file and then false is returned.
   *
   * @return false if we are already at the end of the file else true
   */
  public boolean gotoNextSequence() {
    if (reader == null) {
      throw new MprcException(
          "FASTA stream not initalized properly. Call beforeFirst() before reading first sequence");
    }
    // we should have been left after reading a header because that is how we detect
    // the end of the next sequence
    if (nextHeader == null) {
      return false;
    }
    this.currentHeader = nextHeader;

    // read in lines until we reach the next header
    final StringBuilder sequenceBuilder = new StringBuilder();
    String nextLine = null;
    try {
      nextLine = this.reader.readLine();
    } catch (IOException e) {
      LOGGER.warn(e);
    }
    // if the next line is not a header or an end of line then append it to the sequence
    while (isSequence(nextLine)) {
      sequenceBuilder.append(cleanupSequence(nextLine));
      try {
        // read in the next line
        nextLine = this.reader.readLine();
      } catch (IOException e) {
        LOGGER.warn(e);
      }
    }

    while (nextLine != null && !isHeader(nextLine)) {
      try {
        nextLine = this.reader.readLine();
      } catch (IOException e) {
        LOGGER.warn(e);
      }
    }
    this.nextHeader = nextLine;

    // set the current sequence to the concatenation of all strings
    // If the sequence ends with an * signalizing end codon, quietly drop it
    if (sequenceBuilder.charAt(sequenceBuilder.length() - 1) == '*') {
      currentSequence = sequenceBuilder.substring(0, sequenceBuilder.length() - 1);
    } else {
      currentSequence = sequenceBuilder.toString();
    }

    // return true since we will have a next header
    return true;
  }
Ejemplo n.º 15
0
  /**
   * @param antPattern ant-style path pattern
   * @return java regexp pattern. Note that no matter whether forward or backward slashes were used
   *     in the antPattern the returned regexp pattern will use forward slashes ('/') as file
   *     separators. Paths containing windows-style backslashes must be converted before matching
   *     against the resulting regexp
   * @see com.intellij.openapi.util.io.FileUtil#toSystemIndependentName
   */
  @RegExp
  @NotNull
  public static String convertAntToRegexp(@NotNull String antPattern, boolean ignoreStartingSlash) {
    final StringBuilder builder = new StringBuilder();
    int asteriskCount = 0;
    boolean recursive = true;
    final int start =
        ignoreStartingSlash
                && (StringUtil.startsWithChar(antPattern, '/')
                    || StringUtil.startsWithChar(antPattern, '\\'))
            ? 1
            : 0;
    for (int idx = start; idx < antPattern.length(); idx++) {
      final char ch = antPattern.charAt(idx);

      if (ch == '*') {
        asteriskCount++;
        continue;
      }

      final boolean foundRecursivePattern =
          recursive && asteriskCount == 2 && (ch == '/' || ch == '\\');
      final boolean asterisksFound = asteriskCount > 0;

      asteriskCount = 0;
      recursive = ch == '/' || ch == '\\';

      if (foundRecursivePattern) {
        builder.append("(?:[^/]+/)*?");
        continue;
      }

      if (asterisksFound) {
        builder.append("[^/]*?");
      }

      if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '^' || ch == '$' || ch == '.'
          || ch == '{' || ch == '}' || ch == '+' || ch == '|') {
        // quote regexp-specific symbols
        builder.append('\\').append(ch);
        continue;
      }
      if (ch == '?') {
        builder.append("[^/]{1}");
        continue;
      }
      if (ch == '\\') {
        builder.append('/');
        continue;
      }
      builder.append(ch);
    }

    // handle ant shorthand: mypackage/test/ is interpreted as if it were mypackage/test/**
    final boolean isTrailingSlash =
        builder.length() > 0 && builder.charAt(builder.length() - 1) == '/';
    if (asteriskCount == 0 && isTrailingSlash || recursive && asteriskCount == 2) {
      if (isTrailingSlash) {
        builder.setLength(builder.length() - 1);
      }
      if (builder.length() == 0) {
        builder.append(".*");
      } else {
        builder.append("(?:$|/.+)");
      }
    } else if (asteriskCount > 0) {
      builder.append("[^/]*?");
    }
    return builder.toString();
  }
Ejemplo n.º 16
0
 public static StringBuilder fixTrailingCommaList(StringBuilder sb) {
   if (sb.charAt(sb.length() - 1) == ',') {
     sb.deleteCharAt(sb.length() - 1);
   }
   return sb;
 }
Ejemplo n.º 17
0
  private static String canonicalURI(String s) {
    if (s == null) {
      return null;
    }
    StringBuilder result = new StringBuilder();
    final int len = s.length();
    int pos = 0;
    while (pos < len) {
      char c = s.charAt(pos);
      if (isPathSeparator(c)) {
        /*
         * multiple path separators.
         * 'foo///bar' -> 'foo/bar'
         */
        while (pos + 1 < len && isPathSeparator(s.charAt(pos + 1))) {
          ++pos;
        }

        if (pos + 1 < len && s.charAt(pos + 1) == '.') {
          /*
           * a single dot at the end of the path - we are done.
           */
          if (pos + 2 >= len) {
            break;
          }

          switch (s.charAt(pos + 2)) {
              /*
               * self directory in path
               * foo/./bar -> foo/bar
               */
            case '/':
            case '\\':
              pos += 2;
              continue;

              /*
               * two dots in a path: go back one hierarchy.
               * foo/bar/../baz -> foo/baz
               */
            case '.':
              // only if we have exactly _two_ dots.
              if (pos + 3 < len && isPathSeparator(s.charAt(pos + 3))) {
                pos += 3;
                int separatorPos = result.length() - 1;
                while (separatorPos >= 0 && !isPathSeparator(result.charAt(separatorPos))) {
                  --separatorPos;
                }
                if (separatorPos >= 0) {
                  result.setLength(separatorPos);
                }
                continue;
              }
          }
        }
      }
      result.append(c);
      ++pos;
    }
    return result.toString();
  }