Skip to content

Commit 376b73b

Browse files
committed
ch2 exercise solutions
1 parent 783b367 commit 376b73b

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

02-working-with-arrays.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,4 +123,4 @@ the more fun you will have.
123123
## Exercises
124124
1. Convert `23 34 45 56` to `(,45; ,56)` using a single primitive.
125125
2. Take the first five elements of `!9`, multiply them by 2, and put them back in the same place in !9.
126-
3. Create the array `(6 8 10; 12 14 16)` using the primitives from this chapter.
126+
3. Create the array `(6 8 10; 12 14 16)` using the primitives from this chapter. Try to find more than one way to do it.

code/02.k

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/ 1. Convert `23 34 45 56` to `(,45; ,56)` using a single primitive.
2+
2 3_23 34 45 56 / Using cut `_`
3+
4+
/ 2. Take the first five elements of `!9`, multiply them by 2, and put them back in the same place in !9.
5+
/ The required result is 0 2 4 6 8 5 6 7 8.
6+
(2*5#!9),5_!9 / I assumed the most literal interpretation would lead to this.
7+
(2*5#!9),-4#!9 / Also perfectly fine.
8+
((5#2),4#1)*!9 / This doesn't satisfy the "put them back in the same place" part, but it uses the primitives well.
9+
10+
/ 3. Create the array `(6 8 10; 12 14 16)` using the primitives from this chapter. Try to find more than one way to do it.
11+
/ Let us condense the easiest way to do this into many solutions.
12+
2 3#6 8 10 12 14 16 / perfectly valid.
13+
2 3#6+0 2 4 6 8 10 / take the 6 out
14+
2 3#6+2*0 1 2 3 4 5 / factor the 2 out
15+
2 3#6+2*!6 / make that a range
16+
/ Finding patterns in K code is often very rewarding. In K, patterns that make your code shorter almost always makes it better.

0 commit comments

Comments
 (0)