Problem 42708. Placing Beads Neatly in a Box
You are given a string of n black and white beads. Your job is to pack them neatly into a square box. "Neatly" in this case means that all the black beads are at the bottom, and all the white beads are at the top.
Half the beads are black, and half are white. The number of beads n will always be an even number perfect square (4, 16, 36, ...). Black beads are 1, and white beads are 0, so a string might look like this.
str = [0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1]
Return a square matrix bx that indexes into str such that
str(bx) = [ 0 0 0 0
0 0 0 0
1 1 1 1
1 1 1 1 ]
The matrix bx consists of the numbers 1 through n snaking through the box in a 4-connected sense (see Cody Problem 42705, Is It a Snake?).
Here's one solution for the string shown above.
bx = [ 1 8 9 10
2 7 12 11
3 6 13 14
4 5 16 15 ]
In general the answers are not unique. I will be checking that bx contains the numbers 1 through n, that they form a snake, and that when used with the string of beads, they result in a tidy ones-on-the-bottom formation.
I am grateful to the solvers of problem 42705 for giving me nice short code to use in my test suite for this problem!
Solution Stats
Problem Comments
-
5 Comments
Show
2 older comments
Ned Gulley
on 25 Jan 2016
You also gave me a new test for "Is it Snaky (42705)" that knocked out the current leader.
Carl Witthoft
on 27 Jan 2016
Can you clarify: does the partial sequence 1-1-0-1 force a failure? Your diagram doesn't seem to allow diagonal paths, so it seems that a single 0 or 1 causes failure.
Ned Gulley
on 28 Jan 2016
Hi Carl: All sequences are generated from successful packings. So you wouldn't get 1-1-0-1 because, as you note, it couldn't be packed successfully. In other words, this situation shouldn't come up.
Solution Comments
Show commentsProblem Recent Solvers13
Suggested Problems
-
10740 Solvers
-
274 Solvers
-
Project Euler: Problem 16, Sums of Digits of Powers of Two
141 Solvers
-
Check if number exists in vector
12253 Solvers
-
89 Solvers
More from this Author50
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!