algorithm 1 « algorithm « Java Collection Q&A

Java Collection Q&A
3.Array Byte
4.Array Char
5.Array Convert
6.Array Dimension
7.Array Integer
8.Array Object
9.Array String
14.Garbage Collection
Java Collection Q&A » algorithm » algorithm 1 

1. RFC calculation in Java need help with algorithm

The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in ...

2. Impose a total ordering on all instances of *any* class in Java

I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc.

class TotalOrder<T> implements Comparator<T> {

    public boolean compare(T o1, T o2) {

3. Load Balance in Distributed Project

Does anyone know a simple load balance algorithm (formula) that relates users connected, cpu load, network load and memory usage? This will be used to compare various servers and assign to a ...

4. Programming Problem - Fax Compression

I'm preparing to go to a computer science contest by completing problems from past contests. Most of them are pretty easy, but this one is bugging seems simple but I'm ...

5. Common algorithm for generating a diff of the fields in two beans?

Let's say you have two instances of the same bean type, and you'd like to display a summary of what has changed between the two instances - for example, you have ...

6. How to implement a most-recently-used cache

What would be the best way to implement a most-recently-used cache of objects? Here are the requirements and restrictions...

  • Objects are stored as key/value Object/Object pairs, so the interface would be a bit ...

7. Lossless JPEG Rotate (90/180/270 degrees) in Java?

Is there a Java library for rotating JPEG files (90/180/270 degrees) without quality degraded?

8. Implementation of Prim's Algorithm

For my CS class I need to implement Prim's algorithm in Java and I am having problems with the priority queue step. I have experience with priority queues and understand they ...

9. Algorithm for estimating text width based on contents

This is a long shot, but does anyone know of an algorithm for estimating and categorising text width (for a variable width font) based on its contents? For example, I'd like to ...

10. Print methods not called when running, called when debugging

I created a class with four methods. I inserted print statements into them, so I could see if they work properly. There is no problem with the first three. But when ...

11. Java task runtime

First of all I have to admit that these are very basic and primitive questions... I want to demonstrate different Algorithms in Java for sorting and searching, and to get a ...

12. How can I implement this equation in Java?

OK, this is more of a follow-up question: How to compute optimal paths for traveling salesman bitonic tour? First of all, for the bitonic tour of the traveling salesman problem I ...

13. Grouping Items into Balanced Groups

What's the best way to group x amount of items into y amount of groups based on a variable property of each item eg. weight. Leaving me with y amount of ...

14. Distributed systems, best framework?

I am building a software program that follows the scenario: I have many computers, and add each one of them to the a cluster. Each computer in the cluster can add a file ...

15. Easiest to code algorithm for Rubik's cube?

Edit: I should rephrase this, what would be a relatively easy algorithm to code in Java for solving a Rubik's cube. Efficiency is also important but a secondary consideration. Orig: What is ...

16. Help me implement a rewindable buffer

This is where I'm so far: I have the following the following use case (as impartial jUnit test) to show what I want to achieve:

assertEquals(1, buffer.size());
assertEquals(2, buffer.size());
assertEquals(3, buffer.size());
assertSame(o1, buffer.get());
assertSame(o2, buffer.get());
assertSame(o3, buffer.get());
// NOTE: ...

17. Algorithms behind this animated java applet

I was recently happened to see this animation ( I was wondering what are the algorithms behind this applet. How and Where to learn such things? Thanks

18. Set Combinatorics Algorithm in Java

I have a data set with attributes like this:

Marital_status = {M,S,W,D}
IsBlind = {Y,N}
IsDisabled = {Y,N}
IsVetaran = {Y,N}
etc. There are about 200 such variables. I need an algorithm to generate combinations of the ...

19. implementing unification algorithm

I worked the last 5 days to understand how unification algorithm works in Prolog . Now ,I want to implement such algorithm in Java .. I thought maybe best way is to manipulate ...

20. My problem is how do i make this work

import java.util.Scanner;

public class Fraction
private int numerator;
private int denominator;
    private int product;
    private int sum;

public Fraction(int num, int denom)

 if (this.denominator == 0){

 System.out.println("can ...

21. How do I fix an "Illegal start of expression" error in Java?

I am getting an "Illegal start of expression" error in the following code at the location marked by a comment. How can I correct this error?

class planetUfo {

22. How can I add business days to the current date in Java?

How can I add business days to the current date in Java?

public Calendar addBusinessDate(Calendar cal, int days) {
// code goes over here


It should consider weekends too.

23. Making a Java -code more efficient, USACO

I am trying to complete the first exercise of USACO. How can you make the following code more efficient? It seems that the current problem in the program is that its execution takes ...

24. HTML Parsing/Scraping Algorithm Help..Java

I am writing a program that an HTML scraper that when it grabs the HTML from the page, it returns the HTML, and I want to Grab words that are All ...

25. Dancing Links: Algorithm X not working as expected!

I have implemented the algorithm X using Dancing Links in Java, however, I'm getting unexpected results, that is I'm having dupes of rows of results which are not exact covers. My code ...

26. Why is my Polymorphic Parent class calling the Subclass Method from within itself?

Heres the code I've made up so far. Its fully functional and the only gripe I have with it is that my output for Weekly and Annual pay is always ...

27. Java NullPointerException

I'm writing two classes to handle simple auctions. I have a class ready and working, which handles the operations for a single auction, and now I'm writing another class like an ...

28. O Notation Help

I am getting stuck with the class work we got this week and its a subject i really want to learn so for once i thought i would do the additional ...

29. Question about return statements

import java.util.Scanner;

public class GregorianYear

    private int year;

    public GregorianYear(int a)

     year = a;


30. Markov Chain Text Generation

We were just assigned a new project in my data structures class -- Generating text with markov chains. Overview Given an input text file, we create an initial seed of length n ...

31. is there another way of solving this problem?

i have a list 1 column and 100 rows each with a number the number on each row may not be unique i need to output the unique list of numbers sorted according ...

32. Obtaining powerset of a set in java

The powerset of {1, 2, 3} is: {{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}} Lets say I have a Set in Java...

Set<Integer> mySet = new HashSet<Integer>();
Set<Set<Integer>> powerSet ...

33. Iterative Cartesian Product in Java

I want to compute the cartesian product of an arbitrary number of nonempty sets in Java. I've wrote that iterative code...

public static <T> List<Set<T>> cartesianProduct(List<Set<T>> list) {
 List<Iterator<T>> iterators = new ArrayList<Iterator<T>>(list.size());

34. Running a fastest-algorithm competition

I'd like to run competitions like code golf competitions, but the winner would have the fastest algorithm, not the smallest code.

  • One fair way to measure speed of an algorithm is to ...

35. Getting suggestions on how to get the best code coverage in java

Several tools exists that allow to calculate path coverage for a set of tests, but is there a tool (or an algorithm) that could suggest values to get the best path ...

36. How do I use the DES Algorithm in .NET?

How do I use DES in .NET? Here's how I'd do it in Java:

        public static String decrypt(byte[] pin, byte [] desKeyData ) throws Exception ...

37. Text read and replace algorithm

Looking at this:

...and so on (over 500 lines). What would be the best way to automate copying the label name into the label itself. For example,
would become
I am most familiar ...

38. algorithm for getting time zone from geo coordinates

I want to write app where user can point any place on map (not only cities) and get timezone in that place. What data structure (app will not have Internet connectivity) and ...

39. Send and receive data over a 'noisy' data stream

My Java program saves its data to a binary file, and (very) occasionally the file becomes corrupt due to a hardware fault. Usually only a few bytes are affected ...

40. Algorithm choices - understanding which and why

I am writing a document and was unsure of the following:

  1. I am going to compare two algorithms that can perform on the same structure but we cant say one will always ...

41. Implementation of a simple algorithm (to calculate probability)

EDIT: I've got it, thanks for all the help everyone! + Cleaned up post a little bit. Also, this article was very helpful:

Hi all, I've been asked (as part of ...

42. General classes/source code for solving Java algorithmic problems?

I need to build a small repository of algorithms with implementation and description. I found recently, for example, an efficient permutations generator for permutations of arbitrary length. Where can I find ...

43. What is a good solution for calculating an average where the sum of all values exceeds a double's limits?

I have a requirement to calculate the average of a very large set of doubles (10^9 values). The sum of the values exceeds the upper bound of a double, so ...

44. I need a cycle which iterates through dates interval

I have the start date and the end date. I need to iterate through every day between these 2 dates. What's the best way to do this? I can suggest only something like:

Date ...

45. min-conflicts Algorithm to Solve N-Queen Proplem

using nQueens problem how to translate this algorithm to java code

 function MIN-CONFLICTS(csp,max_steps) returns a solution or failure
   inputs: csp, a constraint satisfaction problem

46. Algorithm to determine possible groups of items

I am scratching my head trying to do this and it's eating me up. I know it is not THAT complex. I have a number of items, this number can be ...

47. Cardinal direction algorithm in Java

This weekend I spend a few minutes thrashing together an algorithm that would take in a heading (in degrees) and return a String for the cardinal direction (I'm using it in ...

48. How can I get the possessive form of a noun?

Here's an algorithm for adding an apostrophe to a given input noun. How would you contruct a string to show ownership?

 * apostrophizes the string properly
 * <pre>
 * curtis = curtis'

49. Right Shift to Perform Divide by 2 On -1

I know that I can perform divide by 2 using right shift. For simplicity, take a 4 bit number system

-1 - 1111
-2 - 1110
-3 - 1101
-4 - 1100
-5 - 1011
-6 - ...

50. Determine whether or not there exist two elements in Set S whose sum is exactly x - correct solution?

Taken from Introduction to Algorithms

Describe a ?(n lg n)-time algorithm that, given a set S of n integers and another integer x, determines whether or not ...

51. Moving between co-ordinates, Java Algorithms

Ok this question is going to be a little abstract. I have an icon moving along a line which is represented by a series of coordinates stored in a vector, and I ...

52. Help me create JojoMips algorithm, the BogoMips for Java VMs

I would like to test the speed of different Java platforms and thought about creating a JojoMips benchmark routine that would work like the Linux BogoMips. It would do a calculation ...

53. Fastest way to get the set of convex polygons formed by Voronoi line segments

I used Fortune's Algorithm to find the Voronoi diagram of a set of points. What I get back is a list of line segments, but I need to know which segments ...

54. Designing this algorithm a better way?

I am working a much more complex version of this (with vehicle moving in both X and Y directions) I made this example to get ideas on better ways to accomplish this.

  1. I ...

55. Java: How to determine programmatically that a dataset doesn't follow a normal distribution?

In a Java program, how can I determine if a dataset I have is following or not a normal distribution? Is it possible? Is there an API or an algorithm that I can ...

56. How can I measure the speed of code written in Java? (AI algorithms)

How can I measure the speed of code written in Java? I planning to develop software which will solve Sudoku using all presently available AI and ML algorithms and compare time ...

57. Most elegant way to change 0 to 1 and vice versa

What is the most elegant way to do the next stuff:

int i = oneOrZero;

if (i == 0) {
   i = 1;
} else {
   i = 0;
You can ...

58. Finding All Ways in FlowChart diagram?

I made an FlowChart diagram editor on Java. It It drows flowscharts and connect them each other and creates me two array. One of it shows connection nodes and lines , ...

59. Trend analysis using iterative value increments

We have configured iReport to generate the following graph: The real data points are in blue, the trend line is green. The problems include:

  • Too many data points for the trend ...

60. Can SHA-1 algorithm be computed on a stream? With low memory footprint?

I am looking for a way to compute SHA-1 checksums of very large files without having to fully load them into memory at once. I don't know the details of the ...

61. Convert arbitrary size of byte[] to BigInteger[] and then safely convert back to exactly the same byte[], any clues?

I believe conversion exactly to BigInteger[] would be optimal in my case. Anyone had done or found this written in Java and willing to share? So imagine I have arbitrary size byte[] ...

62. The Collatz Sequence problem

I'm trying to solve this problem, its not a homework question, its just code I'm submitting to so I can learn better java trough examples. Here is the problem sample ...

63. Algorithm to detect no movable pieces in Stratego

I am creating a Stratego Game and am having trouble creating an algorithm that can detect when there are no more possible moves because all your pieces are gone or the ...

64. Algorithm Analysis tool for java

I am looking for an algorithm analysis tool for java that can calculate Big 0 of a function. Ideal I would like to make it part of my build process, along ...

65. Selecting item from set given distribution

I have a set of X items such as {blower, mower, stove} and each item has a certain percentage of times it should be selected from the overall set {blower=25%,mower=25%,stove=75%} along ...

66. Java Algorithm HmacSHA256 not available

I am trying an encryption-decryption code in java. When I am trying to run it with JDK and code in class with main method it is running fine. But when I ...

67. Diamond square algorithm

I'm trying to write the Diamond-Square algorithm in Java to generate a random map but can't figure out the implementation... Anyone with some Java code (or other language) so i ...

68. How to implement SHA 1 Algorithm in Java

i want to implement SHA 1 Algorithm using java. Can any one help me Thanks in advance

69. Looking for advice on how to do some bit-twiddling

Suppose I have the array

int a[] = new int[] { 0xBCDA, 0xABFE, 0xBCAD, 0xEFCA, 0xFFCA }
I know that there is always some hexadecimal number which occurs in all number or in ...

70. HPC (mainly on Java)

I'm looking for some way of using the number-crunching ability of a GPU (with Java perhaps?) in addition to using the multiple cores that the target machine has. I will be ...

71. Help implementing the All Nearest Smaller Values algorithm This is the site of the problem and here is my code, but I have some trouble to implement it:

import java.util.*;
public class stack{

    public static void ...

72. implement this variable in java

Suppose code is given like this:

pattern_mask[pattern[i]] &= ~(1UL << i);
What kind of type is this in Java? How do I implement this in Java?

73. NoSuchAlgorithmException: Algorithm HmacSHA1 not available

Look at the following line of java:

If I put this in a simple test program, it runs without problems on my server. However, if I use this line in a container, ...

74. substitution cypher with different alphabet length

I would like to implement a simple substitution cypher to mask private ids in URLs I know how my IDs will look like (combination of upperchase ascii, digits and underscore), and they ...

75. Implementing Naïve Bayes algorithm in Java - Need some guidance

As a School assignment i'm required to implement Naïve Bayes algorithm which i am intending to do in Java. In trying to understand how its done, i've read the book "Data Mining ...

76. question about polynomial multiplication

i know that horners method for polynomial pultiplication is faster but here i dont know what is happening here is code

public class horner{

  public static  final ...

77. Java: Longest common subsequence

I have following code:

public class LCS1 {

  public static String lcs(String a,String b) {
      String x;
      String y;


78. question about Tetration

i have question how write program which calculates following procedures
i have exponential program which returns x^n here is code
public class Exp{
public static long ...

79. Modular Inverse and BigInteger division

I've been working on the problem of calculating the modular inverse of an large integer i.e. a^-1 mod n. and have been using BigInteger's built in function modInverse to check ...

80. Page replacement algorithm simulation in Java

Is there utility program for Page replacement algorithm simulation in Java?

81. Garbage Collection in Java

On the slides I am revising from it says the following:

Live objects can be identified either by maintaining a count of the number of references to each object, or ...

82. Question about permute-by-sorting

In the book "Introduction to Algorithms", second edition, there is the following problem: Suppose we have some array:

int a[] = {1,2,3,4}
and some random priorities array:
P = {36,3,97,19}
and the goal is to permute ...

83. define bigrand function in java

here is code of bigrand function in c code

int bigrand (){
 return  RAND_MAX* rand()+rand();
please tell me what is equivalent code in java?

84. question about charAt function

i know java API function charAt for example

String  s="dato"
  char r=s.charAt(0); r is equal d
but my question is how realy it works or what function ...

85. algorithm to combinatorics

I am trying to solve a combinatorics problem, it seems easy, but i am having some trouble with it. If i have at most X tables, and N persons to sit on ...

86. implementing jacobi algorithm to implement laplace equation

The Algorithm traverses a 2D NxN array, making every element the average of its 4 surrounding neighbors (left, right, top, down). The NxN array has initially all zeros and is surrounded by ...

87. logics for crossword

I have a task to create a crossword, a specific one. All the answers are given, but their places are unknown. Program must read a file with board scheme like this ...

88. Improving a prime sieve algorithm

I'm trying to make a decent Java program that generates the primes from 1 to N (mainly for Project Euler problems). At the moment, my algorithm is as follows: Initialise an array of ...

89. Java Decorating The Easy Way

Say you have an API that is not accessible to change:

List<LegacyObject> getImportantThingFromDatabase(Criteria c);
Imaging Legacy Object has a ton of fields and you want to extend it to make getting at certain ...

90. Roulette prediction with Java

Im need to implement a Roulette Prediction System (Roulette Calculator). The scenario is: The player put on the system the values from roulette, and the system tip to him the best bet and ...

91. Algorithm to generate a Turing Machine from a Regular Expression

I'm developing a software to generate a Turing Machine from a regular expression. [ EDIT: To clarify, the OP wants to take a regular expression as input, and programmatically generate a ...

92. question about euler project's problem

here is problem about sum of factorial of digit also here is Define sf(n) as the sum of the digits of f(n). So sf(342) = 3 + 2 = ...

93. Null PointerException in AES algorithm

This is the code for encrypting and decrypting a string in java using AES algorithm. StackTrace:

    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

94. Is a Java book enough or should I have to learn algorithms first?

I am new to Java and referring Head-First book. Do I have to learn Algorithms to be able to make programs in Java? Should I learn Algorithms first or only Java books ...

95. Implementing Algorithms in Java

How can I implement Near array based Prim's algorithm and Disjoint Set based Kruskal's algorithm in java. I have tried but failed. So I can asking for some hints/helps

96. tdd with non-trivial algorithms

In these days I'm coding some data structures in Java. Many of them (if not all) offer a very simple interface (add, contains, delete) but under the hood there are non-trivial ...

97. Working with huge text files in Java

I was given an English vocabulary assignment by my teacher.

Choose a random alphabet, say 'a' Write a word from the alphabet, say 'apple' Take the last word ...

98. Connect the dots - connect the line between contour points

I have a gray scale image of 64x64. I found the dots of the contour by a simple algorithm:

  • find brightest spot (Example: 100)
  • divide by 2 (100/2 = 50)
  • define a band ...

99. How to find out if a sentence is a question (interrogative)?

Is there an open source Java library/algorithm for finding if a particular piece of text is a question or not?
I am working on a question answering system that needs to analyze ...

100. Which is faster obj instanceof class or obj.booleanAnyMethod()

I was asked this in an interview. Not counting the time it takes to execute the method body. Any ideas?  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.