CodeReportSolutions

From ZCubes Wiki
Jump to navigation Jump to search

Code Report Solutions

Thinking in z^3

This is a quick introduction to the z^3 language (pronounced as "zcubes language").

ZCubes Language (z^3) is an easy to write, natural to read, omni-functional language.

Learn z^3 Language in detail by clicking this link.

Introduction

Following are z^3 Solutions to YouTube Code Report Channel Videos. To learn how to code in ZCubes language, please visit [https://coding.zcubes.com]. ZCubes Web Platform can be started in Code Mode at [https://code.zcubes.com].

Problems and Solutions

Sign of Product of an Array

Video: https://www.youtube.com/watch?v=a7CSK7HNEWQ&t=297s [I ❤ APL and Haskell #2 ]

z^3 Solution

a=[-1,-2,-3,4,3,2,1];
∏±a

Gives answer -1

∏ is Product, ± is SIGN function. APL has 3 characters it its solution (selected as the best solution in the video because of its brevity). Interesting that the solution with z^3 has even less characters, just 2.

Powerful Solution to Indexing Problem (1 character in z^3 vs 3 in APL)

Video: https://www.youtube.com/watch?v=ctbGMuakpHk [Python vs 3 Character APL Solution ]

z^3 Solution


a=[0,2,1,5,3,4];
a#a

Gives answer 0 1 2 4 5 3


Actual logic is just # [Hash], which is an index access operator, if operated on any array. For this problem, the answer is just one character (3 to be generous). # operator is far more powerful and is polymorphic depending on the types of arguments provided.

Number of Different Integers in a String

Video: https://www.youtube.com/watch?v=59vAjBS3yZM [APL Wins (vs C++, Java & Python)]

z^3 Solution

s="ad3343sadfsd343434df343443sff";
(s#/[^\d]+/)∪

Result: 3343	343434	343443


 # splits string using the postfix regexp pattern. ∪ extracts unique from the results
 12 Character z^3 Solution vs. 14 Character APL Solution
 
 

Another Solution

 s="ad3343sadfsd343434df343443sff";
(/\d+/g!)(s)#;

Answer: 3. Uses RegExp, and ! is used to create a predicate function to match the RegExp. String is given to the predicate function, and # counts the number of pieces extracted.

Final Value of Variable After Performing Operations

Video: https://www.youtube.com/watch?v=8Njxgy4itts [4 APL Solutions in 10 Minutes!]

z^3 Solution

m=["--x","x++","x++"].print();
[0]@(m!)

Gives answer:

x	[--x,x++,x++]
0	-1	-1	0


m! makes the string m to a function, which is then evaluated using [0]@. 0 forms a single input combinatorial argument.
[0..10]@(m!) can be used to loop through a set of initial values
Interesting that this solution has far less characters than APL solution, and can be made even shorter.

Count Negative Numbers in a Sorted Matrix

Video: https://www.youtube.com/watch?v=pDbDtGn1PXk [LeetCode 176 Problem 1 - Count Negative Numbers in a Sorted Matrix]

z^3 Solution

x=[-2,-1,0;-1,1,3;-1,2,4];
(x⍌).findv(NEGATIVE)#

Gives answer 4

⍌ Flatten Array
.findv Gives result of function call NEGATIVE 
# Counts the result

Check if a matrix is an X-Matrix (X like diagonals are filled)

Video: https://www.youtube.com/watch?v=8ynsN4nJxzU [APL vs BQN vs J vs Q vs NumPy vs Julia vs R - A comparison of seven different programming languages across a few different language criteria.]

z^3 Solution

m=[2 0 0 1; 0 3 1 0; 0 5 2 0; 4 0 0 2];
n=(m#)[0];
xm=|n| |+| |n|⤽;
xm|==|(m.$("x!=0?1:0"!))

Gives answer true

m# gives length of array m. 
|n| gives n dimensional Identity Matrix, which is added using |+| to the .reverse() of same array.
|==| is used to compare this to the m, .$ is used to apply the function "x!=0?1:0"! to every element. "x!=0?1:0"! shows how a function can be created from a string with the ! operator.
⤽ is the same as .reverse();
.$ can also be replaced by bycell ▦ operator to be more compact.
Also note simpler z^3 Array Notation used to create the variable x (with , (when positive numbers alone are used, the comma is also optional) and ;). Usual Javascript array notations also work.

Partitioning Odd and Even Numbers in an Array

Video: https://www.youtube.com/watch?v=A16w7qTfT68 [Implementing C++'s std::partition in BQN ]

z^3 Solution


a=[3,1,2,4];
(a ⑂ [ISEVEN,ISODD]) ⍌

Gives answer 2 4 3 1


Fork (⑂) with an array of functions, and flatten the result. Function Array can have any number of predicates/functions.

Rearrange Array to Maximize Prefix Score

Video: https://www.youtube.com/watch?v=mRT-yK2RTdg [Why I Love BQN So Much! (vs Python)]

z^3 Solution

a=[2,-1,0,1,-3,3,-3];
((a⋱) ≡⧺ ∑)  ↥;

Gives answer 6

Sort by Descending Order (⋱), followed by cumulative row SUM (≡⧺ SUM), followed by MAX (↥)

Hypotenuse

Video: https://www.youtube.com/watch?v=Wah-uQ9ou80 [Python vs Uiua vs BQN]

z^3 Solution

h:=√∑([a,b]^2);
h(3,4)

Gives answer 5

Filter Is Odd From List

Video: https://www.youtube.com/watch?v=XJ3QWOSZ8Nk [Lightning Talk: C++ vs Haskell vs BQN by Conor Hoekstra | Lambda Days 2023]

z^3 Solution

(1..5) ⑂ ISODD

Gives answer 1 3 5

Greatest Common Divisor/Lowest Common Multiple

Video: https://www.youtube.com/watch?v=UVUjnzpQKUo [1 Problem, 16 Programming Languages (C++ vs Rust vs Haskell vs Python vs APL...)]

z^3 Solution

LCM(20,15)
Gives: 60
GCD(20,15)
Gives: 5
GCD(5..20..5,15)
Gives:
-	GCD
5	15	5
10	15	5
15	15	15
20	15	5

Maximum Count of Positive Integer and Negative Integer

Video: https://www.youtube.com/watch?v=U6I-Kwj-AvY&list=PLVFrD1dmDdvf8REa4SkI-IppFGvkRq83O [1 Problem, 24 Programming Languages]

z^3 Solution


Examples:

a=[-2,-1,-1,1,2,3];
b=[-3,-2,-1,0,0,1,2];
c=[5,20,66,1314];

[
 (a ⑂) ≡ ⧻,
 (b ⑂) ≡ ⧻,
 (c ⑂) ≡ ⧻
]

Answer:
3 0 3
3 2 2
0 0 4


 ⑂ - SPLIT INTO NEGATIVE,ZERO,POSITIVE (by default, or any array of boolean functions)
 ≡ - BYROW
 ⧻ - COUNT

Richest Customer Wealth

Video: https://www.youtube.com/watch?v=MKb4WD6mioE [1 Problem, 6 Programming Languages (C++ vs Rust vs Haskell vs APL vs Clojure vs Scala)]

z^3 Solution

w=[
	[1,2,3],
	[5,5,5],
	[3,1,4]	
];
(w≡∑)↥
Answer:
15

 ≡ - BYROW
 ∑ - SUM
 ↥ - MAX

Extract First 4 Words

Video: https://www.youtube.com/watch?v=a7CSK7HNEWQ [I ❤ APL and Haskell]

z^3 Solution

s="This is a sentence which has a lot of words";
(s#" ")#(0..3)
 
 s="Hello how are you Contestant";
(s#" ")#(0..3)
Answer:
This	is	a	sentence
Hello	how	are	you

 #" " Splits the sentence by words
 #(0..3) Extracts first four elements (or) words.
 
 


PowerSet Sum of Powers

Video: https://www.youtube.com/watch?v=k9BNn39gWiM [BQN vs Jelly]

Powers of the Powerset. Power is defined as the square of the largest number in a sequence, multiplied by the smallest.

z^3 Solution

p=POWERSET([2,1,4]);
p≡"[∏(↧x,↥x^2)]"!.*∑;
 
Answer:
141

 "[∏(↧x,↥x^2)]"!  Creates a function (with the fabulous operator !) of product of min and square of max. ! makes a function out of a string.
 ≡ Apply the function by row
 .*∑ applies ∑ to the array on the left 
 
 

Left and Right Sum Differences

Video: https://www.youtube.com/watch?v=i1K_kUKJnE4 [I ❤ BQN and Haskell]

Problem Link: https://leetcode.com/contest/weekly-contest-334/problems/left-and-right-sum-differences/

Given a 0-indexed array nums, find a 0-indexed integer array answer where:

answer.length==nums.length.

answer[i]=|leftSum[i]-rightSum[i]|

Where:

-leftSum[i] is the sum of elements to the left of the index i in the array nums. If there is no such element, leftSum[i]=0

-rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i]=0


z^3 Solution

xs=[10,4,8,3];
n=(xs#1d)[0];
a=[0]⧺ (xs#(0..(n-2))) ≡⧺(SUM);
b=[0]⧺(xs#((n-1)..(1)..-1)) ≡⧺(SUM); 
b⤽;
(a|-|b).$(ABS);

Answer:
15	1	11	22

≡⧺ Cumulate an array with function (SUM).
 ⧺  Concat
 ⤽  Reverse
 |-| Element wise Subtraction
 #1d Size of 1st Dimension with [0] to index the number.
 
 


Sum of Squares of Elements with Index that are Factors of the Length of the Array

Video: https://www.youtube.com/watch?v=SpZJxbOf_jM&list=PLVFrD1dmDdvd_rChH0L1jeMVZpJ8ZIivE [BQN vs Uiua #2]


z^3 Solution

a=[1,2,3,4];
b=[2,7,1,19,18,3];
x=a;
n=x⧻;
m=NOT(n|%|(1..n));
∑((x◍m)²);


Answer:
With x=a: 21

With x=b: 63

 ⧻  Length
 |%|  Array Mod
 |-| Element wise Subtraction
 mask Extract Elements that Match Mask Array (with Null if second parameter is TRUE).
 n|%|(1..n) gets indices that are factors of the length n
 ◍  .mask 
 ²  SQUARED, POWERED TO 2
 ∑  SUM
 


Maximum Nesting Depth of the Paranthesis

Video: https://www.youtube.com/watch?v=zrOIQEN3Wkk [1 Problem, 8 Programming Languages (C++ vs Rust vs Clojure vs Haskell...)]


z^3 Solution

s="(1+(2*3)+((8)/4))+1";
v=(s#/[^()]/ ⚯ "")⎀;
y=(v ✖ 2 ) ➖81;
(NEG([y])≡⧺ ∑)↥; 


Answer:
3

 (s#/[^()]/ ⚯ "") Extracts ( and ) and makes a string of just paranthesis
 ⎀ Char Code
 |-| Element wise Subtraction
 y=(v ✖ 2 ) ➖81;  Multiplies using ZMULTIPLY with 2 and then subtracts 81. This gives -1 and 1 for ( and ).
 ≡⧺ Cumulate the array with function ∑ (SUM)
 ∑  SUM
 ↥  MAX
 ➖ can be used for unary NEG call ( ➖ is ZSUBTRACT for binary arguments, and NEG for unary prefix calls). Hence (NEG([y])≡⧺ ∑)↥; can also be (➖([y])≡⧺ ∑)↥;  
 

Longest Common Prefix

Video: https://www.youtube.com/watch?v=3o4RR9TKdFc [APL-Inspired Python!]


z^3 Solution

strs=["flower","flow","flight"];
((strs▦("x#"!))~≡(UNIQUE@Length)).whereindex(">1"!)
Answer:
2


strs=["dog","racecar","car"];
((strs▦("x#"!))~≡(UNIQUE@Length)).whereindex(">1"!)

Answer:
0

 "x#"! Makes a function that finds the length of string x
 ▦ Apply function to each element of the array
 ~ Transpose Matrix
 ≡ Apply to each row
 @ Concatenates two functions applying in the order
 .whereindex Array member function to find the first index at which the condition is true
 ">1"! Creates a predicate function x>1 using the Fabulous Operator !

Distance from First and Last Prime

Video: https://www.youtube.com/watch?v=ra_VpqPkENU [J vs BQN vs APL vs Jello]


z^3 Solution

 m=[4,2,9,4,3];
 -(MINUS(⇅(m.findi(ISPRIME))))
 
 (or)
 
 m.findi(ISPRIME)⇅.*MINUS.*NEG
 
 Answer: 3
 
 .findi gives indices of the matches of the predicate function
  ⇅ MINMAX
  .* Applies a function to an array
  MINUS subtracts each element from the other
  - - prefix  to make it a positive number.


Snake in Matrix

Video: https://www.youtube.com/watch?v=ec1Rsn5JvnY [BQN: Explicit to Tacit]

Problem Description: https://leetcode.com/problems/snake-in-matrix/description/

There is a snake in an n x n matrix grid and can move in four possible directions. Each cell in the grid is identified by the position: grid[i][j] = (i * n) + j.

The snake starts at cell 0 and follows a sequence of commands.

You are given an integer n representing the size of the grid and an array of strings commands where each command[i] is either "UP", "RIGHT", "DOWN", and "LEFT". It's guaranteed that the snake will remain within the grid boundaries throughout its movement.

Return the position of the final cell where the snake ends up after executing commands.

z^3 Solution

// solution
D=	{
		"LEFT"	:[0,-1],
		"RIGHT"	:[0,1],	
		"UP"	:[-1,0],		
		"DOWN"	:[1,0]
	
	};
DIRECTIONS=D;
m=["DOWN","RIGHT","LEFT"];
n=3;
mx=|n,n,0..(n ²)|;
ms=(D#[m])[0] 
mx#(ms ⋮SUM)~

Answer:
3

For
m=["DOWN","RIGHT","UP"];

Answer: 
1

For 
m=["RIGHT","DOWN"];

Answer:
4

 mx=|n,n,0..(n ²)|;Creation of an nxn matrix, filled with 0..n^2. Note the space inside n ² to allow quick power notation with superscript.
 ms=(D#[m])[0] D#[m] takes the values for keys as each of the elements of m, and [0] to extract the first element of this which contains the array of movements. This is similar to ms=m.$(x=>D[x]); which takes x from D for each of the elements of m.
 
 mx#(ms ⋮SUM)~ On Array ms a column-wise SUM, which is transposed and applied to index the element from mx. This gives the answer. 
 
 Below is the solution compressed a bit further without intermediate variables.
 // solution
D=	{
		"LEFT"	:[0,-1],
		"RIGHT"	:[0,1],	
		"UP"	:[-1,0],		
		"DOWN"	:[1,0]
	
	};
DIRECTIONS=D;
m=["RIGHT","DOWN"];
n=3;
|n,n,0..(n ²)|#((D#[m])[0] ⋮SUM)~
 
 ===Alternate Solution ===
 D=	{
		"LEFT"	:-1,
		"RIGHT"	:1,	
		"UP"	:-n,		
		"DOWN"	:n
	
	};
DIRECTIONS=D;
m=["DOWN","RIGHT","LEFT"];
n=3;
mx=0..(n ²);
ms=(D#[m])[0] 
mx#(∑ms)~

Same as before, but uses a flattened array. Simple SUM is used, instead of columnwise ⋮SUM etc. 
 

Final Array State After K Multiplication Operations I

Video: https://www.youtube.com/watch?v=O9AsxoQzNdI [Python vs C++ vs BQN vs APL]

Problem Description: https://leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/description/

You are given an integer array nums, an integer k, and an integer multiplier.

You need to perform k operations on nums. In each operation:

Find the minimum value x in nums. If there are multiple occurrences of the minimum value, select the one that appears first. Replace the selected minimum value x with x * multiplier. Return an integer array denoting the final state of nums after performing all k operations.


Example 1:

Input: nums = [2,1,3,5,6], k = 5, multiplier = 2

Output: [8,4,6,5,6]

Explanation:

Operation Result After operation 1 [2, 2, 3, 5, 6] After operation 2 [4, 2, 3, 5, 6] After operation 3 [4, 4, 3, 5, 6] After operation 4 [4, 4, 6, 5, 6] After operation 5 [8, 4, 6, 5, 6] Example 2:

Input: nums = [1,2], k = 3, multiplier = 4

Output: [16,8]

Explanation:

Operation Result After operation 1 [4, 2] After operation 2 [4, 8] After operation 3 [16, 8]


Constraints:

1 <= nums.length <= 100 1 <= nums[i] <= 100 1 <= k <= 10 1 <= multiplier <= 5

z^3 Solution


n=[2,1,3,5,6];k=5;m=2;
[q=(n⒤n↧)#0,n[q]*=m];𝕗f;
(1..k)@f;n
// [8,4,6,5,6]
 
n=[1,2];k=3;m=4;
[q=(n⒤n↧)#0,n[q]*=m];𝕗f;
(1..k)@f;n
// 16 8

Explanation: (n⒤n↧) finds index array matching i of min of array n 
#0 picks first element
n[q]*=m multiplies by m
;𝕗f; creates a function named f (stacky/tail). Uses the prior statement or block to construct a function.
(1..k)@f runs f for 1 to k
n is printed at end
Note [ ] to keep multiple pieces of the code together in array form as an interesting style.

Other Interesting Solutions

See Related