– Array Solutions

3 Array Solutions

3.1 Print Array

Write a method that prints out a string array, one element per line

3.1.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        printArray(breakfast);
        //Alternative Method
        printArrayAlt(breakfast);
    }
    void printArray(String [] array)
    {
        for(int i = 0; i<array.length; i++)
        {
            System.out.println(array[i]);
        }
    }
    //Alternative method using for each loop
    void printArrayAlt(String [] array)
    {
        for(String s: array)
        {
            System.out.println(s);
        }
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.2 Last Element of Array

Write a method that returns the last element of a string array

3.2.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
      System.out.println(lastElement(breakfast));
    }
    String lastElement(String [] array)
    {
        return array[array.length-1];
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.3 Last But One Element of Array

Write a method that returns the last but one element of a string array

3.3.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        //Added two extra arrays for testing
        String [] coin = {"Heads", "Tails"};
        String [] lonely = {"solo"};
        System.out.println(lastButOne(breakfast));
        System.out.println(lastButOneSafer(breakfast));
        System.out.println(lastButOneSafer(coin));
        System.out.println(lastButOneSafer(lonely));
    }
    String lastButOne(String [] array)
    {
        return array[array.length-2];
    }
    // The previous method will throw an
    // arrayIndexOutOfBoundsException for arrays of length <2.
    // This method will return an empty string if length <2
    String lastButOneSafer(String [] array)
    {
        if (array.length<2)
        {
            return "";
        }
        else
        {
            return array[array.length-2];
        }
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.4 Reverse an Array

Write a method that returns elements of an Array in reverse order

3.4.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        //Added two extra arrays for testing
        String [] coin = {"Heads", "Tails"};
        String [] lonely = {"solo"};
        printArray(reverse(breakfast));
        printArray(reverse(coin));
        printArray(reverse(lonely));
    }
    void printArray(String [] array)
    {
        for(int i = 0; i<array.length; i++)
        {
            System.out.println(array[i]);
        }
    }
    String [] reverse(String [] array)
    {
        for(int i = 0; i<array.length/2;i++)
        {
            String temp = array[i];
            array[i] = array[array.length-i-1];
            array[array.length-i-1] = temp;
        }
        return array;
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.5 Palindromic Arrays

Write a method that tests to see if an array is palindromic, i.e. the elements are the same when reversed.

3.5.1 Solution

    public class NNArrays {
    NNArrays()
    {
        String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
        String [] lonely = {"solo"};
        String [] palindromic = {"Sausage", "Eggs", "Beans",
                                 "Beans", "Eggs", "Sausage"};
        System.out.println(isPalindrome(palindromic));
        System.out.println(isPalindrome(breakfast));
        System.out.println(isPalindrome(lonely));
    }
    boolean isPalindrome(String [] array)
    {
        boolean isPal = true;
        for (int i = 0; i<array.length/2; i++)
        {
            if (!array[i].equals(array[array.length -i -1]))
                isPal = false;
        }
        return isPal;
    }
    // The following method doesn't work.
    // Need to compare individual elements
    boolean isPalindromeWrong(String [] array)
    {
        if (array.equals(reverse(array)))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    String [] reverse(String [] array)
    {
        for(int i = 0; i<array.length/2;i++)
        {
            String temp = array[i];
            array[i] = array[array.length-i-1];
            array[array.length-i-1] = temp;
        }
        return array;
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.6 Consecutive Duplicates

Write a method to print out an int array with consecutive duplicates eliminated

3.6.1 Solution

    public class NNArrays {
    NNArrays()
    {
        int [] nums = {1,1,3,3,3,2,2,2,1,1,1,1,4,4,4,4};
        int [] num2 = {1,1};
        int [] num1 = {1};
        compress(nums);
        compress(num2);
        compress(num1);
    }
    void compress(int [] array)
    {
        System.out.println(array[0]);
        for (int i = 1; i<array.length; i++)
        {
            if (array[i]!=array[i-1])
            {
                System.out.println(array[i]);
            }
        }
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3.7 Pack Duplicates

Pack consecutive duplicates of a char array into Strings

3.7.1 Solution

    public class NNArrays {
    NNArrays()
    {
        char [] letters = {'a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'};
        pack(letters);
    }
    void pack(char [] array)
    {
        String s = Character.toString(array[0]);
        for(int i = 1; i<array.length; i++)
        {
            if(array[i] != array [i-1])
            {
                System.out.print(s+ ", ");
                s = Character.toString(array[i]);
            }
            else
            {
                s = s + array[i];
            }
        }
        System.out.println(s);
    }
    public static void main(String[] args)
    {
        new NNArrays();
    }
}

3: Arrays

3.1 Print Array

Write a method that prints out a string array, one element per line

3.1.1 Example

 1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
 2:
 3:  printArray(breakfast)
 4:   *** Output ***
 5:  Sausage
 6:  Eggs
 7:  Beans
 8:  Bacon
 9:  Tomatoes
10:  Mushrooms

3.2 Last Element of Array

Write a method that returns the last element of a string array

3.2.1 Example

1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"}
2:
3:  System.out.println(lastElement(breakfast));
4:   *** Output ***
5:  Mushrooms

3.3 Last But One Element of Array

Write a method that returns the last but one element of a string array

3.3.1 Example

1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"}
2:
3:  System.out.println(lastButOne(breakfast));
4:   *** Output ***
5:  Tomatoes

3.4 Reverse an Array

Write a method that reverses the elements of an Array

3.4.1 Example

 1:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"};
 2:
 3:  System.out.println(reverse(breakfast));
 4:   *** Output ***
 5:  : Mushrooms
 6:  : Tomatoes
 7:  : Bacon
 8:  : Beans
 9:  : Eggs
10:  : Sausage
11:  : Tails

3.5 Palindromic Arrays

Write a method that tests to see if an array is palindromic, i.e. the elements are the same when reversed.

3.5.1 Example

1:  String [] palindromic = {"Sausage", "Eggs", "Beans", "Beans", "Eggs", "Sausage"};
2:  String [] breakfast = {"Sausage", "Eggs", "Beans", "Bacon", "Tomatoes", "Mushrooms"}
3:
4:  System.out.println(isPalindrome(palindromic));
5:  System.out.println(isPalindrome(breakfast));
6:   *** Output ***
7:  True
8:  False

3.6 Consecutive Duplicates

Write a method to print out an int array with consecutive duplicates eliminated

 1:  int [] nums = {1,1,3,3,3,2,2,2,1,1,1,1,4,4,4,4};
 2:
 3:  compress(nums)
 4:   *** Output ***
 5:  : 1
 6:  : 3
 7:  : 2
 8:  : 1
 9:  : 4
10:  : 1
11:  : 1
12:

3.7 Pack Duplicates

Pack consecutive duplicates of a char array into Strings

1:  char [] letters = {'a' 'a' 'a' 'a' 'b' 'c' 'c' 'a' 'a' 'd' 'e' 'e' 'e' 'e'};
2:
3:  pack(nums)
4:   *** Output ***
5:  : aaaa, b, cc, aa, d, eeee
6:

– Loop Solutions

1:  package nnloops;
  2:
  3:  import java.util.Scanner;
  4:
  5:  public class NNLoops {
  6:
  7:      NNLoops()
  8:      {
  9:          //oneToTen();
 10:          //oddNumbers();
 11:          //squareNumbers();
 12:          //random4();
 13:          //even(20);
 14:          //powers(8);
 15:          //areWeThereYet();
 16:          //triangle();
 17:          //tableSquare();
 18:          tableSquares(6);
 19:
 20:      }
 21:
 22:      void oneToTen()
 23:      {
 24:          for(int i=1; i <11; i++)
 25:          {
 26:              System.out.println(i);
 27:          }
 28:      }
 29:
 30:      void oddNumbers()
 31:      {
 32:          for (int i=1; i<20; i+=2)
 33:          {
 34:              System.out.println(i);
 35:          }
 36:      }
 37:
 38:      void squareNumbers()
 39:      {
 40:          for (int i=1; i<11; i++)
 41:          {
 42:              System.out.println(i*i);
 43:          }
 44:      }
 45:
 46:      void random4()
 47:      {
 48:          for (int i=0; i<4; i++)
 49:          {
 50:              System.out.println((int)(Math.random()*10)+1);
 51:          }
 52:      }
 53:
 54:      void even(int n)
 55:      {
 56:          for (int i=1; i<n; i+=2)
 57:          {
 58:              System.out.println(i);
 59:          }
 60:      }
 61:
 62:      void powers (int n)
 63:      {
 64:          for (int i =1; i<=n; i++)
 65:          {
 66:              System.out.println(Math.pow(2, i));
 67:          }
 68:      }
 69:
 70:      void areWeThereYet()
 71:      {
 72:          Scanner scan = new Scanner(System.in);
 73:          do
 74:          {
 75:              System.out.println("Are we there yet?");
 76:          } while(!scan.nextLine().equals("Yes"));
 77:          System.out.println("Good!");
 78:      }
 79:
 80:      void triangle()
 81:      {
 82:          for(int i = 0; i<6; i++)
 83:          {
 84:              for (int j= 0; j<i; j++)
 85:              {
 86:                  System.out.print("*");
 87:              }
 88:              System.out.println("");
 89:          }
 90:      }
 91:
 92:      void tableSquare()
 93:      {
 94:          for(int i = 1; i<=4; i++)
 95:          {
 96:              for (int j=1; j<=4; j++)
 97:              {
 98:                  System.out.print("|"+ i*j +"\t");
 99:              }
100:              System.out.println("|");
101:
102:          }
103:      }
104:
105:      void tableSquares(int n)
106:      {
107:          for(int i = 1; i<=n; i++)
108:          {
109:              for (int j=1; j<=n; j++)
110:              {
111:                  System.out.print("|"+ i*j +"\t");
112:              }
113:              System.out.println("|");
114:
115:          }
116:      }
117:
118:
119:      public static void main(String[] args) {
120:         new NNLoops();
121:      }
122:  }

2: Loops

2.1 1 to 10

Write a method that prints the numbers 1 to 10

2.1.1 Example

 1:  oneToTen()
 2:   *** Output ***
 3:  1
 4:  2
 5:  3
 6:  4
 7:  5
 8:  6
 9:  7
10:  8
11:  9
12:  10

2.2 Odd Numbers

Write a method that prints the positive odd numbers less than 20

2.2.1 Example

 1:  oddNumbers()
 2:   *** Output ***
 3:  1
 4:  3
 5:  5
 6:  7
 7:  9
 8:  11
 9:  13
10:  15
11:  17
12:  19

2.3 Square Numbers

Write a method that prints the square numbers up to 100

2.3.1 Example

 1:  squares()
 2:   *** Output ***
 3:  1
 4:  4
 5:  9
 6:  16
 7:  25
 8:  36
 9:  49
10:  64
11:  81
12:  100

2.4 Random Numbers

Write a for loop to print out four random integers between 1 and 10

2.4.1 Example

1:  random4()
2:   *** Output ***
3:  3
4:  5
5:  2
6:  8

2.5 Even Numbers < n

Write a method to print out the positive even numbers less than n

2.5.1 Example

 1:  even(20)
 2:   *** Output ***
 3:  2
 4:  4
 5:  6
 6:  8
 7:  10
 8:  12
 9:  14
10:  16
11:  18

2.6 Powers of 2

Write a method to print out the powers of 2 from 21 up to 2n

2.6.1 Example

 1:  powers(8)
 2:   *** Output ***
 3:  2
 4:  4
 5:  8
 6:  16
 7:  32
 8:  64
 9:  128
10:  256

2.7 Are we there yet?

Write a program that outputs “Are we there yet?” and then waits for input. If the input is “Yes” the program outputs “Good!” and exits, otherwise the program loops.

2.7.1 Example

1:  "Are we there yet?"
2:  No
3:  "Are we there yet?"
4:  Spoons
5:  "Are we there yet?"
6:  Yes
7:  Good!

2.8 Triangle

Write a method that uses nested loops to produce the following pattern

1:  triangle()
2:   *** Output ***
3:  *
4:  **
5:  ***
6:  ****
7:  *****

2.9 Table Square

Write a method that prints out a 4 x 4 table square

2.9.1 Example

1:  tableSquare()
2:   *** Output ***
3:  A 4 x 4 table square
4:  | 1 | 2 |  3 |  4 |
5:  | 1 | 2 |  3 |  4 |
6:  | 2 | 4 |  6 |  8 |
7:  | 3 | 6 |  9 | 12 |
8:  | 4 | 8 | 12 | 16 |

2.10 Table Squares

Extend your answer to the last question produce a method that will print out a n x n table square

2.10.1 Example

 1:  tableSquares(6)
 2:   *** Output ***
 3:  A 6 x 6 table square
 4:  | 1 |  2 |  3 |  4 |  5 |  6 |
 5:  | 2 |  4 |  6 |  8 | 10 | 12 |
 6:  | 3 |  6 |  9 | 12 | 15 | 18 |
 7:  | 4 |  8 | 12 | 16 | 20 | 24 |
 8:  | 5 | 10 | 15 | 20 | 25 | 30 |
 9:  | 6 | 12 | 18 | 24 | 30 | 36 |

1: How to Answer These Questions

Write methods to solve all of the questions. Here are two example questions and their solutions. Notice that the first method prints a value, the second method returns a value.

1.1 Hello <Name>

Write a method that accepts a name as a parameter and prints out “Hello ” <name>

1.1.1 Example

1:  hello("Kim")
2:   *** Output ***
3:  Hello Kim

1.2 Average of two numbers

Write a method that accepts two numbers and returns the average of the two numbers.

1.2.1 Example

1:  System.out.println(average(3,4));
2:   *** Output ***
3:  3.5

1.3 Solutions

 1:  public class NinetyNine {
 2:
 3:      NinetyNine()
 4:      {
 5:          hello("Kim");
 6:          System.out.println(average(3,4));
 7:      }
 8:
 9:      void hello(String s)
10:      {
11:          System.out.println("Hello " + s);
12:      }
13:
14:      double average(double x, double y)
15:      {
16:          return (x+y)/2;
17:      }
18:
19:      public static void main(String[] args)
20:      {
21:          new NinetyNine();
22:      }
23:  }
24:

Installing Ubuntu alongside Windows 8 on a UEFI System

Gone are the days when Ubuntu installed without a hitch. Now there’s UEFI and Windows 8 to contend with. The Ubuntu site has this advice: https://help.ubuntu.com/community/UEFI.  Here’s some advice based on my experience of installing Ubuntu on three separate machines over the past week.

1 Installing Ubuntu

  1. Put the iso on a pendrive/DVD in the usual way
  2. Turn on the machine and hit the key to bring up the boot options
  3. Change the settings so the machine will boot from USB first (naturally)
  4. If it’s UEFI, make sure secure boot is disabled and legacy boot is enabled
  5. Insert the pen drive and boot up. Ubuntu should boot in the usual way from the pen drive. It will then install with no problems (so far, at least.)

2 Troubleshooting

2.1 Machine won’t boot from USB/CD

This seems to be a Windows 8 feature. You need to boot up Windows 8 and do an advanced restart as follows:

  1. In Windows 8 goto PC Settings -> General -> Advanced startup.
  2. Choose Advanced Options -> Startup Settings

The machine will reboot and should hopefully find your USB/CD

2.2 Install Ubuntu alongside Windows option is missing from the install options dialog

Again, you have to boot into Windows 8 and then use the Windows disk partition manager to make a suitable partition. The Linux Partition manger doesn’t seem to work anymore

2.3 Ubuntu is installed, but machine still boots to Windows

Easy! I don’t think so. Not only have Microsoft ruined their own perfectly good desktop with Windows 8, they seem to be doing a pretty good job of ruining the ease of installation for other operating systems. I wish they’d get a grip.

Searching

See the aardvark, a few lines down? It’s worth remembering that it’s often faster get to it by using C-s to search than by moving the cursor. Emacs expects you to search frequently, that’s why searching takes less key presses than C-x s, the save command.

Here’s a reminder of the search commands:

C-s C-w         Search for word after point
C-s C-s         Repeat last search
C-s C-y         Search line
C-s M-y         Search last kill
C-u C-s         Regexp Search
C-u C-r         Regexp Reverse Search

Emacs incremental search can occasionally be a pain. Don’t forget you can search non-incrementally for a specific word such as elephant using

M-s w <RET> elephant <RET>

Here’s the aardvark, by the way.

Date and Time

1 Reading Date and Time

This is how elisp stores a time:

(current-time) => (21209 38073 267139)

The first two numbers are the high and low bits of an integer number giving seconds since the epoch (0:00 January 1, 1970 UTC). The last number is microseconds and may be ommitted. There may be a fourth number representing picoseconds.
decode-time puts this into a more user friendly format:

(decode-time (current-time)) => (30 38 20 17 1 2014 5 nil 0)

The individual values are (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE) DOW is DOW of week DST is t if Daylight saving time is in effect ZONE is an integer indicating the number of seconds east of Greenwich.
format-time-string gives a more everyday format:

(format-time-string "%d/%m/%Y %H:%M:%S" (current-time)) => "17/01/2014 20:38:43"

Or, if you’re really in a hurry:

(current-time-string) => "Fri Jan 17 20:38:54 2014"

2 Setting a Date or Time

Set a time using date-to-time

(date-to-time "May 20 2011 19:30:00") => (19926 45864)

Note that the date strings format is dependent on your machine’s locale settings. For example, the following may be necessary. For more about locales, read this post.

(date-to-time "20 May 2011 19:30:00")

Enter a date using parse-time-string

(setq concert (parse-time-string "May 20 2011 19:30:00")) => (0 30 19 20 5 2011 nil nil nil)

Unlike date-to-time, parse-time-string allows you to omit the time value :

(setq birthday (parse-time-string "July 29 1953")) => (nil nil nil 29 7 1953 nil nil nil)

Here are some times:

(setq five-seconds (seconds-to-time 5))
(setq ninety-minutes (seconds-to-time (* 60 90)))
(setq one-day (seconds-to-time (* 60 60 24)))

The last can be more easily entered as:

(setq one-day (days-to-time 1))

Which leads to

(setq one-week (days-to-time 7))

and so on…

3 Converting Time Values

Use encode-time and decode-time to switch between formats

(encode-time 0 30 19 20 5 2011) => (19926 45864)
(decode-time '(19926  45864)) => (0 30 19 20 5 2011 5 t 3600)

4 Calculations on Dates and Times

Use time-add to add two times together.
Here’s the time a concert starts

(setq concert (date-to-time "May 20 2011 19:30:00"))

Suppose the concert lasts two hours (or 2 x 60 x 60 seconds). You can work out the time the concert ends as follows

(time-add concert (seconds-to-time (* 2 60 60)))

Let’s just check that worked

(format-time-string "%d/%m/%Y %H:%M:%S" (time-add concert (seconds-to-time (* 2 60 60)))) => "20/05/2011 21:30:00"

Suppose you know the start and end times of the concert. Use time-subtract to work out the duration:

(setq concert-start (date-to-time "May 20 2011 19:30:00"))
(setq concert-end (date-to-time "May 20 2011 22:25:00"))
(format-time-string "%H:%M:%S"(time-subtract concert-end concert-start)) => "02:55:00"

See Also

My Emacs Writing Setup

Due to the interest in my post on Writing Tools, I’ve published an HTML document on my Emacs writing setup.

If you want to know how I plan and plot stories, you may find the document interesting.  You’ll probably find it more interesting if you use Emacs yourself.

A Note on Emacs

I think of Emacs as a text editors’ tool. As I spend most of my life working with text, either programming or writing, I want to do it as efficiently as possible.
It first struck me when I was editing my novel Divergence just how inefficient I was being in pressing the arrow key and waiting for the cursor to get to where I wanted. That got me thinking about the time spent deleting text, transposing words, moving around paragraphs… I realised there must be a quicker way.
And then I remembered Emacs.

It makes sense for someone who spends most of their time manipulating text to learn a group of obscure key combinations. It saves time and increases productivity. Learning to use Emacs properly reminds me of playing Jazz on the piano. I’ve learnt all those chords and runs and fills so that I can use them without thinking when I’m improvising. Likewise, I’ve practised using Emacs key strokes such as M-f, M–M-c and C-M-<Space> so often I use them without thinking when editing. I rely on M-/ to complete words, and I can’t do without M-h and C-e to select and move around text.

I practice using Emacs because it makes me a more productive writer. If you’re interested, I’ve written up some of those tips and exercises on my Emacs Workout.