title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Word ladder | Go from Wren | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
| package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func contains(a []string, s string) bool {
for _, e := range a {
if e == s {
return true
}
}
return false
}
func oneAway(a, b string) bool {
sum := 0
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
sum++
}
}
return sum == 1
}
func wordLadder(words []string, a, b string) {
l := len(a)
var poss []string
for _, word := range words {
if len(word) == l {
poss = append(poss, word)
}
}
todo := [][]string{{a}}
for len(todo) > 0 {
curr := todo[0]
todo = todo[1:]
var next []string
for _, word := range poss {
if oneAway(word, curr[len(curr)-1]) {
next = append(next, word)
}
}
if contains(next, b) {
curr = append(curr, b)
fmt.Println(strings.Join(curr, " -> "))
return
}
for i := len(poss) - 1; i >= 0; i-- {
if contains(next, poss[i]) {
copy(poss[i:], poss[i+1:])
poss[len(poss)-1] = ""
poss = poss[:len(poss)-1]
}
}
for _, s := range next {
temp := make([]string, len(curr))
copy(temp, curr)
temp = append(temp, s)
todo = append(todo, temp)
}
}
fmt.Println(a, "into", b, "cannot be done.")
}
func main() {
b, err := ioutil.ReadFile("unixdict.txt")
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))
for i, bword := range bwords {
words[i] = string(bword)
}
pairs := [][]string{
{"boy", "man"},
{"girl", "lady"},
{"john", "jane"},
{"child", "adult"},
}
for _, pair := range pairs {
wordLadder(words, pair[0], pair[1])
}
} |
Word search | Go from Java | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
;Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
;Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
| package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"regexp"
"strings"
"time"
)
var dirs = [][]int{{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}
const (
nRows = 10
nCols = nRows
gridSize = nRows * nCols
minWords = 25
)
var (
re1 = regexp.MustCompile(fmt.Sprintf("^[a-z]{3,%d}$", nRows))
re2 = regexp.MustCompile("[^A-Z]")
)
type grid struct {
numAttempts int
cells [nRows][nCols]byte
solutions []string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
word := strings.ToLower(strings.TrimSpace(scanner.Text()))
if re1.MatchString(word) {
words = append(words, word)
}
}
check(scanner.Err())
return words
}
func createWordSearch(words []string) *grid {
var gr *grid
outer:
for i := 1; i < 100; i++ {
gr = new(grid)
messageLen := gr.placeMessage("Rosetta Code")
target := gridSize - messageLen
cellsFilled := 0
rand.Shuffle(len(words), func(i, j int) {
words[i], words[j] = words[j], words[i]
})
for _, word := range words {
cellsFilled += gr.tryPlaceWord(word)
if cellsFilled == target {
if len(gr.solutions) >= minWords {
gr.numAttempts = i
break outer
} else { // grid is full but we didn't pack enough words, start over
break
}
}
}
}
return gr
}
func (gr *grid) placeMessage(msg string) int {
msg = strings.ToUpper(msg)
msg = re2.ReplaceAllLiteralString(msg, "")
messageLen := len(msg)
if messageLen > 0 && messageLen < gridSize {
gapSize := gridSize / messageLen
for i := 0; i < messageLen; i++ {
pos := i*gapSize + rand.Intn(gapSize)
gr.cells[pos/nCols][pos%nCols] = msg[i]
}
return messageLen
}
return 0
}
func (gr *grid) tryPlaceWord(word string) int {
randDir := rand.Intn(len(dirs))
randPos := rand.Intn(gridSize)
for dir := 0; dir < len(dirs); dir++ {
dir = (dir + randDir) % len(dirs)
for pos := 0; pos < gridSize; pos++ {
pos = (pos + randPos) % gridSize
lettersPlaced := gr.tryLocation(word, dir, pos)
if lettersPlaced > 0 {
return lettersPlaced
}
}
}
return 0
}
func (gr *grid) tryLocation(word string, dir, pos int) int {
r := pos / nCols
c := pos % nCols
le := len(word)
// check bounds
if (dirs[dir][0] == 1 && (le+c) > nCols) ||
(dirs[dir][0] == -1 && (le-1) > c) ||
(dirs[dir][1] == 1 && (le+r) > nRows) ||
(dirs[dir][1] == -1 && (le-1) > r) {
return 0
}
overlaps := 0
// check cells
rr := r
cc := c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] != 0 && gr.cells[rr][cc] != word[i] {
return 0
}
cc += dirs[dir][0]
rr += dirs[dir][1]
}
// place
rr = r
cc = c
for i := 0; i < le; i++ {
if gr.cells[rr][cc] == word[i] {
overlaps++
} else {
gr.cells[rr][cc] = word[i]
}
if i < le-1 {
cc += dirs[dir][0]
rr += dirs[dir][1]
}
}
lettersPlaced := le - overlaps
if lettersPlaced > 0 {
sol := fmt.Sprintf("%-10s (%d,%d)(%d,%d)", word, c, r, cc, rr)
gr.solutions = append(gr.solutions, sol)
}
return lettersPlaced
}
func printResult(gr *grid) {
if gr.numAttempts == 0 {
fmt.Println("No grid to display")
return
}
size := len(gr.solutions)
fmt.Println("Attempts:", gr.numAttempts)
fmt.Println("Number of words:", size)
fmt.Println("\n 0 1 2 3 4 5 6 7 8 9")
for r := 0; r < nRows; r++ {
fmt.Printf("\n%d ", r)
for c := 0; c < nCols; c++ {
fmt.Printf(" %c ", gr.cells[r][c])
}
}
fmt.Println("\n")
for i := 0; i < size-1; i += 2 {
fmt.Printf("%s %s\n", gr.solutions[i], gr.solutions[i+1])
}
if size%2 == 1 {
fmt.Println(gr.solutions[size-1])
}
}
func main() {
rand.Seed(time.Now().UnixNano())
unixDictPath := "/usr/share/dict/words"
printResult(createWordSearch(readWords(unixDictPath)))
} |
Word wrap | Go | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
;Basic task:
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
;Extra credit:
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
| package main
import (
"fmt"
"strings"
)
func wrap(text string, lineWidth int) (wrapped string) {
words := strings.Fields(text)
if len(words) == 0 {
return
}
wrapped = words[0]
spaceLeft := lineWidth - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + word
spaceLeft = lineWidth - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return
}
var frog = `
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face. Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.`
func main() {
fmt.Println("wrapped at 80:")
fmt.Println(wrap(frog, 80))
fmt.Println("wrapped at 72:")
fmt.Println(wrap(frog, 72))
} |
World Cup group stage | Go from Kotlin | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
:::* A win is worth three points.
:::* A draw/tie is worth one point.
:::* A loss is worth zero points.
;Task:
:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
:* Calculate the standings points for each team with each combination of outcomes.
:* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''
| package main
import (
"fmt"
"sort"
"strconv"
)
var games = [6]string{"12", "13", "14", "23", "24", "34"}
var results = "000000"
func nextResult() bool {
if results == "222222" {
return false
}
res, _ := strconv.ParseUint(results, 3, 32)
results = fmt.Sprintf("%06s", strconv.FormatUint(res+1, 3))
return true
}
func main() {
var points [4][10]int
for {
var records [4]int
for i := 0; i < len(games); i++ {
switch results[i] {
case '2':
records[games[i][0]-'1'] += 3
case '1':
records[games[i][0]-'1']++
records[games[i][1]-'1']++
case '0':
records[games[i][1]-'1'] += 3
}
}
sort.Ints(records[:])
for i := 0; i < 4; i++ {
points[i][records[i]]++
}
if !nextResult() {
break
}
}
fmt.Println("POINTS 0 1 2 3 4 5 6 7 8 9")
fmt.Println("-------------------------------------------------------------")
places := [4]string{"1st", "2nd", "3rd", "4th"}
for i := 0; i < 4; i++ {
fmt.Print(places[i], " place ")
for j := 0; j < 10; j++ {
fmt.Printf("%-5d", points[3-i][j])
}
fmt.Println()
}
} |
Write float arrays to a text file | Go | Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
| package main
import (
"fmt"
"os"
)
var (
x = []float64{1, 2, 3, 1e11}
y = []float64{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
xprecision = 3
yprecision = 5
)
func main() {
if len(x) != len(y) {
fmt.Println("x, y different length")
return
}
f, err := os.Create("filename")
if err != nil {
fmt.Println(err)
return
}
for i := range x {
fmt.Fprintf(f, "%.*e, %.*e\n", xprecision-1, x[i], yprecision-1, y[i])
}
f.Close()
} |
Write language name in 3D ASCII | Go | Write/display a language's name in '''3D''' ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
;Related tasks:
* draw a sphere
* draw a cuboid
* draw a rotating cube
* draw a Deathstar
| package main
import (
"fmt"
"strings"
)
var lean = font{
height: 5,
slant: 1,
spacing: 2,
m: map[rune][]string{
'G': []string{
` _/_/_/`,
`_/ `,
`_/ _/_/`,
`_/ _/`,
` _/_/_/`,
},
'o': []string{
` `,
` _/_/ `,
`_/ _/`,
`_/ _/`,
` _/_/ `,
},
}}
var smallKeyboard = font{
height: 4,
slant: 0,
spacing: -1,
m: map[rune][]string{
'G': []string{
` ____ `,
`||G ||`,
`||__||`,
`|/__\|`,
},
'o': []string{
` ____ `,
`||o ||`,
`||__||`,
`|/__\|`,
},
}}
type font struct {
height int
slant int
spacing int
m map[rune][]string
}
func render(s string, f font) string {
rows := make([]string, f.height)
if f.slant != 0 {
start := 0
if f.slant > 0 {
start = f.height
}
for i := range rows {
rows[i] = strings.Repeat(" ", (start-i)*f.slant)
}
}
if f.spacing >= 0 {
spacing := strings.Repeat(" ", f.spacing)
for j, c := range s {
for i, r := range f.m[c] {
if j > 0 {
r = spacing + r
}
rows[i] += r
}
}
} else {
overlap := -f.spacing
for j, c := range s {
for i, r := range f.m[c] {
if j > 0 {
r = r[overlap:]
}
rows[i] += r
}
}
}
return strings.Join(rows, "\n")
}
func main() {
fmt.Println(render("Go", lean))
fmt.Println(render("Go", smallKeyboard))
} |
Write to Windows event log | Go | Write script status to the Windows Event Log
| package main
import (
"fmt"
"os/exec"
)
func main() {
command := "EventCreate"
args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
"/SO", "Go", "/D", "\"Rosetta Code Example\""}
cmd := exec.Command(command, args...)
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
} |
Yellowstone sequence | Go | The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
;Example:
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
;Task
: Find and show as output the first '''30''' Yellowstone numbers.
;Extra
: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
;Related tasks:
:* Greatest common divisor.
:* Plot coordinate pairs.
;See also:
:* The OEIS entry: A098550 The Yellowstone permutation.
:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].
| package main
import (
"fmt"
"log"
"os/exec"
)
func gcd(x, y int) int {
for y != 0 {
x, y = y, x%y
}
return x
}
func yellowstone(n int) []int {
m := make(map[int]bool)
a := make([]int, n+1)
for i := 1; i < 4; i++ {
a[i] = i
m[i] = true
}
min := 4
for c := 4; c <= n; c++ {
for i := min; ; i++ {
if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
a[c] = i
m[i] = true
if i == min {
min++
}
break
}
}
}
return a[1:]
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
x := make([]int, 100)
for i := 0; i < 100; i++ {
x[i] = i + 1
}
y := yellowstone(100)
fmt.Println("The first 30 Yellowstone numbers are:")
fmt.Println(y[:30])
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
check(err)
check(g.Start())
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %d\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
} |
Zeckendorf number representation | Go | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.
;Task:
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
;Also see:
* OEIS A014417 for the the sequence of required results.
* Brown's Criterion - Numberphile
;Related task:
* [[Fibonacci sequence]]
| package main
import "fmt"
func main() {
for i := 0; i <= 20; i++ {
fmt.Printf("%2d %7b\n", i, zeckendorf(i))
}
}
func zeckendorf(n int) int {
// initial arguments of fib0 = 1 and fib1 = 1 will produce
// the Fibonacci sequence {1, 2, 3,..} on the stack as successive
// values of fib1.
_, set := zr(1, 1, n, 0)
return set
}
func zr(fib0, fib1, n int, bit uint) (remaining, set int) {
if fib1 > n {
return n, 0
}
// recurse.
// construct sequence on the way in, construct ZR on the way out.
remaining, set = zr(fib1, fib0+fib1, n, bit+1)
if fib1 <= remaining {
set |= 1 << bit
remaining -= fib1
}
return
} |
Zero to the zero power | Go | Some computer programming languages are not exactly consistent (with other computer programming languages)
when ''raising zero to the zeroth power'': 00
;Task:
Show the results of raising zero to the zeroth power.
If your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
'''Show the result here.'''
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
;See also:
* The Wiki entry: Zero to the power of zero.
* The Wiki entry: Zero to the power of zero: History.
* The MathWorld(tm) entry: exponent laws.
** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1.
* The OEIS entry: The special case of zero to the zeroth power
| package main
import (
"fmt"
"math"
"math/big"
"math/cmplx"
)
func main() {
fmt.Println("float64: ", math.Pow(0, 0))
var b big.Int
fmt.Println("big integer:", b.Exp(&b, &b, nil))
fmt.Println("complex: ", cmplx.Pow(0, 0))
} |
Zhang-Suen thinning algorithm | Go | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
;Algorithm:
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
;Step 1:
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and P6 is white
* (4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
;Step 2:
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and '''P8''' is white
* (4) At least one of '''P2''' and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
;Iteration:
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
;Task:
# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
;Reference:
* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
* "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000`
func main() {
b := wbFromString(in, '1')
b.zhangSuen()
fmt.Println(b)
}
const (
white = 0
black = 1
)
type wbArray [][]byte // elements are white or black.
// parameter blk is character to read as black. otherwise kinda rigid,
// expects ascii, leading newline, no trailing newline,
// takes color from low bit of character.
func wbFromString(s string, blk byte) wbArray {
lines := strings.Split(s, "\n")[1:]
b := make(wbArray, len(lines))
for i, sl := range lines {
bl := make([]byte, len(sl))
for j := 0; j < len(sl); j++ {
bl[j] = sl[j] & 1
}
b[i] = bl
}
return b
}
// rigid again, hard coded to output space for white, # for black,
// no leading or trailing newline.
var sym = [2]byte{
white: ' ',
black: '#',
}
func (b wbArray) String() string {
b2 := bytes.Join(b, []byte{'\n'})
for i, b1 := range b2 {
if b1 > 1 {
continue
}
b2[i] = sym[b1]
}
return string(b2)
}
// neighbor offsets
var nb = [...][2]int{
2: {-1, 0}, // p2 offsets
3: {-1, 1}, // ...
4: {0, 1},
5: {1, 1},
6: {1, 0},
7: {1, -1},
8: {0, -1},
9: {-1, -1}, // p9 offsets
}
func (b wbArray) reset(en []int) (rs bool) {
var r, c int
var p [10]byte
readP := func() {
for nx := 1; nx <= 9; nx++ {
n := nb[nx]
p[nx] = b[r+n[0]][c+n[1]]
}
}
shiftRead := func() {
n := nb[3]
p[9], p[2], p[3] = p[2], p[3], b[r+n[0]][c+n[1]]
n = nb[4]
p[8], p[1], p[4] = p[1], p[4], b[r+n[0]][c+n[1]]
n = nb[5]
p[7], p[6], p[5] = p[6], p[5], b[r+n[0]][c+n[1]]
}
// returns "A", count of white->black transitions in circuit of neighbors
// of an interior pixel b[r][c]
countA := func() (ct byte) {
bit := p[9]
for nx := 2; nx <= 9; nx++ {
last := bit
bit = p[nx]
if last == white {
ct += bit
}
}
return ct
}
// returns "B", count of black pixels neighboring interior pixel b[r][c].
countB := func() (ct byte) {
for nx := 2; nx <= 9; nx++ {
ct += p[nx]
}
return ct
}
lastRow := len(b) - 1
lastCol := len(b[0]) - 1
mark := make([][]bool, lastRow)
for r = range mark {
mark[r] = make([]bool, lastCol)
}
for r = 1; r < lastRow; r++ {
c = 1
readP()
for { // column loop
m := false
// test for failure of any of the five conditions,
if !(p[1] == black) {
goto markDone
}
if b1 := countB(); !(2 <= b1 && b1 <= 6) {
goto markDone
}
if !(countA() == 1) {
goto markDone
}
{
e1, e2 := p[en[1]], p[en[2]]
if !(p[en[0]]&e1&e2 == 0) {
goto markDone
}
if !(e1&e2&p[en[3]] == 0) {
goto markDone
}
}
// no conditions failed, mark this pixel for reset
m = true
rs = true // and mark that image changes
markDone:
mark[r][c] = m
c++
if c == lastCol {
break
}
shiftRead()
}
}
if rs {
for r = 1; r < lastRow; r++ {
for c = 1; c < lastCol; c++ {
if mark[r][c] {
b[r][c] = white
}
}
}
}
return rs
}
var step1 = []int{2, 4, 6, 8}
var step2 = []int{4, 2, 8, 6}
func (b wbArray) zhangSuen() {
for {
rs1 := b.reset(step1)
rs2 := b.reset(step2)
if !rs1 && !rs2 {
break
}
}
} |
100 doors | Java | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
;Task:
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
'''Alternate:'''
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| class HundredDoors {
public static void main(String[] args) {
boolean[] doors = new boolean[101];
for (int i = 1; i < doors.length; i++) {
for (int j = i; j < doors.length; j += i) {
doors[j] = !doors[j];
}
}
for (int i = 1; i < doors.length; i++) {
if (doors[i]) {
System.out.printf("Door %d is open.%n", i);
}
}
}
} |
100 prisoners | Java from Kotlin | The Problem:
* 100 prisoners are individually numbered 1 to 100
* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
* Prisoners start outside the room
:* They can decide some strategy before any enter the room.
:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
:* A prisoner can open no more than 50 drawers.
:* A prisoner tries to find his own number.
:* A prisoner finding his own number is then held apart from the others.
* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand.
;The task:
# Simulate several thousand instances of the game where the prisoners randomly open drawers
# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
:* First opening the drawer whose outside number is his prisoner number.
:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
;References:
# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
# [[wp:100 prisoners problem]]
# 100 Prisoners Escape Puzzle DataGenetics.
# Random permutation statistics#One hundred prisoners on Wikipedia.
| import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
private static boolean playOptimal(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(secretList);
prisoner:
for (int i = 0; i < secretList.size(); ++i) {
int prev = i;
for (int j = 0; j < secretList.size() / 2; ++j) {
if (secretList.get(prev) == i) {
continue prisoner;
}
prev = secretList.get(prev);
}
return false;
}
return true;
}
private static boolean playRandom(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(secretList);
prisoner:
for (Integer i : secretList) {
List<Integer> trialList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(trialList);
for (int j = 0; j < trialList.size() / 2; ++j) {
if (Objects.equals(trialList.get(j), i)) {
continue prisoner;
}
}
return false;
}
return true;
}
private static double exec(int n, int p, Function<Integer, Boolean> play) {
int succ = 0;
for (int i = 0; i < n; ++i) {
if (play.apply(p)) {
succ++;
}
}
return (succ * 100.0) / n;
}
public static void main(String[] args) {
final int n = 100_000;
final int p = 100;
System.out.printf("# of executions: %d\n", n);
System.out.printf("Optimal play success rate: %f%%\n", exec(n, p, Main::playOptimal));
System.out.printf("Random play success rate: %f%%\n", exec(n, p, Main::playRandom));
}
} |
15 puzzle game | Java 8 | Implement the Fifteen Puzzle Game.
The '''15-puzzle''' is also known as:
:::* '''Fifteen Puzzle'''
:::* '''Gem Puzzle'''
:::* '''Boss Puzzle'''
:::* '''Game of Fifteen'''
:::* '''Mystic Square'''
:::* '''14-15 Puzzle'''
:::* and some others.
;Related Tasks:
:* 15 Puzzle Solver
:* [[16 Puzzle Game]]
| package fifteenpuzzle;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
class FifteenPuzzle extends JPanel {
private final int side = 4;
private final int numTiles = side * side - 1;
private final Random rand = new Random();
private final int[] tiles = new int[numTiles + 1];
private final int tileSize;
private int blankPos;
private final int margin;
private final int gridSize;
private boolean gameOver;
private FifteenPuzzle() {
final int dim = 640;
margin = 80;
tileSize = (dim - 2 * margin) / side;
gridSize = tileSize * side;
setPreferredSize(new Dimension(dim, dim + margin));
setBackground(Color.WHITE);
setForeground(new Color(0x6495ED)); // cornflowerblue
setFont(new Font("SansSerif", Font.BOLD, 60));
gameOver = true;
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (gameOver) {
newGame();
} else {
int ex = e.getX() - margin;
int ey = e.getY() - margin;
if (ex < 0 || ex > gridSize || ey < 0 || ey > gridSize) {
return;
}
int c1 = ex / tileSize;
int r1 = ey / tileSize;
int c2 = blankPos % side;
int r2 = blankPos / side;
int clickPos = r1 * side + c1;
int dir = 0;
if (c1 == c2 && Math.abs(r1 - r2) > 0) {
dir = (r1 - r2) > 0 ? 4 : -4;
} else if (r1 == r2 && Math.abs(c1 - c2) > 0) {
dir = (c1 - c2) > 0 ? 1 : -1;
}
if (dir != 0) {
do {
int newBlankPos = blankPos + dir;
tiles[blankPos] = tiles[newBlankPos];
blankPos = newBlankPos;
} while (blankPos != clickPos);
tiles[blankPos] = 0;
}
gameOver = isSolved();
}
repaint();
}
});
newGame();
}
private void newGame() {
do {
reset();
shuffle();
} while (!isSolvable());
gameOver = false;
}
private void reset() {
for (int i = 0; i < tiles.length; i++) {
tiles[i] = (i + 1) % tiles.length;
}
blankPos = tiles.length - 1;
}
private void shuffle() {
// don't include the blank space in the shuffle, leave it
// in the home position
int n = numTiles;
while (n > 1) {
int r = rand.nextInt(n--);
int tmp = tiles[r];
tiles[r] = tiles[n];
tiles[n] = tmp;
}
}
/* Only half the permutations of the puzzle are solvable.
Whenever a tile is preceded by a tile with higher value it counts
as an inversion. In our case, with the blank space in the home
position, the number of inversions must be even for the puzzle
to be solvable.
See also:
www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html
*/
private boolean isSolvable() {
int countInversions = 0;
for (int i = 0; i < numTiles; i++) {
for (int j = 0; j < i; j++) {
if (tiles[j] > tiles[i]) {
countInversions++;
}
}
}
return countInversions % 2 == 0;
}
private boolean isSolved() {
if (tiles[tiles.length - 1] != 0) {
return false;
}
for (int i = numTiles - 1; i >= 0; i--) {
if (tiles[i] != i + 1) {
return false;
}
}
return true;
}
private void drawGrid(Graphics2D g) {
for (int i = 0; i < tiles.length; i++) {
int r = i / side;
int c = i % side;
int x = margin + c * tileSize;
int y = margin + r * tileSize;
if (tiles[i] == 0) {
if (gameOver) {
g.setColor(Color.GREEN);
drawCenteredString(g, "\u2713", x, y);
}
continue;
}
g.setColor(getForeground());
g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);
g.setColor(Color.blue.darker());
g.drawRoundRect(x, y, tileSize, tileSize, 25, 25);
g.setColor(Color.WHITE);
drawCenteredString(g, String.valueOf(tiles[i]), x, y);
}
}
private void drawStartMessage(Graphics2D g) {
if (gameOver) {
g.setFont(getFont().deriveFont(Font.BOLD, 18));
g.setColor(getForeground());
String s = "click to start a new game";
int x = (getWidth() - g.getFontMetrics().stringWidth(s)) / 2;
int y = getHeight() - margin;
g.drawString(s, x, y);
}
}
private void drawCenteredString(Graphics2D g, String s, int x, int y) {
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
int des = fm.getDescent();
x = x + (tileSize - fm.stringWidth(s)) / 2;
y = y + (asc + (tileSize - (asc + des)) / 2);
g.drawString(s, x, y);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
drawStartMessage(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Fifteen Puzzle");
f.setResizable(false);
f.add(new FifteenPuzzle(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
21 game | Java | '''21''' is a two player game, the game is played by choosing
a number ('''1''', '''2''', or '''3''') to be added to the ''running total''.
The game is won by the player whose chosen number causes the ''running total''
to reach ''exactly'' '''21'''.
The ''running total'' starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the ''running total''.
;Task:
Write a computer program that will:
::* do the prompting (or provide a button menu),
::* check for errors and display appropriate error messages,
::* do the additions (add a chosen number to the ''running total''),
::* display the ''running total'',
::* provide a mechanism for the player to quit/exit/halt/stop/close the program,
::* issue a notification when there is a winner, and
::* determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| import java.util.Random;
import java.util.Scanner;
public class TwentyOneGame {
public static void main(String[] args) {
new TwentyOneGame().run(true, 21, new int[] {1, 2, 3});
}
public void run(boolean computerPlay, int max, int[] valid) {
String comma = "";
for ( int i = 0 ; i < valid.length ; i++ ) {
comma += valid[i];
if ( i < valid.length - 2 && valid.length >= 3 ) {
comma += ", ";
}
if ( i == valid.length - 2 ) {
comma += " or ";
}
}
System.out.printf("The %d game.%nEach player chooses to add %s to a running total.%n" +
"The player whose turn it is when the total reaches %d will win the game.%n" +
"Winner of the game starts the next game. Enter q to quit.%n%n", max, comma, max);
int cGames = 0;
int hGames = 0;
boolean anotherGame = true;
try (Scanner scanner = new Scanner(System.in);) {
while ( anotherGame ) {
Random r = new Random();
int round = 0;
int total = 0;
System.out.printf("Start game %d%n", hGames + cGames + 1);
DONE:
while ( true ) {
round++;
System.out.printf("ROUND %d:%n%n", round);
for ( int play = 0 ; play < 2 ; play++ ) {
if ( computerPlay ) {
int guess = 0;
// try find one equal
for ( int test : valid ) {
if ( total + test == max ) {
guess = test;
break;
}
}
// try find one greater than
if ( guess == 0 ) {
for ( int test : valid ) {
if ( total + test >= max ) {
guess = test;
break;
}
}
}
if ( guess == 0 ) {
guess = valid[r.nextInt(valid.length)];
}
total += guess;
System.out.printf("The computer chooses %d%n", guess);
System.out.printf("Running total is now %d%n%n", total);
if ( total >= max ) {
break DONE;
}
}
else {
while ( true ) {
System.out.printf("Your choice among %s: ", comma);
String line = scanner.nextLine();
if ( line.matches("^[qQ].*") ) {
System.out.printf("Computer wins %d game%s, human wins %d game%s. One game incomplete.%nQuitting.%n", cGames, cGames == 1 ? "" : "s", hGames, hGames == 1 ? "" : "s");
return;
}
try {
int input = Integer.parseInt(line);
boolean inputOk = false;
for ( int test : valid ) {
if ( input == test ) {
inputOk = true;
break;
}
}
if ( inputOk ) {
total += input;
System.out.printf("Running total is now %d%n%n", total);
if ( total >= max ) {
break DONE;
}
break;
}
else {
System.out.printf("Invalid input - must be a number among %s. Try again.%n", comma);
}
}
catch (NumberFormatException e) {
System.out.printf("Invalid input - must be a number among %s. Try again.%n", comma);
}
}
}
computerPlay = !computerPlay;
}
}
String win;
if ( computerPlay ) {
win = "Computer wins!!";
cGames++;
}
else {
win = "You win and probably had help from another computer!!";
hGames++;
}
System.out.printf("%s%n", win);
System.out.printf("Computer wins %d game%s, human wins %d game%s%n%n", cGames, cGames == 1 ? "" : "s", hGames, hGames == 1 ? "" : "s");
while ( true ) {
System.out.printf("Another game (y/n)? ");
String line = scanner.nextLine();
if ( line.matches("^[yY]$") ) {
// OK
System.out.printf("%n");
break;
}
else if ( line.matches("^[nN]$") ) {
anotherGame = false;
System.out.printf("Quitting.%n");
break;
}
else {
System.out.printf("Invalid input - must be a y or n. Try again.%n");
}
}
}
}
}
}
|
24 game | Java 7 | The 24 Game tests one's mental arithmetic.
;Task
Write a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to '''24'''.
* Only the following operators/functions are allowed: multiplication, division, addition, subtraction
* Division should use floating point or rational arithmetic, etc, to preserve remainders.
* Brackets are allowed, if using an infix expression evaluator.
* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
* The order of the digits when given does not have to be preserved.
;Notes
* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
* The task is not for the program to generate the expression, or test whether an expression is even possible.
;Related tasks
* [[24 game/Solve]]
;Reference
* The 24 Game on h2g2.
| import java.util.*;
public class Game24 {
static Random r = new Random();
public static void main(String[] args) {
int[] digits = randomDigits();
Scanner in = new Scanner(System.in);
System.out.print("Make 24 using these digits: ");
System.out.println(Arrays.toString(digits));
System.out.print("> ");
Stack<Float> s = new Stack<>();
long total = 0;
for (char c : in.nextLine().toCharArray()) {
if ('0' <= c && c <= '9') {
int d = c - '0';
total += (1 << (d * 5));
s.push((float) d);
} else if ("+/-*".indexOf(c) != -1) {
s.push(applyOperator(s.pop(), s.pop(), c));
}
}
if (tallyDigits(digits) != total)
System.out.print("Not the same digits. ");
else if (Math.abs(24 - s.peek()) < 0.001F)
System.out.println("Correct!");
else
System.out.print("Not correct.");
}
static float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
static long tallyDigits(int[] a) {
long total = 0;
for (int i = 0; i < 4; i++)
total += (1 << (a[i] * 5));
return total;
}
static int[] randomDigits() {
int[] result = new int[4];
for (int i = 0; i < 4; i++)
result[i] = r.nextInt(9) + 1;
return result;
}
} |
24 game/Solve | Java 7 | Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].
Show examples of solutions generated by the program.
;Related task:
* [[Arithmetic Evaluator]]
| import java.util.*;
public class Game24Player {
final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo",
"nnnnooo"};
final String ops = "+-*/^";
String solution;
List<Integer> digits;
public static void main(String[] args) {
new Game24Player().play();
}
void play() {
digits = getSolvableDigits();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Make 24 using these digits: ");
System.out.println(digits);
System.out.println("(Enter 'q' to quit, 's' for a solution)");
System.out.print("> ");
String line = in.nextLine();
if (line.equalsIgnoreCase("q")) {
System.out.println("\nThanks for playing");
return;
}
if (line.equalsIgnoreCase("s")) {
System.out.println(solution);
digits = getSolvableDigits();
continue;
}
char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray();
try {
validate(entry);
if (evaluate(infixToPostfix(entry))) {
System.out.println("\nCorrect! Want to try another? ");
digits = getSolvableDigits();
} else {
System.out.println("\nNot correct.");
}
} catch (Exception e) {
System.out.printf("%n%s Try again.%n", e.getMessage());
}
}
}
void validate(char[] input) throws Exception {
int total1 = 0, parens = 0, opsCount = 0;
for (char c : input) {
if (Character.isDigit(c))
total1 += 1 << (c - '0') * 4;
else if (c == '(')
parens++;
else if (c == ')')
parens--;
else if (ops.indexOf(c) != -1)
opsCount++;
if (parens < 0)
throw new Exception("Parentheses mismatch.");
}
if (parens != 0)
throw new Exception("Parentheses mismatch.");
if (opsCount != 3)
throw new Exception("Wrong number of operators.");
int total2 = 0;
for (int d : digits)
total2 += 1 << d * 4;
if (total1 != total2)
throw new Exception("Not the same digits.");
}
boolean evaluate(char[] line) throws Exception {
Stack<Float> s = new Stack<>();
try {
for (char c : line) {
if ('0' <= c && c <= '9')
s.push((float) c - '0');
else
s.push(applyOperator(s.pop(), s.pop(), c));
}
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return (Math.abs(24 - s.peek()) < 0.001F);
}
float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
List<Integer> randomDigits() {
Random r = new Random();
List<Integer> result = new ArrayList<>(4);
for (int i = 0; i < 4; i++)
result.add(r.nextInt(9) + 1);
return result;
}
List<Integer> getSolvableDigits() {
List<Integer> result;
do {
result = randomDigits();
} while (!isSolvable(result));
return result;
}
boolean isSolvable(List<Integer> digits) {
Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);
permute(digits, dPerms, 0);
int total = 4 * 4 * 4;
List<List<Integer>> oPerms = new ArrayList<>(total);
permuteOperators(oPerms, 4, total);
StringBuilder sb = new StringBuilder(4 + 3);
for (String pattern : patterns) {
char[] patternChars = pattern.toCharArray();
for (List<Integer> dig : dPerms) {
for (List<Integer> opr : oPerms) {
int i = 0, j = 0;
for (char c : patternChars) {
if (c == 'n')
sb.append(dig.get(i++));
else
sb.append(ops.charAt(opr.get(j++)));
}
String candidate = sb.toString();
try {
if (evaluate(candidate.toCharArray())) {
solution = postfixToInfix(candidate);
return true;
}
} catch (Exception ignored) {
}
sb.setLength(0);
}
}
}
return false;
}
String postfixToInfix(String postfix) {
class Expression {
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
}
Stack<Expression> expr = new Stack<>();
for (char c : postfix.toCharArray()) {
int idx = ops.indexOf(c);
if (idx != -1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec)
l.ex = '(' + l.ex + ')';
if (r.prec <= opPrec)
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, "" + c));
} else {
expr.push(new Expression("" + c));
}
}
return expr.peek().ex;
}
char[] infixToPostfix(char[] infix) throws Exception {
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
try {
for (char c : infix) {
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 >= prec1)
sb.append(ops.charAt(s.pop()));
else
break;
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop()));
s.pop();
} else {
sb.append(c);
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop()));
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return sb.toString().toCharArray();
}
void permute(List<Integer> lst, Set<List<Integer>> res, int k) {
for (int i = k; i < lst.size(); i++) {
Collections.swap(lst, i, k);
permute(lst, res, k + 1);
Collections.swap(lst, k, i);
}
if (k == lst.size())
res.add(new ArrayList<>(lst));
}
void permuteOperators(List<List<Integer>> res, int n, int total) {
for (int i = 0, npow = n * n; i < total; i++)
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
} |
4-rings or 4-squares puzzle | Java | Replace '''a, b, c, d, e, f,''' and
'''g ''' with the decimal
digits LOW ---> HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
+--------------+ +--------------+
| | | |
| a | | e |
| | | |
| +---+------+---+ +---+---------+
| | | | | | | |
| | b | | d | | f | |
| | | | | | | |
| | | | | | | |
+----------+---+ +---+------+---+ |
| c | | g |
| | | |
| | | |
+--------------+ +-------------+
Show all output here.
:* Show all solutions for each letter being unique with
LOW=1 HIGH=7
:* Show all solutions for each letter being unique with
LOW=3 HIGH=9
:* Show only the ''number'' of solutions when each letter can be non-unique
LOW=0 HIGH=9
;Related task:
* [[Solve the no connection puzzle]]
| import java.util.Arrays;
public class FourSquares {
public static void main(String[] args) {
fourSquare(1, 7, true, true);
fourSquare(3, 9, true, true);
fourSquare(0, 9, false, false);
}
private static void fourSquare(int low, int high, boolean unique, boolean print) {
int count = 0;
if (print) {
System.out.println("a b c d e f g");
}
for (int a = low; a <= high; ++a) {
for (int b = low; b <= high; ++b) {
if (notValid(unique, a, b)) continue;
int fp = a + b;
for (int c = low; c <= high; ++c) {
if (notValid(unique, c, a, b)) continue;
for (int d = low; d <= high; ++d) {
if (notValid(unique, d, a, b, c)) continue;
if (fp != b + c + d) continue;
for (int e = low; e <= high; ++e) {
if (notValid(unique, e, a, b, c, d)) continue;
for (int f = low; f <= high; ++f) {
if (notValid(unique, f, a, b, c, d, e)) continue;
if (fp != d + e + f) continue;
for (int g = low; g <= high; ++g) {
if (notValid(unique, g, a, b, c, d, e, f)) continue;
if (fp != f + g) continue;
++count;
if (print) {
System.out.printf("%d %d %d %d %d %d %d%n", a, b, c, d, e, f, g);
}
}
}
}
}
}
}
}
if (unique) {
System.out.printf("There are %d unique solutions in [%d, %d]%n", count, low, high);
} else {
System.out.printf("There are %d non-unique solutions in [%d, %d]%n", count, low, high);
}
}
private static boolean notValid(boolean unique, int needle, int... haystack) {
return unique && Arrays.stream(haystack).anyMatch(p -> p == needle);
}
} |
99 bottles of beer | Java | Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''.
;The beer song:
The lyrics follow this form:
::: 99 bottles of beer on the wall
::: 99 bottles of beer
::: Take one down, pass it around
::: 98 bottles of beer on the wall
::: 98 bottles of beer on the wall
::: 98 bottles of beer
::: Take one down, pass it around
::: 97 bottles of beer on the wall
... and so on, until reaching '''0''' (zero).
Grammatical support for ''1 bottle of beer'' is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
;See also:
* http://99-bottles-of-beer.net/
* [[:Category:99_Bottles_of_Beer]]
* [[:Category:Programming language families]]
* Wikipedia 99 bottles of beer
| public class Beer {
public static void main(String args[]) {
song(99);
}
public static void song(int bottles) {
if (bottles >= 0) {
if (bottles > 1)
System.out.println(bottles + " bottles of beer on the wall\n" + bottles + " bottles of beer\nTake one down, pass it around\n" + (bottles - 1) + " bottles of beer on the wall.\n");
else if (bottles == 1)
System.out.println(bottles + " bottle of beer on the wall\n" + bottles + " bottle of beer\nTake one down, pass it around\n" + (bottles - 1) + " bottles of beer on the wall.\n");
else
System.out.println(bottles + " bottles of beer on the wall\n" + bottles + " bottles of beer\nBetter go to the store and buy some more!");
song(bottles - 1);
}
}
} |
99 bottles of beer | Java from C++ | Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''.
;The beer song:
The lyrics follow this form:
::: 99 bottles of beer on the wall
::: 99 bottles of beer
::: Take one down, pass it around
::: 98 bottles of beer on the wall
::: 98 bottles of beer on the wall
::: 98 bottles of beer
::: Take one down, pass it around
::: 97 bottles of beer on the wall
... and so on, until reaching '''0''' (zero).
Grammatical support for ''1 bottle of beer'' is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
;See also:
* http://99-bottles-of-beer.net/
* [[:Category:99_Bottles_of_Beer]]
* [[:Category:Programming language families]]
* Wikipedia 99 bottles of beer
| See: [[99 Bottles of Beer/Java/Object Oriented]]
===GUI===
|
9 billion names of God the integer | Java | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a "name":
:The integer 1 has 1 name "1".
:The integer 2 has 2 names "1+1", and "2".
:The integer 3 has 3 names "1+1+1", "2+1", and "3".
:The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4".
:The integer 5 has 7 names "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".
;Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.
A function G(n) should return the sum of the n-th row.
Demonstrate this function by displaying: G(23), G(123), G(1234), and G(12345).
Optionally note that the sum of the n-th row P(n) is the integer partition function.
Demonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).
;Extra credit
If your environment is able, plot P(n) against n for n=1\ldots 999.
;Related tasks
* [[Partition function P]]
| Translation of [[9_billion_names_of_God_the_integer#Python|Python]] via [[9_billion_names_of_God_the_integer#D|D]]
|
9 billion names of God the integer | Java 8 | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a "name":
:The integer 1 has 1 name "1".
:The integer 2 has 2 names "1+1", and "2".
:The integer 3 has 3 names "1+1+1", "2+1", and "3".
:The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4".
:The integer 5 has 7 names "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".
;Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.
A function G(n) should return the sum of the n-th row.
Demonstrate this function by displaying: G(23), G(123), G(1234), and G(12345).
Optionally note that the sum of the n-th row P(n) is the integer partition function.
Demonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).
;Extra credit
If your environment is able, plot P(n) against n for n=1\ldots 999.
;Related tasks
* [[Partition function P]]
| import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
import static java.lang.Math.min;
public class Test {
static List<BigInteger> cumu(int n) {
List<List<BigInteger>> cache = new ArrayList<>();
cache.add(asList(BigInteger.ONE));
for (int L = cache.size(); L < n + 1; L++) {
List<BigInteger> r = new ArrayList<>();
r.add(BigInteger.ZERO);
for (int x = 1; x < L + 1; x++)
r.add(r.get(r.size() - 1).add(cache.get(L - x).get(min(x, L - x))));
cache.add(r);
}
return cache.get(n);
}
static List<BigInteger> row(int n) {
List<BigInteger> r = cumu(n);
return range(0, n).mapToObj(i -> r.get(i + 1).subtract(r.get(i)))
.collect(toList());
}
public static void main(String[] args) {
System.out.println("Rows:");
for (int x = 1; x < 11; x++)
System.out.printf("%2d: %s%n", x, row(x));
System.out.println("\nSums:");
for (int x : new int[]{23, 123, 1234}) {
List<BigInteger> c = cumu(x);
System.out.printf("%s %s%n", x, c.get(c.size() - 1));
}
}
} |
A+B | Java | '''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
;Task:
Given two integers, '''A''' and '''B'''.
Their sum needs to be calculated.
;Input data:
Two integers are written in the input stream, separated by space(s):
: (-1000 \le A,B \le +1000)
;Output data:
The required output is one integer: the sum of '''A''' and '''B'''.
;Example:
::{|class="standard"
! input
! output
|-
| 2 2
| 4
|-
| 3 2
| 5
|}
| import java.io.*;
import java.util.*;
public class SumDif {
StreamTokenizer in;
PrintWriter out;
public static void main(String[] args) throws IOException {
new SumDif().run();
}
private int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}
public void run() throws IOException {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); // Standard input
out = new PrintWriter(new OutputStreamWriter(System.out)); // Standard output
solve();
out.flush();
}
private void solve() throws IOException {
out.println(nextInt() + nextInt());
}
} |
ABC problem | Java 1.6+ | You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
;Task:
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
::# Once a letter on a block is used that block cannot be used again
::# The function should be case-insensitive
::# Show the output on this page for the following 7 words in the following example
;Example:
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ABC {
public static void main(String[] args) {
List<String> blocks = Arrays.asList(
"BO", "XK", "DQ", "CP", "NA",
"GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB",
"ER", "FS", "LY", "PC", "ZM");
for (String word : Arrays.asList("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE")) {
System.out.printf("%s: %s%n", word.isEmpty() ? "\"\"" : word, canMakeWord(word, blocks));
}
}
public static boolean canMakeWord(String word, List<String> blocks) {
if (word.isEmpty())
return true;
char c = word.charAt(0);
for (int i = 0; i < blocks.size(); i++) {
String b = blocks.get(i);
if (b.charAt(0) != c && b.charAt(1) != c)
continue;
Collections.swap(blocks, 0, i);
if (canMakeWord(word.substring(1), blocks.subList(1, blocks.size())))
return true;
Collections.swap(blocks, 0, i);
}
return false;
}
} |
ASCII art diagram converter | Java | Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:
http://www.ietf.org/rfc/rfc1035.txt
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Where (every column of the table is 1 bit):
ID is 16 bits
QR = Query (0) or Response (1)
Opcode = Four bits defining kind of query:
0: a standard query (QUERY)
1: an inverse query (IQUERY)
2: a server status request (STATUS)
3-15: reserved for future use
AA = Authoritative Answer bit
TC = Truncation bit
RD = Recursion Desired bit
RA = Recursion Available bit
Z = Reserved
RCODE = Response code
QC = Question Count
ANC = Answer Count
AUC = Authority Count
ADC = Additional Count
Write a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.
If your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.
Such "Header" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars "+--+". The code should perform a little of validation of the input string, but for brevity a full validation is not required.
Bonus: perform a thoroughly validation of the input string.
| import java.math.BigInteger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class AsciiArtDiagramConverter {
private static final String TEST = "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ID |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| QDCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ANCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| NSCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\r\n" +
"| ARCOUNT |\r\n" +
"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+";
public static void main(String[] args) {
validate(TEST);
display(TEST);
Map<String,List<Integer>> asciiMap = decode(TEST);
displayMap(asciiMap);
displayCode(asciiMap, "78477bbf5496e12e1bf169a4");
}
private static void displayCode(Map<String,List<Integer>> asciiMap, String hex) {
System.out.printf("%nTest string in hex:%n%s%n%n", hex);
String bin = new BigInteger(hex,16).toString(2);
// Zero pad in front as needed
int length = 0;
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
length += pos.get(1) - pos.get(0) + 1;
}
while ( length > bin.length() ) {
bin = "0" + bin;
}
System.out.printf("Test string in binary:%n%s%n%n", bin);
System.out.printf("Name Size Bit Pattern%n");
System.out.printf("-------- ----- -----------%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
int start = pos.get(0);
int end = pos.get(1);
System.out.printf("%-8s %2d %s%n", code, end-start+1, bin.substring(start, end+1));
}
}
private static void display(String ascii) {
System.out.printf("%nDiagram:%n%n");
for ( String s : TEST.split("\\r\\n") ) {
System.out.println(s);
}
}
private static void displayMap(Map<String,List<Integer>> asciiMap) {
System.out.printf("%nDecode:%n%n");
System.out.printf("Name Size Start End%n");
System.out.printf("-------- ----- ----- -----%n");
for ( String code : asciiMap.keySet() ) {
List<Integer> pos = asciiMap.get(code);
System.out.printf("%-8s %2d %2d %2d%n", code, pos.get(1)-pos.get(0)+1, pos.get(0), pos.get(1));
}
}
private static Map<String,List<Integer>> decode(String ascii) {
Map<String,List<Integer>> map = new LinkedHashMap<>();
String[] split = TEST.split("\\r\\n");
int size = split[0].indexOf("+", 1) - split[0].indexOf("+");
int length = split[0].length() - 1;
for ( int i = 1 ; i < split.length ; i += 2 ) {
int barIndex = 1;
String test = split[i];
int next;
while ( barIndex < length && (next = test.indexOf("|", barIndex)) > 0 ) {
// List is start and end of code.
List<Integer> startEnd = new ArrayList<>();
startEnd.add((barIndex/size) + (i/2)*(length/size));
startEnd.add(((next-1)/size) + (i/2)*(length/size));
String code = test.substring(barIndex, next).replace(" ", "");
map.put(code, startEnd);
// Next bar
barIndex = next + 1;
}
}
return map;
}
private static void validate(String ascii) {
String[] split = TEST.split("\\r\\n");
if ( split.length % 2 != 1 ) {
throw new RuntimeException("ERROR 1: Invalid number of input lines. Line count = " + split.length);
}
int size = 0;
for ( int i = 0 ; i < split.length ; i++ ) {
String test = split[i];
if ( i % 2 == 0 ) {
// Start with +, an equal number of -, end with +
if ( ! test.matches("^\\+([-]+\\+)+$") ) {
throw new RuntimeException("ERROR 2: Improper line format. Line = " + test);
}
if ( size == 0 ) {
int firstPlus = test.indexOf("+");
int secondPlus = test.indexOf("+", 1);
size = secondPlus - firstPlus;
}
if ( ((test.length()-1) % size) != 0 ) {
throw new RuntimeException("ERROR 3: Improper line format. Line = " + test);
}
// Equally spaced splits of +, -
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
if ( test.charAt(j) != '+' ) {
throw new RuntimeException("ERROR 4: Improper line format. Line = " + test);
}
for ( int k = j+1 ; k < j + size ; k++ ) {
if ( test.charAt(k) != '-' ) {
throw new RuntimeException("ERROR 5: Improper line format. Line = " + test);
}
}
}
}
else {
// Vertical bar, followed by optional spaces, followed by name, followed by optional spaces, followed by vdrtical bar
if ( ! test.matches("^\\|(\\s*[A-Za-z]+\\s*\\|)+$") ) {
throw new RuntimeException("ERROR 6: Improper line format. Line = " + test);
}
for ( int j = 0 ; j < test.length()-1 ; j += size ) {
for ( int k = j+1 ; k < j + size ; k++ ) {
// Vertical bar only at boundaries
if ( test.charAt(k) == '|' ) {
throw new RuntimeException("ERROR 7: Improper line format. Line = " + test);
}
}
}
}
}
}
}
|
AVL tree | Java | {{wikipedia|AVL tree}}
In computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.
AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.
;Task:
Implement an AVL tree in the language of choice, and provide at least basic operations.
;Related task
[[Red_black_tree_sort]]
| public class AVLtree {
private Node root;
private static class Node {
private int key;
private int balance;
private int height;
private Node left;
private Node right;
private Node parent;
Node(int key, Node parent) {
this.key = key;
this.parent = parent;
}
}
public boolean insert(int key) {
if (root == null) {
root = new Node(key, null);
return true;
}
Node n = root;
while (true) {
if (n.key == key)
return false;
Node parent = n;
boolean goLeft = n.key > key;
n = goLeft ? n.left : n.right;
if (n == null) {
if (goLeft) {
parent.left = new Node(key, parent);
} else {
parent.right = new Node(key, parent);
}
rebalance(parent);
break;
}
}
return true;
}
private void delete(Node node) {
if (node.left == null && node.right == null) {
if (node.parent == null) {
root = null;
} else {
Node parent = node.parent;
if (parent.left == node) {
parent.left = null;
} else {
parent.right = null;
}
rebalance(parent);
}
return;
}
if (node.left != null) {
Node child = node.left;
while (child.right != null) child = child.right;
node.key = child.key;
delete(child);
} else {
Node child = node.right;
while (child.left != null) child = child.left;
node.key = child.key;
delete(child);
}
}
public void delete(int delKey) {
if (root == null)
return;
Node child = root;
while (child != null) {
Node node = child;
child = delKey >= node.key ? node.right : node.left;
if (delKey == node.key) {
delete(node);
return;
}
}
}
private void rebalance(Node n) {
setBalance(n);
if (n.balance == -2) {
if (height(n.left.left) >= height(n.left.right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
} else if (n.balance == 2) {
if (height(n.right.right) >= height(n.right.left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n.parent != null) {
rebalance(n.parent);
} else {
root = n;
}
}
private Node rotateLeft(Node a) {
Node b = a.right;
b.parent = a.parent;
a.right = b.left;
if (a.right != null)
a.right.parent = a;
b.left = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateRight(Node a) {
Node b = a.left;
b.parent = a.parent;
a.left = b.right;
if (a.left != null)
a.left.parent = a;
b.right = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateLeftThenRight(Node n) {
n.left = rotateLeft(n.left);
return rotateRight(n);
}
private Node rotateRightThenLeft(Node n) {
n.right = rotateRight(n.right);
return rotateLeft(n);
}
private int height(Node n) {
if (n == null)
return -1;
return n.height;
}
private void setBalance(Node... nodes) {
for (Node n : nodes) {
reheight(n);
n.balance = height(n.right) - height(n.left);
}
}
public void printBalance() {
printBalance(root);
}
private void printBalance(Node n) {
if (n != null) {
printBalance(n.left);
System.out.printf("%s ", n.balance);
printBalance(n.right);
}
}
private void reheight(Node node) {
if (node != null) {
node.height = 1 + Math.max(height(node.left), height(node.right));
}
}
public static void main(String[] args) {
AVLtree tree = new AVLtree();
System.out.println("Inserting values 1 to 10");
for (int i = 1; i < 10; i++)
tree.insert(i);
System.out.print("Printing balance: ");
tree.printBalance();
}
} |
Abbreviations, automatic | Java from D | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub-commands, options, etc.
It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if
the minimum abbreviation length of that list could be automatically (programmatically) determined.
For this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag
E_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune
Ehud Segno Maksegno Erob Hamus Arbe Kedame
Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit
Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat
domingu llunes martes miercoles xueves vienres sabadu
Bazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn
Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat
Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar
Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota
Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn
nedelia ponedelnik vtornik sriada chetvartak petak sabota
sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk
Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte
Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee
dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn
Dimanch Lendi Madi Mekredi Jedi Vandredi Samdi
nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota
nede^le ponde^li utery str^eda c^tvrtek patek sobota
Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee
s0ndag mandag tirsdag onsdag torsdag fredag l0rdag
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
Diman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato
pUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev
Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata
sunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur
Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh
sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai
dimanche lundi mardi mercredi jeudi vendredi samedi
Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon
Domingo Segunda_feira Martes Mercores Joves Venres Sabado
k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag
Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato
ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar
popule po`akahi po`alua po`akolu po`aha po`alima po`aono
Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat
ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar
vasarnap hetfo kedd szerda csutortok pentek szombat
Sunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur
sundio lundio mardio merkurdio jovdio venerdio saturdio
Minggu Senin Selasa Rabu Kamis Jumat Sabtu
Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato
De_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn
domenica lunedi martedi mercoledi giovedi venerdi sabato
Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi
Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il
Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien
Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis
Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi
xing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu
Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam
Jabot Manre Juje Wonje Taije Balaire Jarere
geminrongo minomishi martes mierkoles misheushi bernashi mishabaro
Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu
sphndag mandag tirsdag onsdag torsdag fredag lphrdag
lo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte
djadomingo djaluna djamars djarason djaweps djabierna djasabra
Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota
Domingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado
Domingo Lunes martes Miercoles Jueves Viernes Sabado
Duminica Luni Mart'i Miercuri Joi Vineri Sambata
voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota
Sunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne
nedjelja ponedjeljak utorak sreda cxetvrtak petak subota
Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo
Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-
nedel^a pondelok utorok streda s^tvrtok piatok sobota
Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota
domingo lunes martes miercoles jueves viernes sabado
sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday
Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi
sondag mandag tisdag onsdag torsdag fredag lordag
Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado
Le-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak
wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao
Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso
Pazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi
nedilya ponedilok vivtorok sereda chetver pyatnytsya subota
Chu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y
dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn
Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw
iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo
zuntik montik dinstik mitvokh donershtik fraytik shabes
iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo
Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
Bazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae
Sun Moon Mars Mercury Jove Venus Saturn
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend
Domingo Luns Terza_feira Corta_feira Xoves Venres Sabado
Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum
xing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu
djadomingu djaluna djamars djarason djaweps djabierne djasabra
Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau
''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''
To make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).
Notes concerning the above list of words
::* each line has a list of days-of-the-week for a language, separated by at least one blank
::* the words on each line happen to be in order, from Sunday --> Saturday
::* most lines have words in mixed case and some have all manner of accented words and other characters
::* some words were translated to the nearest character that was available to ''code page'' '''437'''
::* the characters in the words are not restricted except that they may not have imbedded blanks
::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word
;Task:
::* The list of words (days of the week) needn't be verified/validated.
::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.
::* A blank line (or a null line) should return a null string.
::* Process and show the output for at least the first '''five''' lines of the file.
::* Show all output here.
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Abbreviations {
public static void main(String[] args) throws IOException {
Path path = Paths.get("days_of_week.txt");
List<String> readAllLines = Files.readAllLines(path);
for (int i = 0; i < readAllLines.size(); i++) {
String line = readAllLines.get(i);
if (line.length() == 0) continue;
String[] days = line.split(" ");
if (days.length != 7) throw new RuntimeException("There aren't 7 days on line " + (i + 1));
Map<String, Integer> temp = new HashMap<>();
for (String day : days) {
Integer count = temp.getOrDefault(day, 0);
temp.put(day, count + 1);
}
if (temp.size() < 7) {
System.out.print(" ∞ ");
System.out.println(line);
continue;
}
int len = 1;
while (true) {
temp.clear();
for (String day : days) {
String sd;
if (len >= day.length()) {
sd = day;
} else {
sd = day.substring(0, len);
}
Integer count = temp.getOrDefault(sd, 0);
temp.put(sd, count + 1);
}
if (temp.size() == 7) {
System.out.printf("%2d %s\n", len, line);
break;
}
len++;
}
}
}
} |
Abbreviations, easy | Java | This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].
For this task, the following ''command table'' will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above ''command table'':
::* it can be thought of as one long literal string (with blanks at end-of-lines)
::* it may have superfluous blanks
::* it may be in any case (lower/upper/mixed)
::* the order of the words in the ''command table'' must be preserved as shown
::* the user input(s) may be in any case (upper/lower/mixed)
::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)
::* A valid abbreviation is a word that has:
:::* at least the minimum length of the number of capital letters of the word in the ''command table''
:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''
:::* a length not longer than the word in the ''command table''
::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''
::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''
::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters
::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''
::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''
::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted
;Task:
::* The command table needn't be verified/validated.
::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table'').
::* If the word is valid, then return the full uppercase version of that "word".
::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).
::* A blank input (or a null input) should return a null string.
::* Show all output here.
;An example test case to be used for this task:
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
| import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n" +
" COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n" +
" NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n" +
" Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n" +
" MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n" +
" READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n" +
" RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
public static void main(String[] args) {
String[] cmdTableArr = COMMAND_TABLE.split("\\s+");
Map<String, Integer> cmd_table = new HashMap<String, Integer>();
for (String word : cmdTableArr) { //Populate words and number of caps
cmd_table.put(word, countCaps(word));
}
System.out.print("Please enter your command to verify: ");
String userInput = input.nextLine();
String[] user_input = userInput.split("\\s+");
for (String s : user_input) {
boolean match = false; //resets each outer loop
for (String cmd : cmd_table.keySet()) {
if (s.length() >= cmd_table.get(cmd) && s.length() <= cmd.length()) {
String temp = cmd.toUpperCase();
if (temp.startsWith(s.toUpperCase())) {
System.out.print(temp + " ");
match = true;
}
}
}
if (!match) { //no match, print error msg
System.out.print("*error* ");
}
}
}
private static int countCaps(String word) {
int numCaps = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
numCaps++;
}
}
return numCaps;
}
}
|
Abbreviations, simple | Java from C++ | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub-commands, options, etc.
For this task, the following ''command table'' will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above ''command table'':
::* it can be thought of as one long literal string (with blanks at end-of-lines)
::* it may have superfluous blanks
::* it may be in any case (lower/upper/mixed)
::* the order of the words in the ''command table'' must be preserved as shown
::* the user input(s) may be in any case (upper/lower/mixed)
::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)
::* a command is followed by an optional number, which indicates the minimum abbreviation
::* A valid abbreviation is a word that has:
:::* at least the minimum length of the word's minimum number in the ''command table''
:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''
:::* a length not longer than the word in the ''command table''
::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''
::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''
::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters
::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''
::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''
::* if there isn't a number after the command, then there isn't an abbreviation permitted
;Task:
::* The command table needn't be verified/validated.
::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table'').
::* If the word is valid, then return the full uppercase version of that "word".
::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).
::* A blank input (or a null input) should return a null string.
::* Show all output here.
;An example test case to be used for this task:
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
| import java.util.*;
public class Abbreviations {
public static void main(String[] args) {
CommandList commands = new CommandList(commandTable);
String input = "riG rePEAT copies put mo rest types fup. 6 poweRin";
System.out.println(" input: " + input);
System.out.println("output: " + test(commands, input));
}
private static String test(CommandList commands, String input) {
StringBuilder output = new StringBuilder();
Scanner scanner = new Scanner(input);
while (scanner.hasNext()) {
String word = scanner.next();
if (output.length() > 0)
output.append(' ');
Command cmd = commands.findCommand(word);
if (cmd != null)
output.append(cmd.cmd);
else
output.append("*error*");
}
return output.toString();
}
private static String commandTable =
"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " +
"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " +
"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " +
"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " +
"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " +
"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1";
private static class Command {
private Command(String cmd, int minLength) {
this.cmd = cmd;
this.minLength = minLength;
}
private boolean match(String str) {
int olen = str.length();
return olen >= minLength && olen <= cmd.length()
&& cmd.regionMatches(true, 0, str, 0, olen);
}
private String cmd;
private int minLength;
}
private static Integer parseInteger(String word) {
try {
return Integer.valueOf(word);
} catch (NumberFormatException ex) {
return null;
}
}
private static class CommandList {
private CommandList(String table) {
Scanner scanner = new Scanner(table);
List<String> words = new ArrayList<>();
while (scanner.hasNext()) {
String word = scanner.next();
words.add(word.toUpperCase());
}
for (int i = 0, n = words.size(); i < n; ++i) {
String word = words.get(i);
// if there's an integer following this word, it specifies the minimum
// length for the command, otherwise the minimum length is the length
// of the command string
int len = word.length();
if (i + 1 < n) {
Integer number = parseInteger(words.get(i + 1));
if (number != null) {
len = number.intValue();
++i;
}
}
commands.add(new Command(word, len));
}
}
private Command findCommand(String word) {
for (Command command : commands) {
if (command.match(word))
return command;
}
return null;
}
private List<Command> commands = new ArrayList<>();
}
} |
Abelian sandpile model | Java | {{wikipedia|Abelian sandpile model}}
Implement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article.
The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.'''
It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.
Examples up to 2^30, wow!
javascript running on web
'''Examples:'''
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 0 -> 0 1 0 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 6 0 0 -> 0 1 2 1 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 2 1 2 0
0 0 16 0 0 -> 1 1 0 1 1
0 0 0 0 0 0 2 1 2 0
0 0 0 0 0 0 0 1 0 0
| import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AbelianSandpile {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Frame frame = new Frame();
frame.setVisible(true);
}
});
}
private static class Frame extends JFrame {
private Frame() {
super("Abelian Sandpile Model");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton start = new JButton("Restart Simulation");
start.addActionListener(e -> restartSimulation());
JButton stop = new JButton("Stop Simulation");
stop.addActionListener(e -> stopSimulation());
controlPanel.add(start);
controlPanel.add(stop);
contentPane.add(controlPanel, BorderLayout.NORTH);
contentPane.add(canvas = new Canvas(), BorderLayout.CENTER);
timer = new Timer(100, e -> canvas.runAndDraw());
timer.start();
pack();
}
private void restartSimulation() {
timer.stop();
canvas.initGrid();
timer.start();
}
private void stopSimulation() {
timer.stop();
}
private Timer timer;
private Canvas canvas;
}
private static class Canvas extends JComponent {
private Canvas() {
setBorder(BorderFactory.createEtchedBorder());
setPreferredSize(new Dimension(600, 600));
}
public void paintComponent(Graphics g) {
int width = getWidth();
int height = getHeight();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
int cellWidth = width/GRID_LENGTH;
int cellHeight = height/GRID_LENGTH;
for (int i = 0; i < GRID_LENGTH; ++i) {
for (int j = 0; j < GRID_LENGTH; ++j) {
if (grid[i][j] > 0) {
g.setColor(COLORS[grid[i][j]]);
g.fillRect(i * cellWidth, j * cellHeight, cellWidth, cellHeight);
}
}
}
}
private void initGrid() {
for (int i = 0; i < GRID_LENGTH; ++i) {
for (int j = 0; j < GRID_LENGTH; ++j) {
grid[i][j] = 0;
}
}
}
private void runAndDraw() {
for (int i = 0; i < 100; ++i)
addSand(GRID_LENGTH/2, GRID_LENGTH/2);
repaint();
}
private void addSand(int i, int j) {
int grains = grid[i][j];
if (grains < 3) {
grid[i][j]++;
}
else {
grid[i][j] = grains - 3;
if (i > 0)
addSand(i - 1, j);
if (i < GRID_LENGTH - 1)
addSand(i + 1, j);
if (j > 0)
addSand(i, j - 1);
if (j < GRID_LENGTH - 1)
addSand(i, j + 1);
}
}
private int[][] grid = new int[GRID_LENGTH][GRID_LENGTH];
}
private static final Color[] COLORS = {
Color.WHITE,
new Color(0x00, 0xbf, 0xff),
new Color(0xff, 0xd7, 0x00),
new Color(0xb0, 0x30, 0x60)
};
private static final int GRID_LENGTH = 300;
} |
Abundant odd numbers | Java | An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',
or, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.
;E.G.:
'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n''');
or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').
Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers.
To make things more interesting, this task is specifically about finding ''odd abundant numbers''.
;Task
*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
;References:
:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| import java.util.ArrayList;
import java.util.List;
public class AbundantOddNumbers {
private static List<Integer> list = new ArrayList<>();
private static List<Integer> result = new ArrayList<>();
public static void main(String[] args) {
System.out.println("First 25: ");
abundantOdd(1,100000, 25, false);
System.out.println("\n\nThousandth: ");
abundantOdd(1,2500000, 1000, true);
System.out.println("\n\nFirst over 1bn:");
abundantOdd(1000000001, 2147483647, 1, false);
}
private static void abundantOdd(int start, int finish, int listSize, boolean printOne) {
for (int oddNum = start; oddNum < finish; oddNum += 2) {
list.clear();
for (int toDivide = 1; toDivide < oddNum; toDivide+=2) {
if (oddNum % toDivide == 0)
list.add(toDivide);
}
if (sumList(list) > oddNum) {
if(!printOne)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
result.add(oddNum);
}
if(printOne && result.size() >= listSize)
System.out.printf("%5d <= %5d \n",oddNum, sumList(list) );
if(result.size() >= listSize) break;
}
}
private static int sumList(List list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
String temp = list.get(i).toString();
sum += Integer.parseInt(temp);
}
return sum;
}
}
|
Accumulator factory | Java | {{requires|Mutable State}}
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
;Rules:
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').
:Before you submit an example, make sure the function
:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used
:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''
:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''
:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''
:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''
: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':
:: x = foo(1);
x(5);
foo(3);
print x(2.3);
: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''
;Task:
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| Java has no first-class functions, so an accumulator can't use the <code>x(5)</code> syntax. The standard syntactic workaround is to use a standard method name, like <code>x.call(5)</code> or <code>x.apply(5)</code>. This is a deviation from task.
Our accumulator sums with long integers as far as possible before switching to floats. This requires the use of the <code>Number</code> class. The code needs Java 5 to autobox primitive values <code>1</code> or <code>2.3</code> into instances of Number. The <code>apply</code> method is ready to implement interface UnaryOperator in Java 8.
|
Accumulator factory | Java 5 and up | {{requires|Mutable State}}
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
;Rules:
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').
:Before you submit an example, make sure the function
:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used
:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''
:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''
:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''
:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''
: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':
:: x = foo(1);
x(5);
foo(3);
print x(2.3);
: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''
;Task:
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| public class Accumulator
//implements java.util.function.UnaryOperator<Number> // Java 8
{
private Number sum;
public Accumulator(Number sum0) {
sum = sum0;
}
public Number apply(Number n) {
// Acts like sum += n, but chooses long or double.
// Converts weird types (like BigInteger) to double.
return (longable(sum) && longable(n)) ?
(sum = sum.longValue() + n.longValue()) :
(sum = sum.doubleValue() + n.doubleValue());
}
private static boolean longable(Number n) {
return n instanceof Byte || n instanceof Short ||
n instanceof Integer || n instanceof Long;
}
public static void main(String[] args) {
Accumulator x = new Accumulator(1);
x.apply(5);
new Accumulator(3);
System.out.println(x.apply(2.3));
}
}
|
Accumulator factory | Java 8 and up | {{requires|Mutable State}}
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
;Rules:
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').
:Before you submit an example, make sure the function
:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used
:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''
:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''
:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''
:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''
: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':
:: x = foo(1);
x(5);
foo(3);
print x(2.3);
: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''
;Task:
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| import java.util.function.UnaryOperator;
public class AccumulatorFactory {
public static UnaryOperator<Number> accumulator(Number sum0) {
// Allows sum[0] = ... inside lambda.
Number[] sum = { sum0 };
// Acts like n -> sum[0] += n, but chooses long or double.
// Converts weird types (like BigInteger) to double.
return n -> (longable(sum[0]) && longable(n)) ?
(sum[0] = sum[0].longValue() + n.longValue()) :
(sum[0] = sum[0].doubleValue() + n.doubleValue());
}
private static boolean longable(Number n) {
return n instanceof Byte || n instanceof Short ||
n instanceof Integer || n instanceof Long;
}
public static void main(String[] args) {
UnaryOperator<Number> x = accumulator(1);
x.apply(5);
accumulator(3);
System.out.println(x.apply(2.3));
}
} |
Aliquot sequence classifications | Java | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the [[Proper divisors]] of the previous term.
:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.
:There are several classifications for non termination:
:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.
:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.
:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.
:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.
:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.
:And finally:
:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
;Task:
# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
# Use it to display the classification and sequences of the numbers one to ten inclusive.
# Use it to show the classification and sequences of the following integers, in order:
:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
;Related tasks:
* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).
* [[Proper divisors]]
* [[Amicable pairs]]
| Translation of [[Aliquot_sequence_classifications#Python|Python]] via [[Aliquot_sequence_classifications#D|D]]
|
Aliquot sequence classifications | Java 8 | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the [[Proper divisors]] of the previous term.
:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.
:There are several classifications for non termination:
:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.
:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.
:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.
:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.
:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.
:And finally:
:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
;Task:
# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
# Use it to display the classification and sequences of the numbers one to ten inclusive.
# Use it to show the classification and sequences of the following integers, in order:
:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
;Related tasks:
* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).
* [[Proper divisors]]
* [[Amicable pairs]]
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
static boolean aliquot(long n, int maxLen, long maxTerm) {
List<Long> s = new ArrayList<>(maxLen);
s.add(n);
long newN = n;
while (s.size() <= maxLen && newN < maxTerm) {
newN = properDivsSum(s.get(s.size() - 1));
if (s.contains(newN)) {
if (s.get(0) == newN) {
switch (s.size()) {
case 1:
return report("Perfect", s);
case 2:
return report("Amicable", s);
default:
return report("Sociable of length " + s.size(), s);
}
} else if (s.get(s.size() - 1) == newN) {
return report("Aspiring", s);
} else
return report("Cyclic back to " + newN, s);
} else {
s.add(newN);
if (newN == 0)
return report("Terminating", s);
}
}
return report("Non-terminating", s);
}
static boolean report(String msg, List<Long> result) {
System.out.println(msg + ": " + result);
return false;
}
public static void main(String[] args) {
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488};
LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));
System.out.println();
Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
}
} |
Anagrams/Deranged anagrams | Java 8 | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.
;Task
Use the word list at unixdict to find and display the longest deranged anagram.
;Related
* [[Permutations/Derangements]]
* Best shuffle
{{Related tasks/Word plays}}
| import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DerangedAnagrams {
public static void main(String[] args) throws IOException {
List<String> words = Files.readAllLines(new File("unixdict.txt").toPath());
printLongestDerangedAnagram(words);
}
private static void printLongestDerangedAnagram(List<String> words) {
words.sort(Comparator.comparingInt(String::length).reversed().thenComparing(String::toString));
Map<String, ArrayList<String>> map = new HashMap<>();
for (String word : words) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String key = String.valueOf(chars);
List<String> anagrams = map.computeIfAbsent(key, k -> new ArrayList<>());
for (String anagram : anagrams) {
if (isDeranged(word, anagram)) {
System.out.printf("%s %s%n", anagram, word);
return;
}
}
anagrams.add(word);
}
System.out.println("no result");
}
private static boolean isDeranged(String word1, String word2) {
for (int i = 0; i < word1.length(); i++) {
if (word1.charAt(i) == word2.charAt(i)) {
return false;
}
}
return true;
}
} |
Angle difference between two bearings | Java from C++ | Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]
;Task:
Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings.
Input bearings are expressed in the range '''-180''' to '''+180''' degrees.
The result is also expressed in the range '''-180''' to '''+180''' degrees.
Compute the angle for the following pairs:
* 20 degrees ('''b1''') and 45 degrees ('''b2''')
* -45 and 45
* -85 and 90
* -95 and 90
* -45 and 125
* -45 and 145
* 29.4803 and -88.6381
* -78.3251 and -159.036
;Optional extra:
Allow the input bearings to be any (finite) value.
;Test cases:
* -70099.74233810938 and 29840.67437876723
* -165313.6666297357 and 33693.9894517456
* 1174.8380510598456 and -154146.66490124757
* 60175.77306795546 and 42213.07192354373
| public class AngleDifference {
public static double getDifference(double b1, double b2) {
double r = (b2 - b1) % 360.0;
if (r < -180.0)
r += 360.0;
if (r >= 180.0)
r -= 360.0;
return r;
}
public static void main(String[] args) {
System.out.println("Input in -180 to +180 range");
System.out.println(getDifference(20.0, 45.0));
System.out.println(getDifference(-45.0, 45.0));
System.out.println(getDifference(-85.0, 90.0));
System.out.println(getDifference(-95.0, 90.0));
System.out.println(getDifference(-45.0, 125.0));
System.out.println(getDifference(-45.0, 145.0));
System.out.println(getDifference(-45.0, 125.0));
System.out.println(getDifference(-45.0, 145.0));
System.out.println(getDifference(29.4803, -88.6381));
System.out.println(getDifference(-78.3251, -159.036));
System.out.println("Input in wider range");
System.out.println(getDifference(-70099.74233810938, 29840.67437876723));
System.out.println(getDifference(-165313.6666297357, 33693.9894517456));
System.out.println(getDifference(1174.8380510598456, -154146.66490124757));
System.out.println(getDifference(60175.77306795546, 42213.07192354373));
}
} |
Anti-primes | Java from Go | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
;Task:
Generate and show here, the first twenty anti-primes.
;Related tasks:
:* [[Factors of an integer]]
:* [[Sieve of Eratosthenes]]
| public class Antiprime {
static int countDivisors(int n) {
if (n < 2) return 1;
int count = 2; // 1 and n
for (int i = 2; i <= n/2; ++i) {
if (n%i == 0) ++count;
}
return count;
}
public static void main(String[] args) {
int maxDiv = 0, count = 0;
System.out.println("The first 20 anti-primes are:");
for (int n = 1; count < 20; ++n) {
int d = countDivisors(n);
if (d > maxDiv) {
System.out.printf("%d ", n);
maxDiv = d;
count++;
}
}
System.out.println();
}
} |
Apply a digital filter (direct form II transposed) | Java from Kotlin | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]
;Task:
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
;See also:
[Wikipedia on Butterworth filters]
| public class DigitalFilter {
private static double[] filter(double[] a, double[] b, double[] signal) {
double[] result = new double[signal.length];
for (int i = 0; i < signal.length; ++i) {
double tmp = 0.0;
for (int j = 0; j < b.length; ++j) {
if (i - j < 0) continue;
tmp += b[j] * signal[i - j];
}
for (int j = 1; j < a.length; ++j) {
if (i - j < 0) continue;
tmp -= a[j] * result[i - j];
}
tmp /= a[0];
result[i] = tmp;
}
return result;
}
public static void main(String[] args) {
double[] a = new double[]{1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17};
double[] b = new double[]{0.16666667, 0.5, 0.5, 0.16666667};
double[] signal = new double[]{
-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,
-0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,
0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,
0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,
0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589
};
double[] result = filter(a, b, signal);
for (int i = 0; i < result.length; ++i) {
System.out.printf("% .8f", result[i]);
System.out.print((i + 1) % 5 != 0 ? ", " : "\n");
}
}
} |
Approximate equality | Java from Kotlin | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
;Task:
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
'''100000000000000.01''' may be approximately equal to '''100000000000000.011''',
even though '''100.01''' is not approximately equal to '''100.011'''.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')
:# 100.01, 100.011 (note: should return ''false'')
:# 10000000000000.001 / 10000.0, 1000000000.0000001000
:# 0.001, 0.0010000001
:# 0.000000000000000000000101, 0.0
:# sqrt(2) * sqrt(2), 2.0
:# -sqrt(2) * sqrt(2), -2.0
:# 3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
__TOC__
| public class Approximate {
private static boolean approxEquals(double value, double other, double epsilon) {
return Math.abs(value - other) < epsilon;
}
private static void test(double a, double b) {
double epsilon = 1e-18;
System.out.printf("%f, %f => %s\n", a, b, approxEquals(a, b, epsilon));
}
public static void main(String[] args) {
test(100000000000000.01, 100000000000000.011);
test(100.01, 100.011);
test(10000000000000.001 / 10000.0, 1000000000.0000001000);
test(0.001, 0.0010000001);
test(0.000000000000000000000101, 0.0);
test(Math.sqrt(2.0) * Math.sqrt(2.0), 2.0);
test(-Math.sqrt(2.0) * Math.sqrt(2.0), -2.0);
test(3.14159265358979323846, 3.14159265358979324);
}
} |
Archimedean spiral | Java 8 | The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.
An Archimedean spiral can be described by the equation:
:\, r=a+b\theta
with real numbers ''a'' and ''b''.
;Task
Draw an Archimedean spiral.
| import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class ArchimedeanSpiral extends JPanel {
public ArchimedeanSpiral() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
void drawGrid(Graphics2D g) {
g.setColor(new Color(0xEEEEEE));
g.setStroke(new BasicStroke(2));
double angle = toRadians(45);
int w = getWidth();
int center = w / 2;
int margin = 10;
int numRings = 8;
int spacing = (w - 2 * margin) / (numRings * 2);
for (int i = 0; i < numRings; i++) {
int pos = margin + i * spacing;
int size = w - (2 * margin + i * 2 * spacing);
g.drawOval(pos, pos, size, size);
double ia = i * angle;
int x2 = center + (int) (cos(ia) * (w - 2 * margin) / 2);
int y2 = center - (int) (sin(ia) * (w - 2 * margin) / 2);
g.drawLine(center, center, x2, y2);
}
}
void drawSpiral(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(Color.orange);
double degrees = toRadians(0.1);
double center = getWidth() / 2;
double end = 360 * 2 * 10 * degrees;
double a = 0;
double b = 20;
double c = 1;
for (double theta = 0; theta < end; theta += degrees) {
double r = a + b * pow(theta, 1 / c);
double x = r * cos(theta);
double y = r * sin(theta);
plot(g, (int) (center + x), (int) (center - y));
}
}
void plot(Graphics2D g, int x, int y) {
g.drawOval(x, y, 1, 1);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
drawSpiral(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Archimedean Spiral");
f.setResizable(false);
f.add(new ArchimedeanSpiral(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Arithmetic-geometric mean | Java | {{wikipedia|Arithmetic-geometric mean}}
;Task:
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence:
: a_0 = a; \qquad g_0 = g
: a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}.
Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
:\mathrm{agm}(1,1/\sqrt{2})
;Also see:
* mathworld.wolfram.com/Arithmetic-Geometric Mean
| /*
* Arithmetic-Geometric Mean of 1 & 1/sqrt(2)
* Brendan Shaklovitz
* 5/29/12
*/
public class ArithmeticGeometricMean {
public static double agm(double a, double g) {
double a1 = a;
double g1 = g;
while (Math.abs(a1 - g1) >= 1.0e-14) {
double arith = (a1 + g1) / 2.0;
double geom = Math.sqrt(a1 * g1);
a1 = arith;
g1 = geom;
}
return a1;
}
public static void main(String[] args) {
System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0)));
}
} |
Arithmetic-geometric mean/Calculate Pi | Java from Kotlin | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \pi.
With the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:
\pi =
\frac{4\; \mathrm{agm}(1, 1/\sqrt{2})^2}
{1 - \sum\limits_{n=1}^{\infty} 2^{n+1}(a_n^2-g_n^2)}
This allows you to make the approximation, for any large '''N''':
\pi \approx
\frac{4\; a_N^2}
{1 - \sum\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \pi.
| import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Objects;
public class Calculate_Pi {
private static final MathContext con1024 = new MathContext(1024);
private static final BigDecimal bigTwo = new BigDecimal(2);
private static final BigDecimal bigFour = new BigDecimal(4);
private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) {
BigDecimal x0 = BigDecimal.ZERO;
BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue()));
while (!Objects.equals(x0, x1)) {
x0 = x1;
x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con);
}
return x1;
}
public static void main(String[] args) {
BigDecimal a = BigDecimal.ONE;
BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024);
BigDecimal t;
BigDecimal sum = BigDecimal.ZERO;
BigDecimal pow = bigTwo;
while (!Objects.equals(a, g)) {
t = a.add(g).divide(bigTwo, con1024);
g = bigSqrt(a.multiply(g), con1024);
a = t;
pow = pow.multiply(bigTwo);
sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow));
}
BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024);
System.out.println(pi);
}
} |
Arithmetic evaluation | Java | Create a program which parses and evaluates arithmetic expressions.
;Requirements:
* An abstract-syntax tree (AST) for the expression must be created from parsing the input.
* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
* The expression will be a string or list of symbols like "(1+3)*7".
* The four symbols + - * / must be supported as binary operators with conventional precedence rules.
* Precedence-control parentheses must also be supported.
;Note:
For those who don't remember, mathematical precedence is as follows:
* Parentheses
* Multiplication/Division (left to right)
* Addition/Subtraction (left to right)
;C.f:
* [[24 game Player]].
* [[Parsing/RPN calculator algorithm]].
* [[Parsing/RPN to infix conversion]].
| import java.util.Stack;
public class ArithmeticEvaluation {
public interface Expression {
BigRational eval();
}
public enum Parentheses {LEFT}
public enum BinaryOperator {
ADD('+', 1),
SUB('-', 1),
MUL('*', 2),
DIV('/', 2);
public final char symbol;
public final int precedence;
BinaryOperator(char symbol, int precedence) {
this.symbol = symbol;
this.precedence = precedence;
}
public BigRational eval(BigRational leftValue, BigRational rightValue) {
switch (this) {
case ADD:
return leftValue.add(rightValue);
case SUB:
return leftValue.subtract(rightValue);
case MUL:
return leftValue.multiply(rightValue);
case DIV:
return leftValue.divide(rightValue);
}
throw new IllegalStateException();
}
public static BinaryOperator forSymbol(char symbol) {
for (BinaryOperator operator : values()) {
if (operator.symbol == symbol) {
return operator;
}
}
throw new IllegalArgumentException(String.valueOf(symbol));
}
}
public static class Number implements Expression {
private final BigRational number;
public Number(BigRational number) {
this.number = number;
}
@Override
public BigRational eval() {
return number;
}
@Override
public String toString() {
return number.toString();
}
}
public static class BinaryExpression implements Expression {
public final Expression leftOperand;
public final BinaryOperator operator;
public final Expression rightOperand;
public BinaryExpression(Expression leftOperand, BinaryOperator operator, Expression rightOperand) {
this.leftOperand = leftOperand;
this.operator = operator;
this.rightOperand = rightOperand;
}
@Override
public BigRational eval() {
BigRational leftValue = leftOperand.eval();
BigRational rightValue = rightOperand.eval();
return operator.eval(leftValue, rightValue);
}
@Override
public String toString() {
return "(" + leftOperand + " " + operator.symbol + " " + rightOperand + ")";
}
}
private static void createNewOperand(BinaryOperator operator, Stack<Expression> operands) {
Expression rightOperand = operands.pop();
Expression leftOperand = operands.pop();
operands.push(new BinaryExpression(leftOperand, operator, rightOperand));
}
public static Expression parse(String input) {
int curIndex = 0;
boolean afterOperand = false;
Stack<Expression> operands = new Stack<>();
Stack<Object> operators = new Stack<>();
while (curIndex < input.length()) {
int startIndex = curIndex;
char c = input.charAt(curIndex++);
if (Character.isWhitespace(c))
continue;
if (afterOperand) {
if (c == ')') {
Object operator;
while (!operators.isEmpty() && ((operator = operators.pop()) != Parentheses.LEFT))
createNewOperand((BinaryOperator) operator, operands);
continue;
}
afterOperand = false;
BinaryOperator operator = BinaryOperator.forSymbol(c);
while (!operators.isEmpty() && (operators.peek() != Parentheses.LEFT) && (((BinaryOperator) operators.peek()).precedence >= operator.precedence))
createNewOperand((BinaryOperator) operators.pop(), operands);
operators.push(operator);
continue;
}
if (c == '(') {
operators.push(Parentheses.LEFT);
continue;
}
afterOperand = true;
while (curIndex < input.length()) {
c = input.charAt(curIndex);
if (((c < '0') || (c > '9')) && (c != '.'))
break;
curIndex++;
}
operands.push(new Number(BigRational.valueOf(input.substring(startIndex, curIndex))));
}
while (!operators.isEmpty()) {
Object operator = operators.pop();
if (operator == Parentheses.LEFT)
throw new IllegalArgumentException();
createNewOperand((BinaryOperator) operator, operands);
}
Expression expression = operands.pop();
if (!operands.isEmpty())
throw new IllegalArgumentException();
return expression;
}
public static void main(String[] args) {
String[] testExpressions = {
"2+3",
"2+3/4",
"2*3-4",
"2*(3+4)+5/6",
"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10",
"2*-3--4+-.25"};
for (String testExpression : testExpressions) {
Expression expression = parse(testExpression);
System.out.printf("Input: \"%s\", AST: \"%s\", value=%s%n", testExpression, expression, expression.eval());
}
}
} |
Array length | Java | Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
| String[] strings = { "apple", "orange" };
int length = strings.length;
|
Ascending primes | Java from C++ | Generate and show all primes with strictly ascending decimal digits.
Aside: Try solving without peeking at existing solutions. I had a weird idea for generating
a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial
but generating them quickly is at least mildly interesting.
Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is
at least one significantly better and much faster way, needing a mere 511 odd/prime tests.
;See also
;* OEIS:A052015 - Primes with distinct digits in ascending order
;Related:
*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)
*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)
| /*
* Ascending primes
*
* Generate and show all primes with strictly ascending decimal digits.
*
*
* Solution
*
* We only consider positive numbers in the range 1 to 123456789. We would
* get 7027260 primes, because there are so many primes smaller than 123456789
* (see also Wolfram Alpha).On the other hand, there are only 511 distinct
* positive integers having their digits arranged in ascending order.
* Therefore, it is better to start with numbers that have properly arranged
* digits and then check if they are prime numbers.The method of generating
* a sequence of such numbers is not indifferent.We want this sequence to be
* monotonically increasing, because then additional sorting of results will
* be unnecessary. It turns out that by using a queue we can easily get the
* desired effect. Additionally, the algorithm then does not use recursion
* (although the program probably does not have to comply with the MISRA
* standard). The problem to be solved is the queue size, the a priori
* assumption that 1000 is good enough, but a bit magical.
*/
package example.rossetacode.ascendingprimes;
import java.util.Arrays;
public class Program implements Runnable {
public static void main(String[] args) {
long t1 = System.nanoTime();
new Program().run();
long t2 = System.nanoTime();
System.out.println(
"total time consumed = " + (t2 - t1) * 1E-6 + " milliseconds");
}
public void run() {
final int MAX_SIZE = 1000;
final int[] queue = new int[MAX_SIZE];
int begin = 0;
int end = 0;
for (int k = 1; k <= 9; k++) {
queue[end++] = k;
}
while (begin < end) {
int n = queue[begin++];
for (int k = n % 10 + 1; k <= 9; k++) {
queue[end++] = n * 10 + k;
}
}
// We can use a parallel stream (and then sort the results)
// to use multiple cores.
//
System.out.println(Arrays.stream(queue).filter(this::isPrime).boxed().toList());
}
private boolean isPrime(int n) {
if (n == 2) {
return true;
}
if (n == 1 || n % 2 == 0) {
return false;
}
int root = (int) Math.sqrt(n);
for (int k = 3; k <= root; k += 2) {
if (n % k == 0) {
return false;
}
}
return true;
}
} |
Associative array/Merging | Java | Define two associative arrays, where one represents the following "base" data:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 12.75
|-
| "color" || "yellow"
|}
And the other represents "update" data:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}
| for(Map.Entry<String, String> entry : mapA.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
for(Map.Entry<String, String> entry : mapB.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
for(Map.Entry<String, String> entry : mapC.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
|
Attractive numbers | Java from C | A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.
;Example:
The number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.
;Task:
Show sequence items up to '''120'''.
;Reference:
:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| public class Attractive {
static boolean is_prime(int n) {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int d = 5;
while (d *d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}
static int count_prime_factors(int n) {
if (n == 1) return 0;
if (is_prime(n)) return 1;
int count = 0, f = 2;
while (true) {
if (n % f == 0) {
count++;
n /= f;
if (n == 1) return count;
if (is_prime(n)) f = n;
}
else if (f >= 3) f += 2;
else f = 3;
}
}
public static void main(String[] args) {
final int max = 120;
System.out.printf("The attractive numbers up to and including %d are:\n", max);
for (int i = 1, count = 0; i <= max; ++i) {
int n = count_prime_factors(i);
if (is_prime(n)) {
System.out.printf("%4d", i);
if (++count % 20 == 0) System.out.println();
}
}
System.out.println();
}
} |
Average loop length | Java | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
;Task:
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class AverageLoopLength {
private static final int N = 100000;
//analytical(n) = sum_(i=1)^n (n!/(n-i)!/n**i)
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
//memoized factorial and powers
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.nextInt(n);
}
Set<Integer> seen = new HashSet<>(n);
int current = 0;
int length = 0;
while (seen.add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void main(String[] args) {
System.out.println(" N average analytical (error)");
System.out.println("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
double avg = average(i);
double ana = analytical(i);
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
}
}
} |
Averages/Mean angle | Java 7+ | {{Related tasks/Statistical measures}}
| import java.util.Arrays;
public class AverageMeanAngle {
public static void main(String[] args) {
printAverageAngle(350.0, 10.0);
printAverageAngle(90.0, 180.0, 270.0, 360.0);
printAverageAngle(10.0, 20.0, 30.0);
printAverageAngle(370.0);
printAverageAngle(180.0);
}
private static void printAverageAngle(double... sample) {
double meanAngle = getMeanAngle(sample);
System.out.printf("The mean angle of %s is %s%n", Arrays.toString(sample), meanAngle);
}
public static double getMeanAngle(double... anglesDeg) {
double x = 0.0;
double y = 0.0;
for (double angleD : anglesDeg) {
double angleR = Math.toRadians(angleD);
x += Math.cos(angleR);
y += Math.sin(angleR);
}
double avgR = Math.atan2(y / anglesDeg.length, x / anglesDeg.length);
return Math.toDegrees(avgR);
}
} |
Averages/Pythagorean means | Java | {{Related tasks/Statistical measures}}
| import java.util.Arrays;
import java.util.List;
public class PythagoreanMeans {
public static double arithmeticMean(List<Double> numbers) {
if (numbers.isEmpty()) return Double.NaN;
double mean = 0.0;
for (Double number : numbers) {
mean += number;
}
return mean / numbers.size();
}
public static double geometricMean(List<Double> numbers) {
if (numbers.isEmpty()) return Double.NaN;
double mean = 1.0;
for (Double number : numbers) {
mean *= number;
}
return Math.pow(mean, 1.0 / numbers.size());
}
public static double harmonicMean(List<Double> numbers) {
if (numbers.isEmpty() || numbers.contains(0.0)) return Double.NaN;
double mean = 0.0;
for (Double number : numbers) {
mean += (1.0 / number);
}
return numbers.size() / mean;
}
public static void main(String[] args) {
Double[] array = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
List<Double> list = Arrays.asList(array);
double arithmetic = arithmeticMean(list);
double geometric = geometricMean(list);
double harmonic = harmonicMean(list);
System.out.format("A = %f G = %f H = %f%n", arithmetic, geometric, harmonic);
System.out.format("A >= G is %b, G >= H is %b%n", (arithmetic >= geometric), (geometric >= harmonic));
}
} |
Averages/Pythagorean means | Java 1.8 | {{Related tasks/Statistical measures}}
| public static double arithmAverage(double array[]){
if (array == null ||array.length == 0) {
return 0.0;
}
else {
return DoubleStream.of(array).average().getAsDouble();
}
}
public static double geomAverage(double array[]){
if (array == null ||array.length == 0) {
return 0.0;
}
else {
double aver = DoubleStream.of(array).reduce(1, (x, y) -> x * y);
return Math.pow(aver, 1.0 / array.length);
}
}
public static double harmAverage(double array[]){
if (array == null ||array.length == 0) {
return 0.0;
}
else {
double aver = DoubleStream.of(array)
// remove null values
.filter(n -> n > 0.0)
// generate 1/n array
.map( n-> 1.0/n)
// accumulating
.reduce(0, (x, y) -> x + y);
// just this reduce is not working- need to do in 2 steps
// .reduce(0, (x, y) -> 1.0/x + 1.0/y);
return array.length / aver ;
}
}
|
Averages/Root mean square | Java | Task
Compute the Root mean square of the numbers 1..10.
The ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}.
;See also
{{Related tasks/Statistical measures}}
| public class RootMeanSquare {
public static double rootMeanSquare(double... nums) {
double sum = 0.0;
for (double num : nums)
sum += num * num;
return Math.sqrt(sum / nums.length);
}
public static void main(String[] args) {
double[] nums = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0};
System.out.println("The RMS of the numbers from 1 to 10 is " + rootMeanSquare(nums));
}
} |
Babbage problem | Java | Charles Babbage
Charles Babbage's analytical engine.
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
{{quote
| What is the smallest positive integer whose square ends in the digits 269,696?
| Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
}}
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
;Task
The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
;Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| public class Test {
public static void main(String[] args) {
// let n be zero
int n = 0;
// repeat the following action
do {
// increase n by 1
n++;
// while the modulo of n times n is not equal to 269696
} while (n * n % 1000_000 != 269696);
// show the result
System.out.println(n);
}
} |
Balanced brackets | Java 1.5+ | '''Task''':
* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order.
* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
;Examples:
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| import java.util.ArrayDeque;
import java.util.Deque;
public class BalancedBrackets {
public static boolean areSquareBracketsBalanced(String expr) {
return isBalanced(expr, "", "", "[", "]", false);
}
public static boolean areBracketsBalanced(String expr) {
return isBalanced(expr, "", "", "{([", "})]", false);
}
public static boolean areStringAndBracketsBalanced(String expr) {
return isBalanced(expr, "'\"", "\\\\", "{([", "})]", true);
}
public static boolean isBalanced(String expr, String lit, String esc, String obr, String cbr, boolean other) {
boolean[] inLit = new boolean[lit.length()];
Deque<Character> stack = new ArrayDeque<Character>();
for (int i=0; i<expr.length(); i+=1) {
char c = get(expr, i);
int x;
if ((x = indexOf(inLit, true)) != -1) {
if (c == get(lit, x) && get(expr, i-1) != get(esc, x)) inLit[x] = false;
}
else if ((x = indexOf(lit, c)) != -1)
inLit[x] = true;
else if ((x = indexOf(obr, c)) != -1)
stack.push(get(cbr, x));
else if (indexOf(cbr, c) != -1) {
if (stack.isEmpty() || stack.pop() != c) return false;
}
else if (!other)
return false;
}
return stack.isEmpty();
}
static int indexOf(boolean[] a, boolean b) {
for (int i=0; i<a.length; i+=1) if (a[i] == b) return i;
return -1;
}
static int indexOf(String s, char c) {
return s.indexOf(c);
}
static char get(String s, int i) {
return s.charAt(i);
}
public static void main(String[] args) {
System.out.println("With areSquareBracketsBalanced:");
for (String s: new String[] {
"", "[]", "[][]", "[[][]]", "][", "][][", "[]][[]", "[", "]"
}
) {
System.out.printf("%s: %s\n", s, areSquareBracketsBalanced(s));
}
System.out.println("\nBut also with areStringAndBracketsBalanced:");
for (String s: new String[] {
"x[]", "[x]", "[]x", "([{}])", "([{}]()", "([{ '([{\\'([{' \"([{\\\"([{\" }])",
}
) {
System.out.printf("%s: %s\n", s, areStringAndBracketsBalanced(s));
}
}
} |
Balanced ternary | Java | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1.
;Examples:
Decimal 11 = 32 + 31 - 30, thus it can be written as "++-"
Decimal 6 = 32 - 31 + 0 x 30, thus it can be written as "+-0"
;Task:
Implement balanced ternary representation of integers with the following:
# Support arbitrarily large integers, both positive and negative;
# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.
# Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
'''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-":
* write out ''a'', ''b'' and ''c'' in decimal notation;
* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.
'''Note:''' The pages floating point balanced ternary.
| /*
* Test case
* With balanced ternaries a from string "+-0++0+", b from native integer -436, c "+-++-":
* Write out a, b and c in decimal notation;
* Calculate a × (b − c), write out the result in both ternary and decimal notations.
*/
public class BalancedTernary
{
public static void main(String[] args)
{
BTernary a=new BTernary("+-0++0+");
BTernary b=new BTernary(-436);
BTernary c=new BTernary("+-++-");
System.out.println("a="+a.intValue());
System.out.println("b="+b.intValue());
System.out.println("c="+c.intValue());
System.out.println();
//result=a*(b-c)
BTernary result=a.mul(b.sub(c));
System.out.println("result= "+result+" "+result.intValue());
}
public static class BTernary
{
String value;
public BTernary(String s)
{
int i=0;
while(s.charAt(i)=='0')
i++;
this.value=s.substring(i);
}
public BTernary(int v)
{
this.value="";
this.value=convertToBT(v);
}
private String convertToBT(int v)
{
if(v<0)
return flip(convertToBT(-v));
if(v==0)
return "";
int rem=mod3(v);
if(rem==0)
return convertToBT(v/3)+"0";
if(rem==1)
return convertToBT(v/3)+"+";
if(rem==2)
return convertToBT((v+1)/3)+"-";
return "You can't see me";
}
private String flip(String s)
{
String flip="";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='+')
flip+='-';
else if(s.charAt(i)=='-')
flip+='+';
else
flip+='0';
}
return flip;
}
private int mod3(int v)
{
if(v>0)
return v%3;
v=v%3;
return (v+3)%3;
}
public int intValue()
{
int sum=0;
String s=this.value;
for(int i=0;i<s.length();i++)
{
char c=s.charAt(s.length()-i-1);
int dig=0;
if(c=='+')
dig=1;
else if(c=='-')
dig=-1;
sum+=dig*Math.pow(3, i);
}
return sum;
}
public BTernary add(BTernary that)
{
String a=this.value;
String b=that.value;
String longer=a.length()>b.length()?a:b;
String shorter=a.length()>b.length()?b:a;
while(shorter.length()<longer.length())
shorter=0+shorter;
a=longer;
b=shorter;
char carry='0';
String sum="";
for(int i=0;i<a.length();i++)
{
int place=a.length()-i-1;
String digisum=addDigits(a.charAt(place),b.charAt(place),carry);
if(digisum.length()!=1)
carry=digisum.charAt(0);
else
carry='0';
sum=digisum.charAt(digisum.length()-1)+sum;
}
sum=carry+sum;
return new BTernary(sum);
}
private String addDigits(char a,char b,char carry)
{
String sum1=addDigits(a,b);
String sum2=addDigits(sum1.charAt(sum1.length()-1),carry);
//System.out.println(carry+" "+sum1+" "+sum2);
if(sum1.length()==1)
return sum2;
if(sum2.length()==1)
return sum1.charAt(0)+sum2;
return sum1.charAt(0)+"";
}
private String addDigits(char a,char b)
{
String sum="";
if(a=='0')
sum=b+"";
else if (b=='0')
sum=a+"";
else if(a=='+')
{
if(b=='+')
sum="+-";
else
sum="0";
}
else
{
if(b=='+')
sum="0";
else
sum="-+";
}
return sum;
}
public BTernary neg()
{
return new BTernary(flip(this.value));
}
public BTernary sub(BTernary that)
{
return this.add(that.neg());
}
public BTernary mul(BTernary that)
{
BTernary one=new BTernary(1);
BTernary zero=new BTernary(0);
BTernary mul=new BTernary(0);
int flipflag=0;
if(that.compareTo(zero)==-1)
{
that=that.neg();
flipflag=1;
}
for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one))
mul=mul.add(this);
if(flipflag==1)
mul=mul.neg();
return mul;
}
public boolean equals(BTernary that)
{
return this.value.equals(that.value);
}
public int compareTo(BTernary that)
{
if(this.intValue()>that.intValue())
return 1;
else if(this.equals(that))
return 0;
return -1;
}
public String toString()
{
return value;
}
}
}
|
Barnsley fern | Java 8 | A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
;Task:
Create this fractal fern, using the following transformations:
* f1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
* f2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = -0.04 xn + 0.85 yn + 1.6
* f3 (chosen 7% of the time)
xn + 1 = 0.2 xn - 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
* f4 (chosen 7% of the time)
xn + 1 = -0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class BarnsleyFern extends JPanel {
BufferedImage img;
public BarnsleyFern() {
final int dim = 640;
setPreferredSize(new Dimension(dim, dim));
setBackground(Color.white);
img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);
createFern(dim, dim);
}
void createFern(int w, int h) {
double x = 0;
double y = 0;
for (int i = 0; i < 200_000; i++) {
double tmpx, tmpy;
double r = Math.random();
if (r <= 0.01) {
tmpx = 0;
tmpy = 0.16 * y;
} else if (r <= 0.08) {
tmpx = 0.2 * x - 0.26 * y;
tmpy = 0.23 * x + 0.22 * y + 1.6;
} else if (r <= 0.15) {
tmpx = -0.15 * x + 0.28 * y;
tmpy = 0.26 * x + 0.24 * y + 0.44;
} else {
tmpx = 0.85 * x + 0.04 * y;
tmpy = -0.04 * x + 0.85 * y + 1.6;
}
x = tmpx;
y = tmpy;
img.setRGB((int) Math.round(w / 2 + x * w / 11),
(int) Math.round(h - y * h / 11), 0xFF32CD32);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(img, 0, 0, null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Barnsley Fern");
f.setResizable(false);
f.add(new BarnsleyFern(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Base64 decode data | Java | See [[Base64 encode data]].
Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| void decodeToFile(String path, byte[] bytes) throws IOException {
try (FileOutputStream stream = new FileOutputStream(path)) {
byte[] decoded = Base64.getDecoder().decode(bytes);
stream.write(decoded, 0, decoded.length);
}
}
|
Base64 decode data | Java from Kotlin | See [[Base64 encode data]].
Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Decode {
public static void main(String[] args) {
String data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=";
Base64.Decoder decoder = Base64.getDecoder();
byte[] decoded = decoder.decode(data);
String decodedStr = new String(decoded, StandardCharsets.UTF_8);
System.out.println(decodedStr);
}
} |
Bell numbers | Java from Kotlin | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.
;So:
:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''
:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''
:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''
:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''
: and so on.
A simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
;Task:
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence.
If you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.
;See also:
:* '''OEIS:A000110 Bell or exponential numbers'''
:* '''OEIS:A011971 Aitken's array'''
| import java.util.ArrayList;
import java.util.List;
public class Bell {
private static class BellTriangle {
private List<Integer> arr;
BellTriangle(int n) {
int length = n * (n + 1) / 2;
arr = new ArrayList<>(length);
for (int i = 0; i < length; ++i) {
arr.add(0);
}
set(1, 0, 1);
for (int i = 2; i <= n; ++i) {
set(i, 0, get(i - 1, i - 2));
for (int j = 1; j < i; ++j) {
int value = get(i, j - 1) + get(i - 1, j - 1);
set(i, j, value);
}
}
}
private int index(int row, int col) {
if (row > 0 && col >= 0 && col < row) {
return row * (row - 1) / 2 + col;
} else {
throw new IllegalArgumentException();
}
}
public int get(int row, int col) {
int i = index(row, col);
return arr.get(i);
}
public void set(int row, int col, int value) {
int i = index(row, col);
arr.set(i, value);
}
}
public static void main(String[] args) {
final int rows = 15;
BellTriangle bt = new BellTriangle(rows);
System.out.println("First fifteen Bell numbers:");
for (int i = 0; i < rows; ++i) {
System.out.printf("%2d: %d\n", i + 1, bt.get(i + 1, 0));
}
for (int i = 1; i <= 10; ++i) {
System.out.print(bt.get(i, 0));
for (int j = 1; j < i; ++j) {
System.out.printf(", %d", bt.get(i, j));
}
System.out.println();
}
}
} |
Benford's law | Java | {{Wikipedia|Benford's_law}}
'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability
:::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right)
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
;See also:
* numberphile.com.
* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.
| import java.math.BigInteger;
import java.util.Locale;
public class BenfordsLaw {
private static BigInteger[] generateFibonacci(int n) {
BigInteger[] fib = new BigInteger[n];
fib[0] = BigInteger.ONE;
fib[1] = BigInteger.ONE;
for (int i = 2; i < fib.length; i++) {
fib[i] = fib[i - 2].add(fib[i - 1]);
}
return fib;
}
public static void main(String[] args) {
BigInteger[] numbers = generateFibonacci(1000);
int[] firstDigits = new int[10];
for (BigInteger number : numbers) {
firstDigits[Integer.valueOf(number.toString().substring(0, 1))]++;
}
for (int i = 1; i < firstDigits.length; i++) {
System.out.printf(Locale.ROOT, "%d %10.6f %10.6f%n",
i, (double) firstDigits[i] / numbers.length, Math.log10(1.0 + 1.0 / i));
}
}
} |
Best shuffle | Java | Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did ''not'' change.
;Example:
tree, eetr, (0)
;Test cases:
abracadabra
seesaw
elk
grrrrrr
up
a
;Related tasks
* [[Anagrams/Deranged anagrams]]
* [[Permutations/Derangements]]
| import java.util.Random;
public class BestShuffle {
private final static Random rand = new Random();
public static void main(String[] args) {
String[] words = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"};
for (String w : words)
System.out.println(bestShuffle(w));
}
public static String bestShuffle(final String s1) {
char[] s2 = s1.toCharArray();
shuffle(s2);
for (int i = 0; i < s2.length; i++) {
if (s2[i] != s1.charAt(i))
continue;
for (int j = 0; j < s2.length; j++) {
if (s2[i] != s2[j] && s2[i] != s1.charAt(j) && s2[j] != s1.charAt(i)) {
char tmp = s2[i];
s2[i] = s2[j];
s2[j] = tmp;
break;
}
}
}
return s1 + " " + new String(s2) + " (" + count(s1, s2) + ")";
}
public static void shuffle(char[] text) {
for (int i = text.length - 1; i > 0; i--) {
int r = rand.nextInt(i + 1);
char tmp = text[i];
text[i] = text[r];
text[r] = tmp;
}
}
private static int count(final String s1, final char[] s2) {
int count = 0;
for (int i = 0; i < s2.length; i++)
if (s1.charAt(i) == s2[i])
count++;
return count;
}
} |
Bin given limits | Java | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..''
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
;Task:
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will ''print the limit of each bin
together with the count of items that fell in the range''.
Assume the numbers to bin are too large to practically sort.
;Task examples:
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Bins {
public static <T extends Comparable<? super T>> int[] bins(
List<? extends T> limits, Iterable<? extends T> data) {
int[] result = new int[limits.size() + 1];
for (T n : data) {
int i = Collections.binarySearch(limits, n);
if (i >= 0) {
// n == limits[i]; we put it in right-side bin (i+1)
i = i+1;
} else {
// n is not in limits and i is ~(insertion point)
i = ~i;
}
result[i]++;
}
return result;
}
public static void printBins(List<?> limits, int[] bins) {
int n = limits.size();
if (n == 0) {
return;
}
assert n+1 == bins.length;
System.out.printf(" < %3s: %2d\n", limits.get(0), bins[0]);
for (int i = 1; i < n; i++) {
System.out.printf(">= %3s and < %3s: %2d\n", limits.get(i-1), limits.get(i), bins[i]);
}
System.out.printf(">= %3s : %2d\n", limits.get(n-1), bins[n]);
}
public static void main(String[] args) {
List<Integer> limits = Arrays.asList(23, 37, 43, 53, 67, 83);
List<Integer> data = Arrays.asList(
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55);
System.out.println("Example 1:");
printBins(limits, bins(limits, data));
limits = Arrays.asList(14, 18, 249, 312, 389,
392, 513, 591, 634, 720);
data = Arrays.asList(
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749);
System.out.println();
System.out.println("Example 2:");
printBins(limits, bins(limits, data));
}
} |
Bioinformatics/Sequence mutation | Java | Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
# Choosing a random base position in the sequence.
# Mutate the sequence by doing one of either:
## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
## '''D'''elete the chosen base at the position.
## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.
# Randomly generate a test DNA sequence of at least 200 bases
# "Pretty print" the sequence and a count of its size, and the count of each base in the sequence
# Mutate the sequence ten times.
# "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
;Extra credit:
* Give more information on the individual mutations applied.
* Allow mutations to be weighted and/or chosen.
| import java.util.Arrays;
import java.util.Random;
public class SequenceMutation {
public static void main(String[] args) {
SequenceMutation sm = new SequenceMutation();
sm.setWeight(OP_CHANGE, 3);
String sequence = sm.generateSequence(250);
System.out.println("Initial sequence:");
printSequence(sequence);
int count = 10;
for (int i = 0; i < count; ++i)
sequence = sm.mutateSequence(sequence);
System.out.println("After " + count + " mutations:");
printSequence(sequence);
}
public SequenceMutation() {
totalWeight_ = OP_COUNT;
Arrays.fill(operationWeight_, 1);
}
public String generateSequence(int length) {
char[] ch = new char[length];
for (int i = 0; i < length; ++i)
ch[i] = getRandomBase();
return new String(ch);
}
public void setWeight(int operation, int weight) {
totalWeight_ -= operationWeight_[operation];
operationWeight_[operation] = weight;
totalWeight_ += weight;
}
public String mutateSequence(String sequence) {
char[] ch = sequence.toCharArray();
int pos = random_.nextInt(ch.length);
int operation = getRandomOperation();
if (operation == OP_CHANGE) {
char b = getRandomBase();
System.out.println("Change base at position " + pos + " from "
+ ch[pos] + " to " + b);
ch[pos] = b;
} else if (operation == OP_ERASE) {
System.out.println("Erase base " + ch[pos] + " at position " + pos);
char[] newCh = new char[ch.length - 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1);
ch = newCh;
} else if (operation == OP_INSERT) {
char b = getRandomBase();
System.out.println("Insert base " + b + " at position " + pos);
char[] newCh = new char[ch.length + 1];
System.arraycopy(ch, 0, newCh, 0, pos);
System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos);
newCh[pos] = b;
ch = newCh;
}
return new String(ch);
}
public static void printSequence(String sequence) {
int[] count = new int[BASES.length];
for (int i = 0, n = sequence.length(); i < n; ++i) {
if (i % 50 == 0) {
if (i != 0)
System.out.println();
System.out.printf("%3d: ", i);
}
char ch = sequence.charAt(i);
System.out.print(ch);
for (int j = 0; j < BASES.length; ++j) {
if (BASES[j] == ch) {
++count[j];
break;
}
}
}
System.out.println();
System.out.println("Base counts:");
int total = 0;
for (int j = 0; j < BASES.length; ++j) {
total += count[j];
System.out.print(BASES[j] + ": " + count[j] + ", ");
}
System.out.println("Total: " + total);
}
private char getRandomBase() {
return BASES[random_.nextInt(BASES.length)];
}
private int getRandomOperation() {
int n = random_.nextInt(totalWeight_), op = 0;
for (int weight = 0; op < OP_COUNT; ++op) {
weight += operationWeight_[op];
if (n < weight)
break;
}
return op;
}
private final Random random_ = new Random();
private int[] operationWeight_ = new int[OP_COUNT];
private int totalWeight_ = 0;
private static final int OP_CHANGE = 0;
private static final int OP_ERASE = 1;
private static final int OP_INSERT = 2;
private static final int OP_COUNT = 3;
private static final char[] BASES = {'A', 'C', 'G', 'T'};
} |
Bioinformatics/base count | Java | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
;Task:
:* "Pretty print" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence
:* print the total count of each base in the string.
| import java.util.HashMap;
import java.util.Map;
public class orderedSequence {
public static void main(String[] args) {
Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
gene.runSequence();
}
}
/** Separate class for defining behaviors */
public class Sequence {
private final String seq;
public Sequence(String sq) {
this.seq = sq;
}
/** print the organized structure of the sequence */
public void prettyPrint() {
System.out.println("Sequence:");
int i = 0;
for ( ; i < seq.length() - 50 ; i += 50) {
System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
}
System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
}
/** display a base vs. frequency chart */
public void displayCount() {
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0 ; i < seq.length() ; ++i) {
counter.merge(seq.charAt(i), 1, Integer::sum);
}
System.out.println("Base vs. Count:");
counter.forEach(
key, value -> System.out.printf("%5s : %s\n", key, value));
System.out.printf("%5s: %s\n", "SUM", seq.length());
}
public void runSequence() {
this.prettyPrint();
this.displayCount();
}
}
|
Bitcoin/address validation | Java | Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
:::* 0 zero
:::* O uppercase oh
:::* I uppercase eye
:::* l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
* the first byte is the version number, which will be zero for this task ;
* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for [[SHA-256]].
;Example of a bitcoin address:
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class BitcoinAddressValidator {
private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
public static boolean validateBitcoinAddress(String addr) {
if (addr.length() < 26 || addr.length() > 35)
return false;
byte[] decoded = decodeBase58To25Bytes(addr);
if (decoded == null)
return false;
byte[] hash1 = sha256(Arrays.copyOfRange(decoded, 0, 21));
byte[] hash2 = sha256(hash1);
return Arrays.equals(Arrays.copyOfRange(hash2, 0, 4), Arrays.copyOfRange(decoded, 21, 25));
}
private static byte[] decodeBase58To25Bytes(String input) {
BigInteger num = BigInteger.ZERO;
for (char t : input.toCharArray()) {
int p = ALPHABET.indexOf(t);
if (p == -1)
return null;
num = num.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(p));
}
byte[] result = new byte[25];
byte[] numBytes = num.toByteArray();
System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length);
return result;
}
private static byte[] sha256(byte[] data) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data);
return md.digest();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
public static void main(String[] args) {
assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", true);
assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", false);
assertBitcoin("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", true);
assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", false);
assertBitcoin("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false);
assertBitcoin("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false);
assertBitcoin("BZbvjr", false);
assertBitcoin("i55j", false);
assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", false);
assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", false);
assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", false);
assertBitcoin("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", false);
assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I", false);
}
private static void assertBitcoin(String address, boolean expected) {
boolean actual = validateBitcoinAddress(address);
if (actual != expected)
throw new AssertionError(String.format("Expected %s for %s, but got %s.", expected, address, actual));
}
} |
Box the compass | Java | Avast me hearties!
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
;Task description:
# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
;Notes;
* The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| enum Compass {
N, NbE, NNE, NEbN, NE, NEbE, ENE, EbN,
E, EbS, ESE, SEbE, SE, SEbS, SSE, SbE,
S, SbW, SSW, SWbS, SW, SWbW, WSW, WbS,
W, WbN, WNW, NWbW, NW, NWbN, NNW, NbW;
float midpoint() {
float midpoint = (360 / 32f) * ordinal();
return midpoint == 0 ? 360 : midpoint;
}
float[] bounds() {
float bound = (360 / 32f) / 2f;
float midpoint = midpoint();
float boundA = midpoint - bound;
float boundB = midpoint + bound;
if (boundB > 360) boundB -= 360;
return new float[] { boundA, boundB };
}
static Compass parse(float degrees) {
float[] bounds;
float[] boundsN = N.bounds();
for (Compass value : Compass.values()) {
bounds = value.bounds();
if (degrees >= boundsN[0] || degrees < boundsN[1])
return N;
if (degrees >= bounds[0] && degrees < bounds[1])
return value;
}
return null;
}
@Override
public String toString() {
String[] strings = new String[name().length()];
int index = 0;
for (char letter : name().toCharArray()) {
switch (letter) {
case 'N' -> strings[index] = "north";
case 'E' -> strings[index] = "east";
case 'S' -> strings[index] = "south";
case 'W' -> strings[index] = "west";
case 'b' -> strings[index] = "by";
}
index++;
}
String string
= strings[0].substring(0, 1).toUpperCase() +
strings[0].substring(1);
switch (strings.length) {
case 2 -> string += strings[1];
case 3 -> {
if (strings[1].equals("by")) {
string += " %s %s".formatted(strings[1], strings[2]);
} else {
string += "-%s%s".formatted(strings[1], strings[2]);
}
}
case 4 -> {
string += String.join(" ", strings[1], strings[2], strings[3]);
}
}
return string;
}
}
|
Brazilian numbers | Java | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.
;E.G.:
:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.
:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.
:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.
:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.
:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.
:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.
:* ''and so on...''
All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.
More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2
;Task:
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
:* the first '''20''' Brazilian numbers;
:* the first '''20 odd''' Brazilian numbers;
:* the first '''20 prime''' Brazilian numbers;
;See also:
:* '''OEIS:A125134 - Brazilian numbers'''
:* '''OEIS:A257521 - Odd Brazilian numbers'''
:* '''OEIS:A085104 - Prime Brazilian numbers'''
| import java.math.BigInteger;
import java.util.List;
public class Brazilian {
private static final List<Integer> primeList = List.of(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281,
283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389,
397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491,
499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607,
611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719,
727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829,
839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949,
953, 967, 971, 977, 983, 991, 997
);
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (Integer prime : primeList) {
if (n == prime) {
return true;
}
if (n % prime == 0) {
return false;
}
if (prime * prime > n) {
return true;
}
}
BigInteger bi = BigInteger.valueOf(n);
return bi.isProbablePrime(10);
}
private static boolean sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
private static boolean isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0) return true;
for (int b = 2; b < n - 1; ++b) {
if (sameDigits(n, b)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
for (String kind : List.of("", "odd ", "prime ")) {
boolean quiet = false;
int bigLim = 99_999;
int limit = 20;
System.out.printf("First %d %sBrazilian numbers:\n", limit, kind);
int c = 0;
int n = 7;
while (c < bigLim) {
if (isBrazilian(n)) {
if (!quiet) System.out.printf("%d ", n);
if (++c == limit) {
System.out.println("\n");
quiet = true;
}
}
if (quiet && !"".equals(kind)) continue;
switch (kind) {
case "":
n++;
break;
case "odd ":
n += 2;
break;
case "prime ":
do {
n += 2;
} while (!isPrime(n));
break;
default:
throw new AssertionError("Oops");
}
}
if ("".equals(kind)) {
System.out.printf("The %dth Brazilian number is: %d\n\n", bigLim + 1, n);
}
}
}
} |
Break OO privacy | Java | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| Example example = new Example();
Method method = example.getClass().getDeclaredMethod("stringB");
method.setAccessible(true);
String stringA = example.stringA;
String stringB = (String) method.invoke(example);
System.out.println(stringA + " " + stringB);
|
Brilliant numbers | Java from C++ | '''Brilliant numbers''' are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers '''that both have the same number of digits when expressed in base 10'''.
''Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.''
;E.G.
* '''3 x 3''' (9) is a brilliant number.
* '''2 x 7''' (14) is a brilliant number.
* '''113 x 691''' (78083) is a brilliant number.
* '''2 x 31''' (62) is semiprime, but is '''not''' a brilliant number (different number of digits in the two factors).
;Task
* Find and display the first 100 brilliant numbers.
* For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).
;Stretch
* Continue for larger orders of magnitude.
;See also
;* Numbers Aplenty - Brilliant numbers
;* OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits
| import java.util.*;
public class BrilliantNumbers {
public static void main(String[] args) {
var primesByDigits = getPrimesByDigits(100000000);
System.out.println("First 100 brilliant numbers:");
List<Integer> brilliantNumbers = new ArrayList<>();
for (var primes : primesByDigits) {
int n = primes.size();
for (int i = 0; i < n; ++i) {
int prime1 = primes.get(i);
for (int j = i; j < n; ++j) {
int prime2 = primes.get(j);
brilliantNumbers.add(prime1 * prime2);
}
}
if (brilliantNumbers.size() >= 100)
break;
}
Collections.sort(brilliantNumbers);
for (int i = 0; i < 100; ++i) {
char c = (i + 1) % 10 == 0 ? '\n' : ' ';
System.out.printf("%,5d%c", brilliantNumbers.get(i), c);
}
System.out.println();
long power = 10;
long count = 0;
for (int p = 1; p < 2 * primesByDigits.size(); ++p) {
var primes = primesByDigits.get(p / 2);
long position = count + 1;
long minProduct = 0;
int n = primes.size();
for (int i = 0; i < n; ++i) {
long prime1 = primes.get(i);
var primes2 = primes.subList(i, n);
int q = (int)((power + prime1 - 1) / prime1);
int j = Collections.binarySearch(primes2, q);
if (j == n)
continue;
if (j < 0)
j = -(j + 1);
long prime2 = primes2.get(j);
long product = prime1 * prime2;
if (minProduct == 0 || product < minProduct)
minProduct = product;
position += j;
if (prime1 >= prime2)
break;
}
System.out.printf("First brilliant number >= 10^%d is %,d at position %,d\n",
p, minProduct, position);
power *= 10;
if (p % 2 == 1) {
long size = primes.size();
count += size * (size + 1) / 2;
}
}
}
private static List<List<Integer>> getPrimesByDigits(int limit) {
PrimeGenerator primeGen = new PrimeGenerator(100000, 100000);
List<List<Integer>> primesByDigits = new ArrayList<>();
List<Integer> primes = new ArrayList<>();
for (int p = 10; p <= limit; ) {
int prime = primeGen.nextPrime();
if (prime > p) {
primesByDigits.add(primes);
primes = new ArrayList<>();
p *= 10;
}
primes.add(prime);
}
return primesByDigits;
}
} |
Burrows–Wheeler transform | Java from Kotlin | {{Wikipedia|Burrows-Wheeler_transform}}
The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows-Wheeler transform
| import java.util.ArrayList;
import java.util.List;
public class BWT {
private static final String STX = "\u0002";
private static final String ETX = "\u0003";
private static String bwt(String s) {
if (s.contains(STX) || s.contains(ETX)) {
throw new IllegalArgumentException("String cannot contain STX or ETX");
}
String ss = STX + s + ETX;
List<String> table = new ArrayList<>();
for (int i = 0; i < ss.length(); i++) {
String before = ss.substring(i);
String after = ss.substring(0, i);
table.add(before + after);
}
table.sort(String::compareTo);
StringBuilder sb = new StringBuilder();
for (String str : table) {
sb.append(str.charAt(str.length() - 1));
}
return sb.toString();
}
private static String ibwt(String r) {
int len = r.length();
List<String> table = new ArrayList<>();
for (int i = 0; i < len; ++i) {
table.add("");
}
for (int j = 0; j < len; ++j) {
for (int i = 0; i < len; ++i) {
table.set(i, r.charAt(i) + table.get(i));
}
table.sort(String::compareTo);
}
for (String row : table) {
if (row.endsWith(ETX)) {
return row.substring(1, len - 1);
}
}
return "";
}
private static String makePrintable(String s) {
// substitute ^ for STX and | for ETX to print results
return s.replace(STX, "^").replace(ETX, "|");
}
public static void main(String[] args) {
List<String> tests = List.of(
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
);
for (String test : tests) {
System.out.println(makePrintable(test));
System.out.print(" --> ");
String t = "";
try {
t = bwt(test);
System.out.println(makePrintable(t));
} catch (IllegalArgumentException e) {
System.out.println("ERROR: " + e.getMessage());
}
String r = ibwt(t);
System.out.printf(" --> %s\n\n", r);
}
}
} |
CSV data manipulation | Java | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
;Task:
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| import java.io.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class CSV {
private HashMap<Point, String> _map = new HashMap<Point, String>();
private int _cols;
private int _rows;
public void open(File file) throws FileNotFoundException, IOException {
open(file, ',');
}
public void open(File file, char delimiter)
throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(file);
scanner.useDelimiter(Character.toString(delimiter));
clear();
while(scanner.hasNextLine()) {
String[] values = scanner.nextLine().split(Character.toString(delimiter));
int col = 0;
for ( String value: values ) {
_map.put(new Point(col, _rows), value);
_cols = Math.max(_cols, ++col);
}
_rows++;
}
scanner.close();
}
public void save(File file) throws IOException {
save(file, ',');
}
public void save(File file, char delimiter) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int row = 0; row < _rows; row++) {
for (int col = 0; col < _cols; col++) {
Point key = new Point(col, row);
if (_map.containsKey(key)) {
bw.write(_map.get(key));
}
if ((col + 1) < _cols) {
bw.write(delimiter);
}
}
bw.newLine();
}
bw.flush();
bw.close();
}
public String get(int col, int row) {
String val = "";
Point key = new Point(col, row);
if (_map.containsKey(key)) {
val = _map.get(key);
}
return val;
}
public void put(int col, int row, String value) {
_map.put(new Point(col, row), value);
_cols = Math.max(_cols, col+1);
_rows = Math.max(_rows, row+1);
}
public void clear() {
_map.clear();
_cols = 0;
_rows = 0;
}
public int rows() {
return _rows;
}
public int cols() {
return _cols;
}
public static void main(String[] args) {
try {
CSV csv = new CSV();
csv.open(new File("test_in.csv"));
csv.put(0, 0, "Column0");
csv.put(1, 1, "100");
csv.put(2, 2, "200");
csv.put(3, 3, "300");
csv.put(4, 4, "400");
csv.save(new File("test_out.csv"));
} catch (Exception e) {
}
}
} |
CSV to HTML translation | Java | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be ''escaped'' when converted to HTML
;Task:
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
: Character,Speech
: The multitude,The messiah! Show us the messiah!
: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!
: The multitude,Who are you?
: Brians mother,I'm his mother; that's who!
: The multitude,Behold his mother! Behold his mother!
;Extra credit:
''Optionally'' allow special formatting for the first row of the table as if it is the tables header row
(via preferably; CSS if you must).
| import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
class Csv2Html {
public static String escapeChars(String lineIn) {
StringBuilder sb = new StringBuilder();
int lineLength = lineIn.length();
for (int i = 0; i < lineLength; i++) {
char c = lineIn.charAt(i);
switch (c) {
case '"':
sb.append(""");
break;
case '&':
sb.append("&");
break;
case '\'':
sb.append("'");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
default: sb.append(c);
}
}
return sb.toString();
}
public static void tableHeader(PrintStream ps, String[] columns) {
ps.print("<tr>");
for (int i = 0; i < columns.length; i++) {
ps.print("<th>");
ps.print(columns[i]);
ps.print("</th>");
}
ps.println("</tr>");
}
public static void tableRow(PrintStream ps, String[] columns) {
ps.print("<tr>");
for (int i = 0; i < columns.length; i++) {
ps.print("<td>");
ps.print(columns[i]);
ps.print("</td>");
}
ps.println("</tr>");
}
public static void main(String[] args) throws Exception {
boolean withTableHeader = (args.length != 0);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
PrintStream stdout = System.out;
stdout.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
stdout.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
stdout.println("<head><meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\"/>");
stdout.println("<title>Csv2Html</title>");
stdout.println("<style type=\"text/css\">");
stdout.println("body{background-color:#FFF;color:#000;font-family:OpenSans,sans-serif;font-size:10px;}");
stdout.println("table{border:0.2em solid #2F6FAB;border-collapse:collapse;}");
stdout.println("th{border:0.15em solid #2F6FAB;padding:0.5em;background-color:#E9E9E9;}");
stdout.println("td{border:0.1em solid #2F6FAB;padding:0.5em;background-color:#F9F9F9;}</style>");
stdout.println("</head><body><h1>Csv2Html</h1>");
stdout.println("<table>");
String stdinLine;
boolean firstLine = true;
while ((stdinLine = br.readLine()) != null) {
String[] columns = escapeChars(stdinLine).split(",");
if (withTableHeader == true && firstLine == true) {
tableHeader(stdout, columns);
firstLine = false;
} else {
tableRow(stdout, columns);
}
}
stdout.println("</table></body></html>");
}
}
|
Calculating the value of e | Java | Calculate the value of ''e''.
(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)
See details: Calculating the value of e
| BigDecimal e(BigInteger limit, int scale) {
BigDecimal e = BigDecimal.ONE.setScale(scale, HALF_UP);
BigDecimal n;
BigInteger term = BigInteger.ONE;
while (term.compareTo(limit) <= 0) {
n = new BigDecimal(String.valueOf(factorial(term)));
e = e.add(BigDecimal.ONE.divide(n, scale, HALF_UP));
term = term.add(BigInteger.ONE);
}
return e;
}
BigInteger factorial(BigInteger value) {
if (value.compareTo(BigInteger.ONE) > 0) {
return value.multiply(factorial(value.subtract(BigInteger.ONE)));
} else {
return BigInteger.ONE;
}
}
|
Calculating the value of e | Java from Kotlin | Calculate the value of ''e''.
(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)
See details: Calculating the value of e
| public class CalculateE {
public static final double EPSILON = 1.0e-15;
public static void main(String[] args) {
long fact = 1;
double e = 2.0;
int n = 2;
double e0;
do {
e0 = e;
fact *= n++;
e += 1.0 / fact;
} while (Math.abs(e - e0) >= EPSILON);
System.out.printf("e = %.15f\n", e);
}
} |
Calkin-Wilf sequence | Java | The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
{{math|a1}} = {{math|1}}
{{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1
;Task part 1:
* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to use a rational number data type.
It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.
It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:
{{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}}
;Example:
The fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''',
which means '''9/4''' appears as the '''35th''' term of the sequence.
;Task part 2:
* Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence.
;See also:
* Wikipedia entry: Calkin-Wilf tree
* [[Continued fraction]]
* [[Continued fraction/Arithmetic/Construct from rational number]]
| import java.util.ArrayDeque;
import java.util.Deque;
public final class CalkinWilfSequence {
public static void main(String[] aArgs) {
Rational term = Rational.ONE;
System.out.println("First 20 terms of the Calkin-Wilf sequence are:");
for ( int i = 1; i <= 20; i++ ) {
System.out.println(String.format("%2d", i) + ": " + term);
term = nextCalkinWilf(term);
}
System.out.println();
Rational rational = new Rational(83_116, 51_639);
System.out.println(" " + rational + " is the " + termIndex(rational) + "th term of the sequence.");
}
private static Rational nextCalkinWilf(Rational aTerm) {
Rational divisor = Rational.TWO.multiply(aTerm.floor()).add(Rational.ONE).subtract(aTerm);
return Rational.ONE.divide(divisor);
}
private static long termIndex(Rational aRational) {
long result = 0;
long binaryDigit = 1;
long power = 0;
for ( long term : continuedFraction(aRational) ) {
for ( long i = 0; i < term; power++, i++ ) {
result |= ( binaryDigit << power );
}
binaryDigit = ( binaryDigit == 0 ) ? 1 : 0;
}
return result;
}
private static Deque<Long> continuedFraction(Rational aRational) {
long numerator = aRational.numerator();
long denominator = aRational.denominator();
Deque<Long> result = new ArrayDeque<Long>();
while ( numerator != 1 ) {
result.addLast(numerator / denominator);
long copyNumerator = numerator;
numerator = denominator;
denominator = copyNumerator % denominator;
}
if ( ! result.isEmpty() && result.size() % 2 == 0 ) {
final long back = result.removeLast();
result.addLast(back - 1);
result.addLast(1L);
}
return result;
}
}
final class Rational {
public Rational(long aNumerator, long aDenominator) {
if ( aDenominator == 0 ) {
throw new ArithmeticException("Denominator cannot be zero");
}
if ( aNumerator == 0 ) {
aDenominator = 1;
}
if ( aDenominator < 0 ) {
numer = -aNumerator;
denom = -aDenominator;
} else {
numer = aNumerator;
denom = aDenominator;
}
final long gcd = gcd(numer, denom);
numer = numer / gcd;
denom = denom / gcd;
}
public Rational add(Rational aOther) {
return new Rational(numer * aOther.denom + aOther.numer * denom, denom * aOther.denom);
}
public Rational subtract(Rational aOther) {
return new Rational(numer * aOther.denom - aOther.numer * denom, denom * aOther.denom);
}
public Rational multiply(Rational aOther) {
return new Rational(numer * aOther.numer, denom * aOther.denom);
}
public Rational divide(Rational aOther) {
return new Rational(numer * aOther.denom, denom * aOther.numer);
}
public Rational floor() {
return new Rational(numer / denom, 1);
}
public long numerator() {
return numer;
}
public long denominator() {
return denom;
}
@Override
public String toString() {
return numer + "/" + denom;
}
public static final Rational ONE = new Rational(1, 1);
public static final Rational TWO = new Rational(2, 1);
private long gcd(long aOne, long aTwo) {
if ( aTwo == 0 ) {
return aOne;
}
return gcd(aTwo, aOne % aTwo);
}
private long numer;
private long denom;
}
|
Call a function | Java | Demonstrate the different syntax and semantics provided for calling a function.
This may include:
:* Calling a function that requires no arguments
:* Calling a function with a fixed number of arguments
:* Calling a function with optional arguments
:* Calling a function with a variable number of arguments
:* Calling a function with named arguments
:* Using a function in statement context
:* Using a function in first-class context within an expression
:* Obtaining the return value of a function
:* Distinguishing built-in functions and user-defined functions
:* Distinguishing subroutines and functions
;* Stating whether arguments are passed by value or by reference
;* Is partial application possible and how
This task is ''not'' about defining functions.
| int myMethod( Map<String,Object> params ){
return
((Integer)params.get("x")).intValue()
+ ((Integer)params.get("y")).intValue();
} |
Canonicalize CIDR | Java | Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
;Example:
Given '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''
;Explanation:
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.
The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.
;More examples for testing
36.18.154.103/12 - 36.16.0.0/12
62.62.197.11/29 - 62.62.197.8/29
67.137.119.181/4 - 64.0.0.0/4
161.214.74.21/24 - 161.214.74.0/24
184.232.176.184/18 - 184.232.128.0/18
| import java.text.MessageFormat;
import java.text.ParseException;
public class CanonicalizeCIDR {
public static void main(String[] args) {
for (String test : TESTS) {
try {
CIDR cidr = new CIDR(test);
System.out.printf("%-18s -> %s\n", test, cidr.toString());
} catch (Exception ex) {
System.err.printf("Error parsing '%s': %s\n", test, ex.getLocalizedMessage());
}
}
}
private static class CIDR {
private CIDR(int address, int maskLength) {
this.address = address;
this.maskLength = maskLength;
}
private CIDR(String str) throws Exception {
Object[] args = new MessageFormat(FORMAT).parse(str);
int address = 0;
for (int i = 0; i < 4; ++i) {
int a = ((Number)args[i]).intValue();
if (a < 0 || a > 255)
throw new Exception("Invalid IP address");
address <<= 8;
address += a;
}
int maskLength = ((Number)args[4]).intValue();
if (maskLength < 1 || maskLength > 32)
throw new Exception("Invalid mask length");
int mask = ~((1 << (32 - maskLength)) - 1);
this.address = address & mask;
this.maskLength = maskLength;
}
public String toString() {
int address = this.address;
int d = address & 0xFF;
address >>= 8;
int c = address & 0xFF;
address >>= 8;
int b = address & 0xFF;
address >>= 8;
int a = address & 0xFF;
Object[] args = { a, b, c, d, maskLength };
return new MessageFormat(FORMAT).format(args);
}
private int address;
private int maskLength;
private static final String FORMAT = "{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}";
};
private static final String[] TESTS = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
} |
Cantor set | Java from Kotlin | Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| public class App {
private static final int WIDTH = 81;
private static final int HEIGHT = 5;
private static char[][] lines;
static {
lines = new char[HEIGHT][WIDTH];
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
lines[i][j] = '*';
}
}
}
private static void cantor(int start, int len, int index) {
int seg = len / 3;
if (seg == 0) return;
for (int i = index; i < HEIGHT; i++) {
for (int j = start + seg; j < start + seg * 2; j++) {
lines[i][j] = ' ';
}
}
cantor(start, seg, index + 1);
cantor(start + seg * 2, seg, index + 1);
}
public static void main(String[] args) {
cantor(0, WIDTH, 1);
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
System.out.print(lines[i][j]);
}
System.out.println();
}
}
}
|
Cartesian product of two or more lists | Java Virtual Machine 1.8 | Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
:: {1, 2} x {} = {}
:: {} x {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}
:: {1, 2, 3} x {30} x {500, 100}
:: {1, 2, 3} x {} x {500, 100}
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CartesianProduct<V> {
public List<List<V>> product(List<List<V>> lists) {
List<List<V>> product = new ArrayList<>();
// We first create a list for each value of the first list
product(product, new ArrayList<>(), lists);
return product;
}
private void product(List<List<V>> result, List<V> existingTupleToComplete, List<List<V>> valuesToUse) {
for (V value : valuesToUse.get(0)) {
List<V> newExisting = new ArrayList<>(existingTupleToComplete);
newExisting.add(value);
// If only one column is left
if (valuesToUse.size() == 1) {
// We create a new list with the exiting tuple for each value with the value
// added
result.add(newExisting);
} else {
// If there are still several columns, we go into recursion for each value
List<List<V>> newValues = new ArrayList<>();
// We build the next level of values
for (int i = 1; i < valuesToUse.size(); i++) {
newValues.add(valuesToUse.get(i));
}
product(result, newExisting, newValues);
}
}
}
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>(Arrays.asList(new Integer[] { 1776, 1789 }));
List<Integer> list2 = new ArrayList<>(Arrays.asList(new Integer[] { 7, 12 }));
List<Integer> list3 = new ArrayList<>(Arrays.asList(new Integer[] { 4, 14, 23 }));
List<Integer> list4 = new ArrayList<>(Arrays.asList(new Integer[] { 0, 1 }));
List<List<Integer>> input = new ArrayList<>();
input.add(list1);
input.add(list2);
input.add(list3);
input.add(list4);
CartesianProduct<Integer> cartesianProduct = new CartesianProduct<>();
List<List<Integer>> product = cartesianProduct.product(input);
System.out.println(product);
}
}
|
Casting out nines | Java 8 | Task (in three parts):
;Part 1
Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.
With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.
;Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).
: note that 318682 has the same checksum as (101558 + 217124);
: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
: \mathit{co9}(x) is the residual of x mod 9;
: the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;related tasks
* [[First perfect square in base N with N unique digits]]
* [[Kaprekar numbers]]
| import java.util.*;
import java.util.stream.IntStream;
public class CastingOutNines {
public static void main(String[] args) {
System.out.println(castOut(16, 1, 255));
System.out.println(castOut(10, 1, 99));
System.out.println(castOut(17, 1, 288));
}
static List<Integer> castOut(int base, int start, int end) {
int[] ran = IntStream
.range(0, base - 1)
.filter(x -> x % (base - 1) == (x * x) % (base - 1))
.toArray();
int x = start / (base - 1);
List<Integer> result = new ArrayList<>();
while (true) {
for (int n : ran) {
int k = (base - 1) * x + n;
if (k < start)
continue;
if (k > end)
return result;
result.add(k);
}
x++;
}
}
} |
Catalan numbers/Pascal's triangle | Java from C++ | Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.
;See:
* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
;Related Tasks:
[[Pascal's triangle]]
| public class Test {
public static void main(String[] args) {
int N = 15;
int[] t = new int[N + 2];
t[1] = 1;
for (int i = 1; i <= N; i++) {
for (int j = i; j > 1; j--)
t[j] = t[j] + t[j - 1];
t[i + 1] = t[i];
for (int j = i + 1; j > 1; j--)
t[j] = t[j] + t[j - 1];
System.out.printf("%d ", t[i + 1] - t[i]);
}
}
} |
Catamorphism | Java 8 | ''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
;Task:
Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.
;See also:
* Wikipedia article: Fold
* Wikipedia article: Catamorphism
| import java.util.stream.Stream;
public class ReduceTask {
public static void main(String[] args) {
System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum());
System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b));
}
} |
Chaocipher | Java from Kotlin | Description:
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
;Task:
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| import java.util.Arrays;
public class Chaocipher {
private enum Mode {
ENCRYPT,
DECRYPT
}
private static final String L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
private static final String R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
private static int indexOf(char[] a, char c) {
for (int i = 0; i < a.length; ++i) {
if (a[i] == c) {
return i;
}
}
return -1;
}
private static String exec(String text, Mode mode) {
return exec(text, mode, false);
}
private static String exec(String text, Mode mode, Boolean showSteps) {
char[] left = L_ALPHABET.toCharArray();
char[] right = R_ALPHABET.toCharArray();
char[] eText = new char[text.length()];
char[] temp = new char[26];
for (int i = 0; i < text.length(); ++i) {
if (showSteps) {
System.out.printf("%s %s\n", new String(left), new String(right));
}
int index;
if (mode == Mode.ENCRYPT) {
index = indexOf(right, text.charAt(i));
eText[i] = left[index];
} else {
index = indexOf(left, text.charAt(i));
eText[i] = right[index];
}
if (i == text.length() - 1) {
break;
}
// permute left
if (26 - index >= 0) System.arraycopy(left, index, temp, 0, 26 - index);
System.arraycopy(left, 0, temp, 26 - index, index);
char store = temp[1];
System.arraycopy(temp, 2, temp, 1, 12);
temp[13] = store;
left = Arrays.copyOf(temp, temp.length);
// permute right
if (26 - index >= 0) System.arraycopy(right, index, temp, 0, 26 - index);
System.arraycopy(right, 0, temp, 26 - index, index);
store = temp[0];
System.arraycopy(temp, 1, temp, 0, 25);
temp[25] = store;
store = temp[2];
System.arraycopy(temp, 3, temp, 2, 11);
temp[13] = store;
right = Arrays.copyOf(temp, temp.length);
}
return new String(eText);
}
public static void main(String[] args) {
String plainText = "WELLDONEISBETTERTHANWELLSAID";
System.out.printf("The original plaintext is : %s\n", plainText);
System.out.println("\nThe left and right alphabets after each permutation during encryption are:");
String cipherText = exec(plainText, Mode.ENCRYPT, true);
System.out.printf("\nThe cipher text is : %s\n", cipherText);
String plainText2 = exec(cipherText, Mode.DECRYPT);
System.out.printf("\nThe recovered plaintext is : %s\n", plainText2);
}
} |
Chaos game | Java 8 | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
;Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.
After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.
;See also
* The Game of Chaos
| import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class ChaosGame extends JPanel {
static class ColoredPoint extends Point {
int colorIndex;
ColoredPoint(int x, int y, int idx) {
super(x, y);
colorIndex = idx;
}
}
Stack<ColoredPoint> stack = new Stack<>();
Point[] points = new Point[3];
Color[] colors = {Color.red, Color.green, Color.blue};
Random r = new Random();
public ChaosGame() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
int margin = 60;
int size = dim.width - 2 * margin;
points[0] = new Point(dim.width / 2, margin);
points[1] = new Point(margin, size);
points[2] = new Point(margin + size, size);
stack.push(new ColoredPoint(-1, -1, 0));
new Timer(10, (ActionEvent e) -> {
if (stack.size() < 50_000) {
for (int i = 0; i < 1000; i++)
addPoint();
repaint();
}
}).start();
}
private void addPoint() {
try {
int colorIndex = r.nextInt(3);
Point p1 = stack.peek();
Point p2 = points[colorIndex];
stack.add(halfwayPoint(p1, p2, colorIndex));
} catch (EmptyStackException e) {
e.printStackTrace();
}
}
void drawPoints(Graphics2D g) {
for (ColoredPoint p : stack) {
g.setColor(colors[p.colorIndex]);
g.fillOval(p.x, p.y, 1, 1);
}
}
ColoredPoint halfwayPoint(Point a, Point b, int idx) {
return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPoints(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Chaos Game");
f.setResizable(false);
f.add(new ChaosGame(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
Check Machin-like formulas | Java | Machin-like formulas are useful for efficiently computing numerical approximations for \pi
;Task:
Verify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':
: {\pi\over4} = \arctan{1\over2} + \arctan{1\over3}
: {\pi\over4} = 2 \arctan{1\over3} + \arctan{1\over7}
: {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over239}
: {\pi\over4} = 5 \arctan{1\over7} + 2 \arctan{3\over79}
: {\pi\over4} = 5 \arctan{29\over278} + 7 \arctan{3\over79}
: {\pi\over4} = \arctan{1\over2} + \arctan{1\over5} + \arctan{1\over8}
: {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over70} + \arctan{1\over99}
: {\pi\over4} = 5 \arctan{1\over7} + 4 \arctan{1\over53} + 2 \arctan{1\over4443}
: {\pi\over4} = 6 \arctan{1\over8} + 2 \arctan{1\over57} + \arctan{1\over239}
: {\pi\over4} = 8 \arctan{1\over10} - \arctan{1\over239} - 4 \arctan{1\over515}
: {\pi\over4} = 12 \arctan{1\over18} + 8 \arctan{1\over57} - 5 \arctan{1\over239}
: {\pi\over4} = 16 \arctan{1\over21} + 3 \arctan{1\over239} + 4 \arctan{3\over1042}
: {\pi\over4} = 22 \arctan{1\over28} + 2 \arctan{1\over443} - 5 \arctan{1\over1393} - 10 \arctan{1\over11018}
: {\pi\over4} = 22 \arctan{1\over38} + 17 \arctan{7\over601} + 10 \arctan{7\over8149}
: {\pi\over4} = 44 \arctan{1\over57} + 7 \arctan{1\over239} - 12 \arctan{1\over682} + 24 \arctan{1\over12943}
: {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12943}
and confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''':
: {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12944}
These identities are useful in calculating the values:
: \tan(a + b) = {\tan(a) + \tan(b) \over 1 - \tan(a) \tan(b)}
: \tan\left(\arctan{a \over b}\right) = {a \over b}
: \tan(-a) = -\tan(a)
You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.
Note: to formally prove the formula correct, it would have to be shown that ''{-3 pi \over 4} < right hand side < {5 pi \over 4}'' due to ''\tan()'' periodicity.
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CheckMachinFormula {
private static String FILE_NAME = "MachinFormula.txt";
public static void main(String[] args) {
try {
runPrivate();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void runPrivate() throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) {
String inLine = null;
while ( (inLine = reader.readLine()) != null ) {
String[] split = inLine.split("=");
System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim()));
}
}
}
private static String tanLeft(String formula) {
if ( formula.compareTo("pi/4") == 0 ) {
return "1";
}
throw new RuntimeException("ERROR 104: Unknown left side: " + formula);
}
private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");
private static Fraction tanRight(String formula) {
Matcher matcher = ARCTAN_PATTERN.matcher(formula);
List<Term> terms = new ArrayList<>();
while ( matcher.find() ) {
terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3))));
}
return evaluateArctan(terms);
}
private static Fraction evaluateArctan(List<Term> terms) {
if ( terms.size() == 1 ) {
Term term = terms.get(0);
return evaluateArctan(term.coefficient, term.fraction);
}
int size = terms.size();
List<Term> left = terms.subList(0, (size+1) / 2);
List<Term> right = terms.subList((size+1) / 2, size);
return arctanFormula(evaluateArctan(left), evaluateArctan(right));
}
private static Fraction evaluateArctan(int coefficient, Fraction fraction) {
//System.out.println("C = " + coefficient + ", F = " + fraction);
if ( coefficient == 1 ) {
return fraction;
}
else if ( coefficient < 0 ) {
return evaluateArctan(-coefficient, fraction).negate();
}
if ( coefficient % 2 == 0 ) {
Fraction f = evaluateArctan(coefficient/2, fraction);
return arctanFormula(f, f);
}
Fraction a = evaluateArctan(coefficient/2, fraction);
Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction);
return arctanFormula(a, b);
}
private static Fraction arctanFormula(Fraction f1, Fraction f2) {
return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2)));
}
private static class Fraction {
public static final Fraction ONE = new Fraction("1", "1");
private BigInteger numerator;
private BigInteger denominator;
public Fraction(String num, String den) {
numerator = new BigInteger(num);
denominator = new BigInteger(den);
}
public Fraction(BigInteger num, BigInteger den) {
numerator = num;
denominator = den;
}
public Fraction negate() {
return new Fraction(numerator.negate(), denominator);
}
public Fraction add(Fraction f) {
BigInteger gcd = denominator.gcd(f.denominator);
BigInteger first = numerator.multiply(f.denominator.divide(gcd));
BigInteger second = f.numerator.multiply(denominator.divide(gcd));
return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd));
}
public Fraction subtract(Fraction f) {
return add(f.negate());
}
public Fraction multiply(Fraction f) {
BigInteger num = numerator.multiply(f.numerator);
BigInteger den = denominator.multiply(f.denominator);
BigInteger gcd = num.gcd(den);
return new Fraction(num.divide(gcd), den.divide(gcd));
}
public Fraction divide(Fraction f) {
return multiply(new Fraction(f.denominator, f.numerator));
}
@Override
public String toString() {
if ( denominator.compareTo(BigInteger.ONE) == 0 ) {
return numerator.toString();
}
return numerator + " / " + denominator;
}
}
private static class Term {
private int coefficient;
private Fraction fraction;
public Term(int c, Fraction f) {
coefficient = c;
fraction = f;
}
}
}
|
Cheryl's birthday | Java from D | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.
1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
3) Albert: Then I also know when Cheryl's birthday is.
;Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.
;Related task:
* [[Sum and Product Puzzle]]
;References
* Wikipedia article of the same name.
* Tuple Relational Calculus
| import java.time.Month;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
private static class Birthday {
private Month month;
private int day;
public Birthday(Month month, int day) {
this.month = month;
this.day = day;
}
public Month getMonth() {
return month;
}
public int getDay() {
return day;
}
@Override
public String toString() {
return month + " " + day;
}
}
public static void main(String[] args) {
List<Birthday> choices = List.of(
new Birthday(Month.MAY, 15),
new Birthday(Month.MAY, 16),
new Birthday(Month.MAY, 19),
new Birthday(Month.JUNE, 17),
new Birthday(Month.JUNE, 18),
new Birthday(Month.JULY, 14),
new Birthday(Month.JULY, 16),
new Birthday(Month.AUGUST, 14),
new Birthday(Month.AUGUST, 15),
new Birthday(Month.AUGUST, 17)
);
System.out.printf("There are %d candidates remaining.\n", choices.size());
// The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer
Set<Month> uniqueMonths = choices.stream()
.collect(Collectors.groupingBy(Birthday::getDay))
.values()
.stream()
.filter(g -> g.size() == 1)
.flatMap(Collection::stream)
.map(Birthday::getMonth)
.collect(Collectors.toSet());
List<Birthday> f1List = choices.stream()
.filter(birthday -> !uniqueMonths.contains(birthday.month))
.collect(Collectors.toList());
System.out.printf("There are %d candidates remaining.\n", f1List.size());
// Bernard now knows the answer, so the day must be unique within the remaining choices
List<Birthday> f2List = f1List.stream()
.collect(Collectors.groupingBy(Birthday::getDay))
.values()
.stream()
.filter(g -> g.size() == 1)
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.printf("There are %d candidates remaining.\n", f2List.size());
// Albert knows the answer too, so the month must be unique within the remaining choices
List<Birthday> f3List = f2List.stream()
.collect(Collectors.groupingBy(Birthday::getMonth))
.values()
.stream()
.filter(g -> g.size() == 1)
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.printf("There are %d candidates remaining.\n", f3List.size());
if (f3List.size() == 1) {
System.out.printf("Cheryl's birthday is %s\n", f3List.get(0));
} else {
System.out.println("No unique choice found");
}
}
} |
Chinese remainder theorem | Java | Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime.
Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences:
::: \begin{align}
x &\equiv a_1 \pmod{n_1} \\
x &\equiv a_2 \pmod{n_2} \\
&{}\ \ \vdots \\
x &\equiv a_k \pmod{n_k}
\end{align}
Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k.
;Task:
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k.
''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].
'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k
Again, to begin, the product N = n_1n_2 \ldots n_k is defined.
Then a solution x can be found as follows:
For each i, the integers n_i and N/n_i are co-prime.
Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1.
Then, one solution to the system of simultaneous congruences is:
::: x = \sum_{i=1}^k a_i s_i N/n_i
and the minimal solution,
::: x \pmod{N}.
| Translation of [[Chinese_remainder_theorem#Python|Python]] via [[Chinese_remainder_theorem#D|D]]
|
Chinese remainder theorem | Java 8 | Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime.
Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences:
::: \begin{align}
x &\equiv a_1 \pmod{n_1} \\
x &\equiv a_2 \pmod{n_2} \\
&{}\ \ \vdots \\
x &\equiv a_k \pmod{n_k}
\end{align}
Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k.
;Task:
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k.
''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].
'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k
Again, to begin, the product N = n_1n_2 \ldots n_k is defined.
Then a solution x can be found as follows:
For each i, the integers n_i and N/n_i are co-prime.
Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1.
Then, one solution to the system of simultaneous congruences is:
::: x = \sum_{i=1}^k a_i s_i N/n_i
and the minimal solution,
::: x \pmod{N}.
| import static java.util.Arrays.stream;
public class ChineseRemainderTheorem {
public static int chineseRemainder(int[] n, int[] a) {
int prod = stream(n).reduce(1, (i, j) -> i * j);
int p, sm = 0;
for (int i = 0; i < n.length; i++) {
p = prod / n[i];
sm += a[i] * mulInv(p, n[i]) * p;
}
return sm % prod;
}
private static int mulInv(int a, int b) {
int b0 = b;
int x0 = 0;
int x1 = 1;
if (b == 1)
return 1;
while (a > 1) {
int q = a / b;
int amb = a % b;
a = b;
b = amb;
int xqx = x1 - q * x0;
x1 = x0;
x0 = xqx;
}
if (x1 < 0)
x1 += b0;
return x1;
}
public static void main(String[] args) {
int[] n = {3, 5, 7};
int[] a = {2, 3, 2};
System.out.println(chineseRemainder(n, a));
}
} |
Chinese zodiac | Java | Determine the Chinese zodiac sign and related associations for a given year.
Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.
Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.
Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.
The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.
Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.
;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
;Requisite information:
* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
* Each element gets two consecutive years; a yang followed by a yin.
* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.
Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle.
;Information for optional task:
* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
| public class Zodiac {
final static String animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"};
final static String elements[]={"Wood","Fire","Earth","Metal","Water"};
final static String animalChars[]={"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"};
static String elementChars[][]={{"甲","丙","戊","庚","壬"},{"乙","丁","己","辛","癸"}};
static String getYY(int year)
{
if(year%2==0)
{
return "yang";
}
else
{
return "yin";
}
}
public static void main(String[] args)
{
int years[]={1935,1938,1968,1972,1976,1984,1985,2017};
for(int i=0;i<years.length;i++)
{
System.out.println(years[i]+" is the year of the "+elements[(int) Math.floor((years[i]-4)%10/2)]+" "+animals[(years[i]-4)%12]+" ("+getYY(years[i])+"). "+elementChars[years[i]%2][(int) Math.floor((years[i]-4)%10/2)]+animalChars[(years[i]-4)%12]);
}
}
}
|
Church numerals | Java 8 and above | In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''
* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''
* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
* Church Zero,
* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
* functions for Addition, Multiplication and Exponentiation over Church numerals,
* a function to convert integers to corresponding Church numerals,
* and a function to convert Church numerals to corresponding integers.
You should:
* Derive Church numerals three and four in terms of Church zero and a Church successor function.
* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
* convert each result back to an integer, and return it or print it to the console.
| package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next(ChurchNum n) {
return f -> x -> f.apply(n.apply(f).apply(x));
}
public static ChurchNum plus(ChurchNum a) {
return b -> f -> x -> b.apply(f).apply(a.apply(f).apply(x));
}
public static ChurchNum pow(ChurchNum m) {
return n -> m.apply(n);
}
public static ChurchNum mult(ChurchNum a) {
return b -> f -> x -> b.apply(a.apply(f)).apply(x);
}
public static ChurchNum toChurchNum(int n) {
if (n <= 0) {
return zero();
}
return next(toChurchNum(n - 1));
}
public static int toInt(ChurchNum c) {
AtomicInteger counter = new AtomicInteger(0);
ChurchNum funCounter = f -> {
counter.incrementAndGet();
return f;
};
plus(zero()).apply(c).apply(funCounter).apply(x -> x);
return counter.get();
}
public static void main(String[] args) {
ChurchNum zero = zero();
ChurchNum three = next(next(next(zero)));
ChurchNum four = next(next(next(next(zero))));
System.out.println("3+4=" + toInt(plus(three).apply(four))); // prints 7
System.out.println("4+3=" + toInt(plus(four).apply(three))); // prints 7
System.out.println("3*4=" + toInt(mult(three).apply(four))); // prints 12
System.out.println("4*3=" + toInt(mult(four).apply(three))); // prints 12
// exponentiation. note the reversed order!
System.out.println("3^4=" + toInt(pow(four).apply(three))); // prints 81
System.out.println("4^3=" + toInt(pow(three).apply(four))); // prints 64
System.out.println(" 8=" + toInt(toChurchNum(8))); // prints 8
}
} |
Circles of given radius through two points | Java from Kotlin | 2 circles with a given radius through 2 points in 2D space.
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
;Exceptions:
# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.
# If the points are too far apart then no circles can be drawn.
;Task detail:
* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.
* Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
;Related task:
* [[Total circles area]].
;See also:
* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| import java.util.Objects;
public class Circles {
private static class Point {
private final double x, y;
public Point(Double x, Double y) {
this.x = x;
this.y = y;
}
public double distanceFrom(Point other) {
double dx = x - other.x;
double dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
Point point = (Point) other;
return x == point.x && y == point.y;
}
@Override
public String toString() {
return String.format("(%.4f, %.4f)", x, y);
}
}
private static Point[] findCircles(Point p1, Point p2, double r) {
if (r < 0.0) throw new IllegalArgumentException("the radius can't be negative");
if (r == 0.0 && p1 != p2) throw new IllegalArgumentException("no circles can ever be drawn");
if (r == 0.0) return new Point[]{p1, p1};
if (Objects.equals(p1, p2)) throw new IllegalArgumentException("an infinite number of circles can be drawn");
double distance = p1.distanceFrom(p2);
double diameter = 2.0 * r;
if (distance > diameter) throw new IllegalArgumentException("the points are too far apart to draw a circle");
Point center = new Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0);
if (distance == diameter) return new Point[]{center, center};
double mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0);
double dx = (p2.x - p1.x) * mirrorDistance / distance;
double dy = (p2.y - p1.y) * mirrorDistance / distance;
return new Point[]{
new Point(center.x - dy, center.y + dx),
new Point(center.x + dy, center.y - dx)
};
}
public static void main(String[] args) {
Point[] p = new Point[]{
new Point(0.1234, 0.9876),
new Point(0.8765, 0.2345),
new Point(0.0000, 2.0000),
new Point(0.0000, 0.0000)
};
Point[][] points = new Point[][]{
{p[0], p[1]},
{p[2], p[3]},
{p[0], p[0]},
{p[0], p[1]},
{p[0], p[0]},
};
double[] radii = new double[]{2.0, 1.0, 2.0, 0.5, 0.0};
for (int i = 0; i < radii.length; ++i) {
Point p1 = points[i][0];
Point p2 = points[i][1];
double r = radii[i];
System.out.printf("For points %s and %s with radius %f\n", p1, p2, r);
try {
Point[] circles = findCircles(p1, p2, r);
Point c1 = circles[0];
Point c2 = circles[1];
if (Objects.equals(c1, c2)) {
System.out.printf("there is just one circle with center at %s\n", c1);
} else {
System.out.printf("there are two circles with centers at %s and %s\n", c1, c2);
}
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
System.out.println();
}
}
} |
Cistercian numerals | Java from Kotlin | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.
;How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
:* The '''upper-right''' quadrant represents the '''ones''' place.
:* The '''upper-left''' quadrant represents the '''tens''' place.
:* The '''lower-right''' quadrant represents the '''hundreds''' place.
:* The '''lower-left''' quadrant represents the '''thousands''' place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]
;Task
:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
:* Use the routine to show the following Cistercian numerals:
::* 0
::* 1
::* 20
::* 300
::* 4000
::* 5555
::* 6789
::* And a number of your choice!
;Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.
;See also
:* '''Numberphile - The Forgotten Number System'''
:* '''dcode.fr - Online Cistercian numeral converter'''
| import java.util.Arrays;
import java.util.List;
public class Cistercian {
private static final int SIZE = 15;
private final char[][] canvas = new char[SIZE][SIZE];
public Cistercian(int n) {
initN();
draw(n);
}
public void initN() {
for (var row : canvas) {
Arrays.fill(row, ' ');
row[5] = 'x';
}
}
private void horizontal(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r][c] = 'x';
}
}
private void vertical(int r1, int r2, int c) {
for (int r = r1; r <= r2; r++) {
canvas[r][c] = 'x';
}
}
private void diagd(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r + c - c1][c] = 'x';
}
}
private void diagu(int c1, int c2, int r) {
for (int c = c1; c <= c2; c++) {
canvas[r - c + c1][c] = 'x';
}
}
private void draw(int v) {
var thousands = v / 1000;
v %= 1000;
var hundreds = v / 100;
v %= 100;
var tens = v / 10;
var ones = v % 10;
drawPart(1000 * thousands);
drawPart(100 * hundreds);
drawPart(10 * tens);
drawPart(ones);
}
private void drawPart(int v) {
switch (v) {
case 1:
horizontal(6, 10, 0);
break;
case 2:
horizontal(6, 10, 4);
break;
case 3:
diagd(6, 10, 0);
break;
case 4:
diagu(6, 10, 4);
break;
case 5:
drawPart(1);
drawPart(4);
break;
case 6:
vertical(0, 4, 10);
break;
case 7:
drawPart(1);
drawPart(6);
break;
case 8:
drawPart(2);
drawPart(6);
break;
case 9:
drawPart(1);
drawPart(8);
break;
case 10:
horizontal(0, 4, 0);
break;
case 20:
horizontal(0, 4, 4);
break;
case 30:
diagu(0, 4, 4);
break;
case 40:
diagd(0, 4, 0);
break;
case 50:
drawPart(10);
drawPart(40);
break;
case 60:
vertical(0, 4, 0);
break;
case 70:
drawPart(10);
drawPart(60);
break;
case 80:
drawPart(20);
drawPart(60);
break;
case 90:
drawPart(10);
drawPart(80);
break;
case 100:
horizontal(6, 10, 14);
break;
case 200:
horizontal(6, 10, 10);
break;
case 300:
diagu(6, 10, 14);
break;
case 400:
diagd(6, 10, 10);
break;
case 500:
drawPart(100);
drawPart(400);
break;
case 600:
vertical(10, 14, 10);
break;
case 700:
drawPart(100);
drawPart(600);
break;
case 800:
drawPart(200);
drawPart(600);
break;
case 900:
drawPart(100);
drawPart(800);
break;
case 1000:
horizontal(0, 4, 14);
break;
case 2000:
horizontal(0, 4, 10);
break;
case 3000:
diagd(0, 4, 10);
break;
case 4000:
diagu(0, 4, 14);
break;
case 5000:
drawPart(1000);
drawPart(4000);
break;
case 6000:
vertical(10, 14, 0);
break;
case 7000:
drawPart(1000);
drawPart(6000);
break;
case 8000:
drawPart(2000);
drawPart(6000);
break;
case 9000:
drawPart(1000);
drawPart(8000);
break;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (var row : canvas) {
builder.append(row);
builder.append('\n');
}
return builder.toString();
}
public static void main(String[] args) {
for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
System.out.printf("%d:\n", number);
var c = new Cistercian(number);
System.out.println(c);
}
}
} |
Closures/Value capture | Java 8+ | Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
;Goal:
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: [[Multiple distinct objects]]
| import java.util.List;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public interface ValueCapture {
public static void main(String... arguments) {
List<IntSupplier> closures = IntStream.rangeClosed(0, 10)
.<IntSupplier>mapToObj(i -> () -> i * i)
.collect(toList())
;
IntSupplier closure = closures.get(3);
System.out.println(closure.getAsInt()); // prints "9"
}
} |
Colorful numbers | Java from C | A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
;E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840
Every product is unique.
2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144
The product '''6''' is repeated.
Single digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
;Task
* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
* Use that routine to find all of the colorful numbers less than 100.
* Use that routine to find the largest possible colorful number.
;Stretch
* Find and display the count of colorful numbers in each order of magnitude.
* Find and show the total count of '''all''' colorful numbers.
''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''
| public class ColorfulNumbers {
private int count[] = new int[8];
private boolean used[] = new boolean[10];
private int largest = 0;
public static void main(String[] args) {
System.out.printf("Colorful numbers less than 100:\n");
for (int n = 0, count = 0; n < 100; ++n) {
if (isColorful(n))
System.out.printf("%2d%c", n, ++count % 10 == 0 ? '\n' : ' ');
}
ColorfulNumbers c = new ColorfulNumbers();
System.out.printf("\n\nLargest colorful number: %,d\n", c.largest);
System.out.printf("\nCount of colorful numbers by number of digits:\n");
int total = 0;
for (int d = 0; d < 8; ++d) {
System.out.printf("%d %,d\n", d + 1, c.count[d]);
total += c.count[d];
}
System.out.printf("\nTotal: %,d\n", total);
}
private ColorfulNumbers() {
countColorful(0, 0, 0);
}
public static boolean isColorful(int n) {
// A colorful number cannot be greater than 98765432.
if (n < 0 || n > 98765432)
return false;
int digit_count[] = new int[10];
int digits[] = new int[8];
int num_digits = 0;
for (int m = n; m > 0; m /= 10) {
int d = m % 10;
if (n > 9 && (d == 0 || d == 1))
return false;
if (++digit_count[d] > 1)
return false;
digits[num_digits++] = d;
}
// Maximum number of products is (8 x 9) / 2.
int products[] = new int[36];
for (int i = 0, product_count = 0; i < num_digits; ++i) {
for (int j = i, p = 1; j < num_digits; ++j) {
p *= digits[j];
for (int k = 0; k < product_count; ++k) {
if (products[k] == p)
return false;
}
products[product_count++] = p;
}
}
return true;
}
private void countColorful(int taken, int n, int digits) {
if (taken == 0) {
for (int d = 0; d < 10; ++d) {
used[d] = true;
countColorful(d < 2 ? 9 : 1, d, 1);
used[d] = false;
}
} else {
if (isColorful(n)) {
++count[digits - 1];
if (n > largest)
largest = n;
}
if (taken < 9) {
for (int d = 2; d < 10; ++d) {
if (!used[d]) {
used[d] = true;
countColorful(taken + 1, n * 10 + d, digits + 1);
used[d] = false;
}
}
}
}
}
} |
Colour bars/Display | Java | Display a series of vertical color bars across the width of the display.
The color bars should either use:
:::* the system palette, or
:::* the sequence of colors:
::::::* black
::::::* red
::::::* green
::::::* blue
::::::* magenta
::::::* cyan
::::::* yellow
::::::* white
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class ColorFrame extends JFrame {
public ColorFrame(int width, int height) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(width, height);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
Color[] colors = { Color.black, Color.red, Color.green, Color.blue,
Color.pink, Color.CYAN, Color.yellow, Color.white };
for (int i = 0; i < colors.length; i++) {
g.setColor(colors[i]);
g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()
/ colors.length, this.getHeight());
}
}
public static void main(String args[]) {
new ColorFrame(200, 200);
}
}
|
Comma quibbling | Java | Comma quibbling is a task originally set by Eric Lippert in his blog.
;Task:
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
# An input of no words produces the output string of just the two brace characters "{}".
# An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
# An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
# An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
* [] # (No input words).
* ["ABC"]
* ["ABC", "DEF"]
* ["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| public class Quibbler {
public static String quibble(String[] words) {
String qText = "{";
for(int wIndex = 0; wIndex < words.length; wIndex++) {
qText += words[wIndex] + (wIndex == words.length-1 ? "" :
wIndex == words.length-2 ? " and " :
", ";
}
qText += "}";
return qText;
}
public static void main(String[] args) {
System.out.println(quibble(new String[]{}));
System.out.println(quibble(new String[]{"ABC"}));
System.out.println(quibble(new String[]{"ABC", "DEF"}));
System.out.println(quibble(new String[]{"ABC", "DEF", "G"}));
System.out.println(quibble(new String[]{"ABC", "DEF", "G", "H"}));
}
} |
Command-line arguments | Java | {{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].
See also [[Program name]].
For parsing command line arguments intelligently, see [[Parsing command-line arguments]].
Example command line:
myprogram -c "alpha beta" -h "gamma"
| public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
} |
Compare a list of strings | Java | Given a list of arbitrarily many strings, show how to:
* test if they are all lexically '''equal'''
* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is ''no'' need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
| boolean isAscending(String[] strings) {
String previous = strings[0];
int index = 0;
for (String string : strings) {
if (index++ == 0)
continue;
if (string.compareTo(previous) < 0)
return false;
previous = string;
}
return true;
}
|
Subsets and Splits