Download code

Jump to: navigation, search

Back to Look_and_say_sequence_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

LookAndSaySequence.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Look_and_say_sequence_(Java)?oldid=12074
14 */
15 
16 import java.util.Arrays;
17 
18 public class LookAndSaySequence
19 {
20     public static String[] look_and_say(String seed, int len)
21     {
22         String[] seq = new String[len];
23         seq[0] = seed;
24 
25         for (int i = 1; i < len; i++) {
26             String val = seq[i-1];
27 
28             StringBuilder nextval = new StringBuilder();
29             for (int ix = 0; ix < val.length(); ) {
30                 char ch = val.charAt(ix);
31                 int n;
32                 for (n = 1; ++ix < val.length() && val.charAt(ix)==ch; n++)
33                     ;
34                 nextval.append(n).append(ch);
35             }
36             seq[i] = nextval.toString();
37         }
38 
39         return seq;
40     }
41 
42     public static void main(String[] args)
43     {
44         String[] seq = look_and_say("3", 10);
45         System.out.println(Arrays.toString(seq));
46     }
47 }
48 


hijacker
hijacker
hijacker
hijacker