task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #HicEst | HicEst | REAL :: a(7), b(3), c(10)
c = a
DO i = 1, LEN(b)
c(i + LEN(a)) = b(i)
ENDDO |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Hy | Hy | => (setv a [1 2 3])
=> a
[1, 2, 3]
=> (+ a [4 5 6]) ; returns the concatenation
[1, 2, 3, 4, 5, 6]
=> a
[1, 2, 3]
=> (.extend a [7 8 9]) ; modifies the list in place
=> a
[1, 2, 3, 7, 8, 9]
=> (+ [1 2] [3 4] [5 6]) ; can accept multiple arguments
[1, 2, 3, 4, 5, 6] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #i | i | main
a $= [1, 2, 3]
b $= [4, 5, 6]
print(a + b)
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Icon_and_Unicon | Icon and Unicon |
procedure main()
L1 := [1, 2, 3, 4]
L2 := [11, 12, 13, 14]
L3 := L1 ||| L2
sep := ""
every writes(sep, !L3) do
sep := ", "
write()
end
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #IDL | IDL |
> a = [1,2,3]
> b = [4,5,6]
> help,a
A INT = Array[3]
> help,b
B INT = Array[3]
> print,a
1 2 3
> print,b
4 5 6
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Idris | Idris | Idris> [1, 2] ++ [4, 5, 6]
[1, 2, 3, 4, 5] : List Integer
Idris> :module Data.Vect
*Data/Vect> (the (Vect 2 Nat) [1, 2]) ++ (the (Vect 3 Nat) [3, 4, 5])
[1, 2, 3, 4, 5] : Vect 5 Nat |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Inform_7 | Inform 7 | let A be {1, 2, 3};
let B be {4, 5, 6};
add B to A; |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Ioke | Ioke | iik> [1,2,3] + [3,2,1]
[1,2,3] + [3,2,1]
+> [1, 2, 3, 3, 2, 1] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #J | J | array1 =: 1 2 3
array2 =: 4 5 6
array1 , array2
1 2 3 4 5 6 |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Java | Java | public static Object[] concat(Object[] arr1, Object[] arr2) {
Object[] res = new Object[arr1.length + arr2.length];
System.arraycopy(arr1, 0, res, 0, arr1.length);
System.arraycopy(arr2, 0, res, arr1.length, arr2.length);
return res;
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #JavaScript | JavaScript | var a = [1,2,3],
b = [4,5,6],
c = a.concat(b); //=> [1,2,3,4,5,6] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #jq | jq | [1,2] + [3] + [null] # => [1,2,3,null]
[range(1;3), 3, null] # => [1,2,3,null]
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Julia | Julia | a = [1,2,3]
b = [4,5,6]
ab = [a;b]
# the above bracket notation simply generates a call to vcat
ab = vcat(a,b)
# hcat is short for `horizontal concatenation`
ab = hcat(a,b) #ab -> 3x2 matrix
# the append!(a,b) method is mutating, appending `b` to `a`
append!(a,b) # a now equals [1,2,3,4,5,6] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #K | K |
a: 1 2 3
b: 4 5 6
a,b
1 2 3 4 5 6 |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
( 1.0 "Hello" 3 2 / 4 2.1 power ) ( 5 6 7 8 ) chain print
" " input |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Klong | Klong |
[1 2 3],[4 5 6] :" join "
[1 2 3 4 5 6]
[1 2],:\[[3 4] [5 6] [7 8]] :" join each-left "
[[1 2 3 4] [1 2 5 6] [1 2 7 8]]
[1 2],:/[[3 4] [5 6] [7 8]] :" join each-right "
[[3 4 1 2] [5 6 1 2] [7 8 1 2]]
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Kotlin | Kotlin | fun main(args: Array<String>) {
val a: Array<Int> = arrayOf(1, 2, 3) // initialise a
val b: Array<Int> = arrayOf(4, 5, 6) // initialise b
val c: Array<Int> = (a.toList() + b.toList()).toTypedArray()
println(c)
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #LabVIEW | LabVIEW |
{def A {A.new 1 2 3 4 5 6}} -> [1,2,3,4,5,6]
{def B {A.new 7 8 9}} -> [7,8,9]
{A.concat {A} {B}} -> [1,2,3,4,5,6,7,8,9]
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Lambdatalk | Lambdatalk |
{def A {A.new 1 2 3 4 5 6}} -> [1,2,3,4,5,6]
{def B {A.new 7 8 9}} -> [7,8,9]
{A.concat {A} {B}} -> [1,2,3,4,5,6,7,8,9]
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Lang5 | Lang5 | [1 2] [3 4] append collapse . |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #langur | langur | val .a = [1, 2, 3]
val .b = [7, 8, 9]
val .c = .a ~ .b
writeln .c |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Lasso | Lasso |
local(arr1 = array(1, 2, 3))
local(arr2 = array(4, 5, 6))
local(arr3 = #arr1->asCopy) // make arr3 a copy of arr2
#arr3->merge(#arr2) // concatenate 2 arrays
Result:
arr1 = array(1, 2, 3)
arr2 = array(4, 5, 6)
arr3 = array(4, 5, 6)
arr3 = array(1, 2, 3, 4, 5, 6) |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #LFE | LFE |
> (++ '(1 2 3) '(4 5 6))
(1 2 3 4 5 6)
> (: lists append '(1 2 3) '(4 5 6))
(1 2 3 4 5 6)
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Liberty_BASIC | Liberty BASIC | x=10
y=20
dim array1(x)
dim array2(y)
[concatenate]
dim array3(x + y)
for i = 1 to x
array3(i) = array1(i)
next
for i = 1 to y
array3(i + x) = array2(i)
next
[print]
for i = 1 to x + y
print array3(i)
next |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #LIL | LIL | ##
Array concatenation in LIL
##
set a [list 1 2 3]
set b [list 4 5 6]
set c [quote $a $b]
print $c
print "[index $c 0] [index $c 3]" |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Limbo | Limbo | implement Command;
include "sys.m";
sys: Sys;
include "draw.m";
include "sh.m";
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
a := array[] of {1, 2};
b := array[] of {3, 4, 5};
c := array[len a + len b] of int;
c[:] = a;
c[len a:] = b;
for (i := 0; i < len c; i++)
sys->print("%d\n", c[i]);
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Lingo | Lingo | a = [1,2]
b = [3,4,5]
repeat with v in b
a.append(v)
end repeat
put a
-- [1, 2, 3, 4, 5] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Little | Little | void main() {
int a[] = {0, 1, 2, 3, 4};
int b[] = {5, 6, 7, 8, 9};
int c[] = {(expand)a, (expand)b};
puts(c);
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Logo | Logo |
to combine-arrays :a1 :a2
output listtoarray sentence arraytolist :a1 arraytolist :a2
end
show combine-arrays {1 2 3} {4 5 6} ; {1 2 3 4 5 6}
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Lua | Lua | a = {1, 2, 3}
b = {4, 5, 6}
for _, v in pairs(b) do
table.insert(a, v)
end
print(table.concat(a, ", ")) |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #M2000_Interpreter | M2000 Interpreter |
a=(1,2,3,4,5)
b=Cons(a, (6,7,8),a)
Print b
1 2 3 4 5 6 7 8 1 2 3 4 5
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Maple | Maple |
> A := Array( [ 1, 2, 3 ] );
A := [1, 2, 3]
> B := Vector['row']( [ sin( x ), cos( x ), tan( x ) ] );
B := [sin(x), cos(x), tan(x)]
> ArrayTools:-Concatenate( 1, A, B ); # stack vertically
[ 1 2 3 ]
[ ]
[sin(x) cos(x) tan(x)]
> ArrayTools:-Concatenate( 2, A, B ); # stack horizontally
[1, 2, 3, sin(x), cos(x), tan(x)]
> M := << a, b, c ; d, e, f >>; # a matrix
[a b c]
M := [ ]
[d e f]
> ArrayTools:-Concatenate( 1, M, A );
[a b c]
[ ]
[d e f]
[ ]
[1 2 3]
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Mathcad | Mathcad |
create a pair of arbitrary array:
a:=matrix(2,2,max) b:=a+3
a=|0 1| b=|3 4|
|1 1| |4 4|
concatentate them vertically:
|0 1|
stack(a,b) = |1 1|
|3 4|
|4 4|
augment(a,b) = |0 1 3 4|
|1 1 3 4|
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Join[{1,2,3}, {4,5,6}]
-> {1, 2, 3, 4, 5, 6} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #MATLAB_.2F_Octave | MATLAB / Octave | >> a = [1 2 3];
>> b = [4 5 6];
>> c = [a b]
c =
1 2 3 4 5 6
>> c = [a;b]
c =
1 2 3
4 5 6 |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Maxima | Maxima | u: [1, 2, 3, 4]$
v: [5, 6, 7, 8, 9, 10]$
append(u, v);
/* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] */
/* There are also functions for matrices */
a: matrix([6, 1, 8],
[7, 5, 3],
[2, 9, 4])$
addcol(a, ident(3));
/* matrix([6, 1, 8, 1, 0, 0],
[7, 5, 3, 0, 1, 0],
[2, 9, 4, 0, 0, 1]) */
addrow(a, ident(3));
/* matrix([6, 1, 8],
[7, 5, 3],
[2, 9, 4],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]) */ |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Mercury | Mercury | A `append` B = C |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #min | min | (1 2 3) (4 "apple" 6) concat print |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #MiniScript | MiniScript |
arrOne = [1, 2, 3]
arrTwo = [4, 5, 6]
print arrOne + arrTwo
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Nanoquery | Nanoquery | a + b |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Neko | Neko | /*
Array concatenation, in Neko
*/
var a1 = $array(1,2,3,4)
var a2 = $array("abc", "def")
/* $array(a1, a2) creates an array of two arrays, $aconcat merges to one */
var ac = $aconcat($array(a1, a2))
$print(ac, "\n") |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Nemerle | Nemerle | using System.Console;
using Nemerle.Collections;
module ArrayCat
{
Main() : void
{
def arr1 = array[1, 2, 3]; def arr2 = array[4, 5, 6];
def arr12 = arr1.Append(arr2); // <----
foreach (i in arr12) Write($"$i ");
}
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref nobinary
cymru = [ 'Ogof Ffynnon Ddu', 'Ogof Draenen' ]
dlm = '-'.copies(40)
say dlm
loop c_ = 0 to cymru.length - 1
say c_ cymru[c_]
end c_
yorks = [ 'Malham Tarn Pot', 'Greygill Hole' ]
say dlm
loop y_ = 0 to yorks.length - 1
say y_ yorks[y_]
end y_
merge = ArrayList()
merge.addAll(Arrays.asList(cymru))
merge.addAll(Arrays.asList(yorks))
say dlm
merged = merge.toArray()
loop m_ = 0 to merged.length - 1
say m_ merged[m_]
end m_ |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #NewLISP | NewLISP | ; file: arraycon.lsp
; url: http://rosettacode.org/wiki/Array_concatenation
; author: oofoe 2012-01-28
(println "Append lists: " (append '(3 a 5 3) (sequence 1 9)))
(println "Multi append: "
(append '(this is)
'(a test)
'(of the emergency)
(sequence 3 1)))
(println "Append arrays: "
(append '((x 56) (b 99)) '((z 34) (c 23) (r 88))))
(exit) |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Nial | Nial | a:= 1 2 3
+-+-+-+
|1|2|3|
+-+-+-+
b:= 4 5 6
+-+-+-+
|4|5|6|
+-+-+-+ |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Nim | Nim | var
x = @[1,2,3,4,5,6]
y = @[7,8,9,10,11]
z = x & y |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Oberon-2 | Oberon-2 |
MODULE ArrayConcat;
IMPORT
Out;
TYPE
IntArray = POINTER TO ARRAY OF INTEGER;
VAR
x, y, z: IntArray;
PROCEDURE InitArray(VAR x: IntArray;from: INTEGER);
VAR
i: LONGINT;
BEGIN
FOR i := 0 TO LEN(x^) - 1 DO
x[i] := from;
INC(from)
END
END InitArray;
PROCEDURE Concat(x,y: IntArray; VAR z: IntArray);
VAR
i: LONGINT;
BEGIN
ASSERT(LEN(x^) + LEN(y^) <= LEN(z^));
FOR i := 0 TO LEN(x^) - 1 DO z[i] := x[i] END;
FOR i := 0 TO LEN(y^) - 1 DO z[i + LEN(x^)] := y[i] END
END Concat;
PROCEDURE Show(x: IntArray);
VAR
i: INTEGER;
BEGIN
i := 0;
Out.Char('[');
WHILE (i < LEN(x^)) DO
Out.LongInt(x[i],3);IF i < LEN(x^) - 1 THEN Out.Char(',') END;
INC(i)
END;
Out.Char(']');Out.Ln
END Show;
BEGIN
(* Standard types *)
NEW(x,5);InitArray(x,1);
NEW(y,10);InitArray(y,6);
NEW(z,LEN(x^) + LEN(y^));
Concat(x,y,z);
Show(z)
END ArrayConcat.
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Objeck | Objeck |
bundle Default {
class Arithmetic {
function : Main(args : String[]) ~ Nil {
array1 := [3, 5, 7];
array2 := [2, 4, 6];
array3 := Copy(array1, array2);
each(i : array3) {
array3[i]->PrintLine();
};
}
function : native : Copy(array1 : Int[], array2 : Int[]) ~ Int[] {
max := array1->Size() + array2->Size();
array3 := Int->New[max];
i := 0;
for(i := i; i < array1->Size(); i += 1;) {
array3[i] := array1[i];
};
j := 0;
for(i := i; i < max; i += 1;) {
array3[i] := array2[j];
j += 1;
};
return array3;
}
}
}
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Objective-C | Objective-C | NSArray *arr1 = @[@1, @2, @3];
NSArray *arr2 = @[@4, @5, @6];
NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2]; |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #OCaml | OCaml | # let list1 = [1; 2; 3];;
val list1 : int list = [1; 2; 3]
# let list2 = [4; 5; 6];;
val list2 : int list = [4; 5; 6]
# let list1and2 = list1 @ list2;;
val list1and2 : int list = [1; 2; 3; 4; 5; 6] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Oforth | Oforth | import: mapping
[1, 2, 3 ] [ 4, 5, 6, 7 ] + |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Onyx | Onyx | # With two arrays on the stack, cat pops
# them, concatenates them, and pushes the result back
# on the stack. This works with arrays of integers,
# strings, or whatever. For example,
[1 2 3] [4 5 6] cat # result: [1 2 3 4 5 6]
[`abc' `def'] [`ghi' `jkl'] cat # result: [`abc' `def' `ghi' `jkl']
# To concatenate more than two arrays, push the number of arrays
# to concatenate onto the stack and use ncat. For example,
[1 true `a'] [2 false `b'] [`3rd array'] 3 ncat
# leaves [1 true `a' 2 false `b' `3rd array'] on the stack |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #ooRexx | ooRexx | a = .array~of(1,2,3)
say "Array a has " a~items "items"
b = .array~of(4,5,6)
say "Array b has " b~items "items"
a~appendall(b) -- adds all items from b to a
say "Array a now has " a~items "items" |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Order | Order | #include <order/interpreter.h>
ORDER_PP( 8tuple_append(8tuple(1, 2, 3), 8tuple(4, 5, 6), 8pair(7, 8)) )
// -> (1,2,3,4,5,6,7,8)
ORDER_PP( 8seq_append(8seq(1, 2, 3), 8seq(4, 5, 6), 8seq(7, 8)) )
// -> (1)(2)(3)(4)(5)(6)(7)(8) |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #OxygenBasic | OxygenBasic |
'CREATE DYNAMIC ARRAY SPACES USING STRINGS
string sa=nuls 5* sizeof float
string sb=sa
'MAP ARRAY VARIABLES ONTO STRINGS
float a at *sa
float b at *sb
'ASSIGN SOME VALUES
a<=10,20,30,40,50
b<=60,70,80,90,00
'ADD ARRAY B TO A BY STRING CONCATENATION
sa+=sb
'TEST
print a[7] 'result 70
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Oz | Oz | %% concatenating 2 lists
{Append [a b] [c d]} = [a b c d]
%% concatenating 2 tuples
{Tuple.append t(1 2 3) u(4 5 6)} = u(1 2 3 4 5 6) |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #PARI.2FGP | PARI/GP | concat(u,v) |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Pascal | Pascal | my @arr1 = (1, 2, 3);
my @arr2 = (4, 5, 6);
my @arr3 = (@arr1, @arr2); |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Perl | Perl | my @arr1 = (1, 2, 3);
my @arr2 = (4, 5, 6);
my @arr3 = (@arr1, @arr2); |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Phix | Phix | sequence s1 = {1,2,3}, s2 = {4,5,6}
? s1 & s2
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Phixmonti | Phixmonti | 1.0 "Hello" 3 2 / 4 2.1 power 4 tolist 5 6 7 8 4 tolist chain print |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #PHP | PHP | $arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2); |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Picat | Picat | go =>
L1 = {1,2,3,4,5}, % define an array with {}
L2 = {6,7,8,9},
% The built-in array/list concatenation
println(L1 ++ L2),
% Using the built-in append/3 works only on lists
% so the arrays must be converted to lists.
append(L1.to_list,L2.to_list,L3),
println(L3.to_array),
nl. |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #PicoLisp | PicoLisp | : (setq A (1 2 3) B '(a b c))
-> (a b c)
: (conc A B) # Concatenate lists in 'A' and 'B'
-> (1 2 3 a b c)
: A
-> (1 2 3 a b c) # Side effect: List in 'A' is modified! |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Pike | Pike | int main() {
array arr1 = ({1, 2, 3});
array arr2 = ({4, 5, 6});
array arr3 = arr1 + arr2;
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #PL.2FI | PL/I |
declare x(12) fixed;
declare b(5) fixed defined x;
declare c(7) fixed defined x(1sub+5);
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Pony | Pony |
actor Main
new create(env:Env)=>
var a:Array[I32]=Array[I32](4)
var b:Array[I32]=Array[I32](2)
a.push(1)
a.push(2)
a.push(3)
a.push(4)
b.push(5)
b.push(6)
a.concat(b.values())
for i in a.values() do
env.out.print(i.string())
end
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #PostScript | PostScript |
[1 2 3 4] [5 6 7 8] concat
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #PowerShell | PowerShell | $a = 1,2,3
$b = 4,5,6
$c = $a + $b
Write-Host $c |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Processing | Processing |
int[] a = {1, 2, 3}, b = {4, 5, 6};
int[] c = concat(a, b);
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Prolog | Prolog |
?- append([1,2,3],[4,5,6],R).
R = [1, 2, 3, 4, 5, 6].
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #PureBasic | PureBasic | Procedure displayArray(Array a(1), msg.s)
Protected i
Print(msg + " [")
For i = 0 To ArraySize(a())
Print(Str(a(i)))
If i <> ArraySize(a())
Print(", ")
EndIf
Next
PrintN("]")
EndProcedure
Procedure randomElements(Array a(1), lo, hi)
Protected i
For i = 0 To ArraySize(a())
a(i) = random(hi - lo) + lo
Next
EndProcedure
Procedure arrayConcat(Array a(1), Array b(1), Array c(1))
Protected i, newSize = ArraySize(a()) + ArraySize(b()) + 1
Dim c(newSize)
For i = 0 To ArraySize(a())
c(i) = a(i)
Next
For i = 0 To ArraySize(b())
c(i + ArraySize(a()) + 1) = b(i)
Next
EndProcedure
If OpenConsole()
Dim a(random(3) + 1)
Dim b(random(3) + 1)
Dim c(0) ;array will be resized by arrayConcat()
randomElements(a(), -5, 5)
randomElements(b(), -5, 5)
displayArray(a(), "a:")
displayArray(b(), "b:")
arrayConcat(a(), b(), c())
displayArray(c(), "concat of a[] + b[]:")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Python | Python | arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
assert arr4 == [1, 2, 3, 4, 5, 6]
arr4.extend(arr3)
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Q | Q | list1:1 2 3
list2:4 5 6
list1,list2 |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #QBasic | QBasic | FUNCTION ConcatArrays(a(), b())
ta = UBOUND(a)
tb = UBOUND(b)
nt = ta + tb
FOR i = ta + 1 TO nt
a(i) = b(i - ta)
NEXT i
ConcatArrays = nt
END FUNCTION
dimen = 5
DIM a(dimen)
DIM b(dimen)
FOR i = 1 TO dimen
a(i) = i
b(i) = i + dimen
NEXT i
nt = ConcatArrays(a(), b())
FOR i = 1 TO nt
PRINT a(i);
IF i < nt THEN PRINT ", ";
NEXT i
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #QB64 | QB64 |
Dim As Integer First, Second
First = 5: Second = 8
Dim As Integer Array1(1 To First), Array2(1 To Second), ArrayResult(1 To First + Second)
Init Array1(), 2
Print "First array"
ShowArr Array1()
Sleep 2
Print "Second array"
Init Array2(), 5
ShowArr Array2()
Sleep 2
Print "Final array"
ConcatArray Array1(), Array2(), ArrayResult()
ShowArr ArrayResult()
End
Sub Init (A() As Integer, R As Integer)
Dim Index As Integer
For Index = 1 To UBound(a)
A(Index) = Index * R
Next
End Sub
Sub ShowArr (A() As Integer)
Dim Index As Integer
For Index = 1 To UBound(a)
Print A(Index)
Next
End Sub
Sub ConcatArray (A() As Integer, B() As Integer, R() As Integer)
Dim Index As Integer
For Index = 1 To UBound(a)
R(Index) = A(Index)
Next
For Index = (1) To (UBound(b))
R(Index + UBound(a)) = B(Index)
Next
End Sub
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Quackery | Quackery | > quackery
Welcome to Quackery.
Enter "leave" to leave the shell.
/O> ' [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
... ' [ [ 7 8 ] [ 9 0 ] ] join echo
...
[ [ 1 2 ] [ 3 4 ] [ 5 6 ] [ 7 8 ] [ 9 0 ] ]
Stack empty.
/O> leave
...
Goodbye.
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #R | R |
a1 <- c(1, 2, 3)
a2 <- c(3, 4, 5)
a3 <- c(a1, a2)
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Racket | Racket |
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10))
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Raku | Raku | my @array1 = 1, 2, 3;
my @array2 = 4, 5, 6;
# If you want to concatenate two array to form a third,
# either use the slip operator "|", to flatten each array.
my @array3 = |@array1, |@array2;
say @array3;
# or just flatten both arrays in one fell swoop
@array3 = flat @array1, @array2;
say @array3;
# On the other hand, if you just want to add the elements
# of the second array to the first, use the .append method.
say @array1.append: @array2; |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #RapidQ | RapidQ |
DEFINT A(1 to 4) = {1, 2, 3, 4}
DEFINT B(1 to 4) = {10, 20, 30, 40}
'Append array B to array A
Redim A(1 to 8) as integer
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
|
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | 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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program asciiDiagram64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Structures */
/********************************************/
/* Structure result */
.struct 0
res_name: //
.struct res_name + 8
res_startzone: //
.struct res_startzone + 8
res_endzone: //
.struct res_endzone + 8
res_size: //
.struct res_size + 8
res_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessDiagram: .asciz "Display diagramm :\n"
szMessValBin: .asciz "\nBinary Value :\n"
szMessValZone: .asciz "\nZones values : \n"
szMessResultTab: .asciz "Name @ start @ end @ size @ \n"
szMessSplitZone: .asciz "Name @ value : @ \n"
szMessErrSep: .asciz "Error : no séparator in first position of line.\n"
szMessErrlong: .asciz "Error : string hexa size not multiple to 4. \n"
szCarriageReturn: .asciz "\n"
szLine1: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
.equ LGLINE, . - szLine1
szLine2: .asciz "| ID |"
szLine3: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine4: .asciz "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |"
szLine5: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine6: .asciz "| QDCOUNT |"
szLine7: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine8: .asciz "| ANCOUNT |"
szLine9: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine10: .asciz "| NSCOUNT |"
szLine11: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine12: .asciz "| ARCOUNT |"
szLine13: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
.equ NBLINES, (. - szLine1) / LGLINE
bSeparator: .byte '|'
szValueHex: .asciz "78477bbf5496e12e1bf169a4"
szValueHexTest: .asciz "0ABCDEFabcdef123"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
tbZones: .skip res_end * NBLINES * 5
sBuffer: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessDiagram
bl affichageMess
ldr x1,qAdrszLine1
mov x3,#LGLINE
mov x2,#0
1: // display diagram lines
madd x0,x2,x3,x1
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x2,x2,#1
cmp x2,#NBLINES
blt 1b
ldr x0,qAdrszLine1 // first line address of diagram
bl decode // decode the diagram
mov x8,x0 // save result number
mov x3,#0 // indice
mov x4,#res_end // one result size
ldr x5,qAdrtbZones // table result address
2:
madd x6,x3,x4,x5 // compute result offset
ldr x1,[x6,#res_name] // zone name
ldr x0,qAdrszMessResultTab
bl strInsertAtCharInc // insertion in message
mov x7,x0
ldr x0,[x6,#res_startzone]
ldr x1,qAdrsZoneConv
bl conversion10 // call decimal conversion
mov x0,x7
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
mov x7,x0
ldr x0,[x6,#res_endzone]
ldr x1,qAdrsZoneConv // else display odd message
bl conversion10 // call decimal conversion
mov x0,x7
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
mov x7,x0
ldr x0,[x6,#res_size]
ldr x1,qAdrsZoneConv // else display odd message
bl conversion10 // call decimal conversion
mov x0,x7
ldr x1,qAdrsZoneConv // insert value conversion in message
bl strInsertAtCharInc
mov x7,x0
bl affichageMess
bl libererPlace // liberation heap area
add x3,x3,#1
cmp x3,x8
blt 2b
ldr x0,qAdrtbZones
ldr x1,qAdrszValueHex
//ldr x1,qAdrszValueHexTest
bl extractValue // convert string value hexa in binary string
mov x7,x0 // string binary address
ldr x0,qAdrszMessValZone
bl affichageMess
mov x0,x7
ldr x1,qAdrtbZones
mov x2,x8 // result number
bl splitZone
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessResultTab: .quad szMessResultTab
qAdrszMessDiagram: .quad szMessDiagram
qAdrszMessValZone: .quad szMessValZone
qAdrsZoneConv: .quad sZoneConv
qAdrszLine1: .quad szLine1
qAdrszValueHex: .quad szValueHex
qAdrszValueHexTest: .quad szValueHexTest
/***************************************************/
/* decode lines */
/***************************************************/
// x0 contains diagram address
// x0 return result counter
decode:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
mov x5,x0
mov x7,#LGLINE // size line diagram
ldr x3,qAdrbSeparator // séparator
ldrb w3,[x3]
ldr x1,qAdrtbZones // result table address
mov x2,#0 // result counter
mov x6,#1 // line 2
1:
madd x0,x6,x7,x5 // compute line offset
ldrb w4,[x0] // load one byte
cmp w4,w3 // separator ?
bne 99f // no -> error
bl decodeOneLine // decode a line
mov x2,x0 // new result number
add x6,x6,#2 // new line
cmp x6,#NBLINES // end ?
blt 1b
mov x0,x2 // return result counter
b 100f
99:
ldr x0,qAdrszMessErrSep
bl affichageMess
mov x0,#-1
100:
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrbSeparator: .quad bSeparator
qAdrszMessErrSep: .quad szMessErrSep
qAdrtbZones: .quad tbZones
/***************************************************/
/* decode one line */
/***************************************************/
// x0 contains line diagram address
// x1 contains table result
// x2 contains result number
// x3 contains séparator
// x0 return new result number
decodeOneLine:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
stp x10,x11,[sp,-16]! // save registres
stp x12,x13,[sp,-16]! // save registres
mov x11,x0 // save address diagram
mov x7,x1 // save address table result
mov x4,x2 // save result counter
mov x0,#0 // zone size
mov x5,#-1 // name text begin address
mov x6,x3 // séparator
mov x8,#res_end
mov x10,#0 // zone start
mov x12,#1 // character indice
1:
ldrb w1,[x11,x12] // load one byte
cmp w1,#0 // line end ?
beq 10f
cmp w1,w6 // separator ?
beq 3f
cmp w1,#' ' // space ?
bne 2f
cmp x5,#0 // text name found ?
mov x1,#0
blt 11f
strb w1,[x11,x12] // yes -> 0 final text
11:
add x0,x0,#1 // increment zone size
add x12,x12,#1 // new byte
b 1b // and loop
2:
cmp x5,#0 // text name found ?
add x1,x11,x12 // no -> start zone
csel x5,x1,x5,lt
add x0,x0,#1 // increment zone size
add x12,x12,#1 // new byte
b 1b // and loop
3: // separator
cmp x5,#0 // zone name ?
blt 31f
mov x1,#0
strb w1,[x11,x12] // yes -> 0 final
31:
madd x9,x4,x8,x7 // compute result offset
str x5,[x9,#res_name] // store address start name
add x0,x0,#1 // compute zone size
cmp x0,#3
mov x1,#2
mov x5,#3
csel x1,x5,x1,gt
udiv x2,x0,x1 // / by size characters zone
str x2,[x9,#res_size]
cmp x4,#0 // first result ?
csel x10,xzr,x10,eq
beq 4f
sub x10,x9,x8 // else start zone = prev end zone + 1
ldr x10,[x10,#res_endzone]
add x10,x10,#1
4:
str x10,[x9,#res_startzone]
add x10,x10,x2 // end zone = start zone + size - 1
sub x10,x10,#1
str x10,[x9,#res_endzone]
add x4,x4,#1 // increment counter result
mov x0,#0 // raz size zone
add x10,x10,#1 // next byte
mov x5,#-1 // no text name
add x12,x12,#1 // next byte
b 1b // and loop
10:
mov x0,x4 // return result counter
100:
ldp x12,x13,[sp],16 // restaur des 2 registres
ldp x10,x11,[sp],16 // restaur des 2 registres
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/***************************************************/
/* convert strinh value hexa in binary string */
/***************************************************/
// x0 contains diagram address
// x1 contains string hex value
extractValue:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
mov x5,x0 // save address
ldr x0,qAdrszMessValBin
bl affichageMess
mov x6,x1 // save address string hexa
mov x2,#0
mov x3,#0
1: // compute string size
ldrb w4,[x1,x2] // load byte
cmp w4,#0 // end string ?
cinc x2,x2,ne
bne 1b
lsr x8,x2,#2 // control if multiple of 4
lsl x3,x8,#2
cmp x3,x2
bne 99f // no -> error
lsl x0,x2,#3 // compute size string * 8
add x0,x0,#1 // zero final
bl reserverPlace // reserve array on the heap
mov x7,x0 // address of heap array
mov x1,x0 // for routine
mov x0,x6 // address string value hexa
bl conversionBin // conversion string hexa -> binary
mov x0,x7
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x7 // return address string binary
b 100f
99:
ldr x0,qAdrszMessErrlong
bl affichageMess
mov x0,#-1
100:
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessValBin: .quad szMessValBin
qAdrszMessErrlong: .quad szMessErrlong
/***************************************************/
/* decode lines */
/***************************************************/
// x0 contains address string binary
// x1 contains table zones address
// x2 contains result number
splitZone:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
stp x10,x11,[sp,-16]! // save registres
stp x12,x13,[sp,-16]! // save registres
mov x5,x0
mov x6,x1
mov x3,#0 // indice table
mov x4,#0 // indice string
mov x8,#res_end
1: // loop
madd x7,x3,x8,x6 // compute result offset
ldr x0,[x7,#res_startzone]
ldr x1,[x7,#res_size] // zone size
ldr x12,qAdrsBuffer
mov x9,#0
add x0,x0,x5
2: // copy bytes
ldrb w10,[x0,x9]
strb w10,[x12,x9]
add x9,x9,#1
cmp x9,x1 // zone size maxi ?
blt 2b // no -> loop
mov x10,#0 // 0 final
strb w10,[x12,x9]
// dislay name and value
ldr x0,qAdrszMessSplitZone
ldr x1,[x7,#res_name]
bl strInsertAtCharInc
mov x1,x12
bl strInsertAtCharInc
bl affichageMess
bl libererPlace
add x3,x3,#1
cmp x3,x2 // end result ?
blt 1b // no -> loop
100:
ldp x12,x13,[sp],16 // restaur des 2 registres
ldp x10,x11,[sp],16 // restaur des 2 registres
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
qAdrszMessSplitZone: .quad szMessSplitZone
qAdrsBuffer: .quad sBuffer
/***************************************************/
/* conversion chaine hexa en */
/***************************************************/
// x0 contains string address
// x1 contains buffer address
conversionBin:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
stp x6,x7,[sp,-16]! // save registres
stp x8,x9,[sp,-16]! // save registres
mov x2,#0
mov x3,#0
1:
ldrb w4,[x0,x2]
cmp w4,#0 // string end
beq 10f
subs w4,w4,#0x30 // conversion digits
blt 5f
cmp w4,#10
blt 2f // digits 0 à 9 OK
cmp w4,#18 // < A ?
blt 5f
cmp w4,#24
sub w5,w4,#8 // letters A-F
csel w4,w5,w4,lt
blt 2f
cmp w4,#49 // < a ?
blt 5f
cmp w4,#54 // > f ?
bgt 5f
sub w4,w4,#39 // letters a-f
2: // x4 contains value on right 4 bits
mov x5,#0
add x3,x3,#4 // size ' bits
sub x7,x3,#1 // store indice
3:
tst x4,#1 // test first right bit
mov x6,#48 // character '0'
mov x8,#49 // character '1'
csel x6,x8,x6,ne
lsr x4,x4,1
strb w6,[x1,x7] // character -> display zone
sub x7,x7,#1 // prev position
add x5,x5,#1 // next bit
cmp x5,#4 // end ?
blt 3b
5: // loop to next byte
add x2,x2,#1
b 1b
10:
mov x6,#0
strb w6,[x1,x3] // zéro final
100:
ldp x8,x9,[sp],16 // restaur des 2 registres
ldp x6,x7,[sp],16 // restaur des 2 registres
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #REBOL | REBOL |
a1: [1 2 3]
a2: [4 5 6]
a3: [7 8 9]
append a1 a2 ; -> [1 2 3 4 5 6]
append/only a1 a3 ; -> [1 2 3 4 5 6 [7 8 9]]
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Red | Red | >> arr1: ["a" "b" "c"]
>> arr2: ["d" "e" "f"]
>> append arr1 arr2
== ["a" "b" "c" "d" "e" "f"]
>> arr3: [1 2 3]
>> insert arr1 arr3
>> arr1
== [1 2 3 "a" "b" "c" "d" "e" "f"]
>> arr4: [22 33 44]
== [22 33 44]
>> append/only arr1 arr4
== [1 2 3 "a" "b" "c" "d" "e" "f" [22 33 44]] |
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | 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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI or android 32 bits */
/* program asciiDiagram.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
/*******************************************/
/* Structures */
/********************************************/
/* Structure result */
.struct 0
res_name: //
.struct res_name + 4
res_startzone: //
.struct res_startzone + 4
res_endzone: //
.struct res_endzone + 4
res_size: //
.struct res_size + 4
res_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessDiagram: .asciz "Display diagramm :\n"
szMessValBin: .asciz "\nBinary Value :\n"
szMessValZone: .asciz "\nZones values : \n"
szMessResultTab: .asciz "Name @ start @ end @ size @ \n"
szMessSplitZone: .asciz "Name @ value : @ \n"
szMessErrSep: .asciz "Error : no séparator in first position of line.\n"
szMessErrlong: .asciz "Error : string hexa size not multiple to 4. \n"
szCarriageReturn: .asciz "\n"
szLine1: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
.equ LGLINE, . - szLine1
szLine2: .asciz "| ID |"
szLine3: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine4: .asciz "|QR| Opcode |AA|TC|RD|RA| Z | RCODE |"
szLine5: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine6: .asciz "| QDCOUNT |"
szLine7: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine8: .asciz "| ANCOUNT |"
szLine9: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine10: .asciz "| NSCOUNT |"
szLine11: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
szLine12: .asciz "| ARCOUNT |"
szLine13: .asciz "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
.equ NBLINES, (. - szLine1) / LGLINE
bSeparator: .byte '|'
szValueHex: .asciz "78477bbf5496e12e1bf169a4"
szValueHexTest: .asciz "0ABCDEFabcdef123"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
tbZones: .skip res_end * NBLINES * 5
sBuffer: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessDiagram
bl affichageMess
ldr r1,iAdrszLine1
mov r3,#LGLINE
mov r2,#0
1: @ display diagram lines
mla r0,r2,r3,r1
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
add r2,r2,#1
cmp r2,#NBLINES
blt 1b
ldr r0,iAdrszLine1 @ first line address of diagram
bl decode @ decode the diagram
mov r8,r0 @ save result number
mov r3,#0 @ indice
mov r4,#res_end @ one result size
ldr r5,iAdrtbZones @ table result address
2:
mla r6,r3,r4,r5 @ compute result offset
ldr r1,[r6,#res_name] @ zone name
ldr r0,iAdrszMessResultTab
bl strInsertAtCharInc @ insertion in message
mov r7,r0
ldr r0,[r6,#res_startzone]
ldr r1,iAdrsZoneConv
bl conversion10 @ call decimal conversion
mov r0,r7
ldr r1,iAdrsZoneConv @ insert value conversion in message
bl strInsertAtCharInc
mov r7,r0
ldr r0,[r6,#res_endzone]
ldr r1,iAdrsZoneConv @ else display odd message
bl conversion10 @ call decimal conversion
mov r0,r7
ldr r1,iAdrsZoneConv @ insert value conversion in message
bl strInsertAtCharInc
mov r7,r0
ldr r0,[r6,#res_size]
ldr r1,iAdrsZoneConv @ else display odd message
bl conversion10 @ call decimal conversion
mov r0,r7
ldr r1,iAdrsZoneConv @ insert value conversion in message
bl strInsertAtCharInc
mov r7,r0
bl affichageMess
bl libererPlace @ liberation heap area
add r3,r3,#1
cmp r3,r8
blt 2b
ldr r0,iAdrtbZones
ldr r1,iAdrszValueHex
//ldr r1,iAdrszValueHexTest
bl extractValue @ convert string value hexa in binary string
mov r7,r0 @ string binary address
ldr r0,iAdrszMessValZone
bl affichageMess
mov r0,r7
ldr r1,iAdrtbZones
mov r2,r8 @ result number
bl splitZone
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessResultTab: .int szMessResultTab
iAdrszMessDiagram: .int szMessDiagram
iAdrszMessValZone: .int szMessValZone
iAdrsZoneConv: .int sZoneConv
iAdrszLine1: .int szLine1
iAdrszValueHex: .int szValueHex
iAdrszValueHexTest: .int szValueHexTest
/***************************************************/
/* decode lines */
/***************************************************/
// r0 contains diagram address
// r0 return result counter
decode:
push {r1-r7,lr} @ save registers
mov r5,r0
mov r7,#LGLINE @ size line diagram
ldr r3,iAdrbSeparator @ séparator
ldrb r3,[r3]
ldr r1,iAdrtbZones @ result table address
mov r2,#0 @ result counter
mov r6,#1 @ line 2
1:
mla r0,r6,r7,r5 @ compute line offset
ldrb r4,[r0] @ load one byte
cmp r4,r3 @ separator ?
bne 99f @ no -> error
bl decodeOneLine @ decode a line
mov r2,r0 @ new result number
add r6,r6,#2 @ new line
cmp r6,#NBLINES @ end ?
blt 1b
mov r0,r2 @ return result counter
b 100f
99:
ldr r0,iAdrszMessErrSep
bl affichageMess
mov r0,#-1
100:
pop {r1-r7,lr} @ restaur registers
bx lr @ return
iAdrbSeparator: .int bSeparator
iAdrszMessErrSep: .int szMessErrSep
iAdrtbZones: .int tbZones
/***************************************************/
/* decode one line */
/***************************************************/
// r0 contains line diagram address
// r1 contains table result
// r2 contains result number
// r3 contains séparator
// r0 return new result number
decodeOneLine:
push {r1-r12,lr} @ save registers
mov r11,r0 @ save address diagram
mov r7,r1 @ save address table result
mov r4,r2 @ save result counter
mov r0,#0 @ zone size
mov r5,#-1 @ name text begin address
mov r6,r3 @ séparator
mov r8,#res_end
mov r10,#0 @ zone start
mov r12,#1 @ character indice
1:
ldrb r1,[r11,r12] @ load one byte
cmp r1,#0 @ line end ?
beq 10f
cmp r1,r6 @ separator ?
beq 3f
cmp r1,#' ' @ space ?
bne 2f
cmp r5,#0 @ text name found ?
mov r1,#0
strgeb r1,[r11,r12] @ yes -> 0 final text
add r0,r0,#1 @ increment zone size
add r12,r12,#1 @ new byte
b 1b @ and loop
2:
cmp r5,#0 @ text name found ?
addlt r5,r11,r12 @ no -> start zone
add r0,r0,#1 @ increment zone size
add r12,r12,#1 @ new byte
b 1b @ and loop
3: @ separator
cmp r5,#0 @ zone name ?
mov r1,#0
strgeb r1,[r11,r12] @ yes -> 0 final
mla r9,r4,r8,r7 @ compute result offset
str r5,[r9,#res_name] @ store address start name
add r0,r0,#1 @ compute zone size
cmp r0,#3
movle r1,#2
movgt r1,#3
bl division @ / by size characters zone
str r2,[r9,#res_size]
cmp r4,#0 @ first result ?
moveq r10,#0 @ yes -> start zone = 0
beq 4f
sub r10,r9,r8 @ else start zone = prev end zone + 1
ldr r10,[r10,#res_endzone]
add r10,r10,#1
4:
str r10,[r9,#res_startzone]
add r10,r10,r2 @ end zone = start zone + size - 1
sub r10,r10,#1
str r10,[r9,#res_endzone]
add r4,r4,#1 @ increment counter result
mov r0,#0 @ raz size zone
add r10,r10,#1 @ next byte
mov r5,#-1 @ no text name
add r12,r12,#1 @ next byte
b 1b @ and loop
10:
mov r0,r4 @ return result counter
100:
pop {r1-r12,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* convert strinh value hexa in binary string */
/***************************************************/
// r0 contains diagram address
// r1 contains string hex value
extractValue:
push {r1-r8,lr} @ save registers
mov r5,r0 @ save address
ldr r0,iAdrszMessValBin
bl affichageMess
mov r6,r1 @ save address string hexa
mov r2,#0
mov r3,#0
1: @ compute string size
ldrb r4,[r1,r2] @ load byte
cmp r4,#0 @ end string ?
addne r2,r2,#1
bne 1b
lsr r8,r2,#2 @ control if multiple of 4
lsl r3,r8,#2
cmp r3,r2
bne 99f @ no -> error
lsl r0,r2,#3 @ compute size string * 8
add r0,r0,#1 @ zero final
bl reserverPlace @ reserve array on the heap
mov r7,r0 @ address of heap array
mov r1,r0 @ for routine
mov r0,r6 @ address string value hexa
bl conversionBin @ conversion string hexa -> binary
mov r0,r7
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
mov r0,r7 @ return address string binary
b 100f
99:
ldr r0,iAdrszMessErrlong
bl affichageMess
mov r0,#-1
100:
pop {r1-r8,lr} @ restaur registers
bx lr @ return
iAdrszMessValBin: .int szMessValBin
iAdrszMessErrlong: .int szMessErrlong
/***************************************************/
/* decode lines */
/***************************************************/
// r0 contains address string binary
// r1 contains table zones address
// r2 contains result number
splitZone:
push {r1-r12,lr} @ save registers
mov r5,r0
mov r6,r1
mov r3,#0 @ indice table
mov r4,#0 @ indice string
mov r8,#res_end
1: @ loop
mla r7,r3,r8,r6 @ compute result offset
ldr r0,[r7,#res_startzone]
ldr r1,[r7,#res_size] @ zone size
ldr r12,iAdrsBuffer
mov r9,#0
add r0,r0,r5
2: @ copy bytes
ldrb r10,[r0,r9]
strb r10,[r12,r9]
add r9,r9,#1
cmp r9,r1 @ zone size maxi ?
blt 2b @ no -> loop
mov r10,#0 @ 0 final
str r10,[r12,r9]
@ dislay name and value
ldr r0,iAdrszMessSplitZone
ldr r1,[r7,#res_name]
bl strInsertAtCharInc
mov r1,r12
bl strInsertAtCharInc
bl affichageMess
bl libererPlace
add r3,r3,#1
cmp r3,r2 @ end result ?
blt 1b @ no -> loop
100:
pop {r1-r12,lr} @ restaur registers
bx lr @ return
iAdrszMessSplitZone: .int szMessSplitZone
iAdrsBuffer: .int sBuffer
/***************************************************/
/* conversion chaine hexa en */
/***************************************************/
// r0 contains string address
// r1 contains buffer address
conversionBin:
push {r2-r7,lr} @ save registers
mov r2,#0
mov r3,#0
1:
ldrb r4,[r0,r2]
cmp r4,#0 @ string end
beq 10f
subs r4,r4,#0x30 @ conversion digits
blt 5f
cmp r4,#10
blt 2f @ digits 0 à 9 OK
cmp r4,#18 @ < A ?
blt 5f
//vidregtit inter
cmp r4,#24
sublt r4,r4,#8 @ letters A-F
blt 2f
cmp r4,#49 @ < a ?
blt 5f
cmp r4,#54 @ > f ?
bgt 5f
sub r4,r4,#39 @ letters a-f
2: @ r4 contains value on right 4 bits
mov r5,#0
add r3,r3,#4 @ size bits
sub r7,r3,#1 @ store indice
3:
lsrs r4,#1 @ right bit in carry
movcc r6,#48 @ flag carry off character '0'
movcs r6,#49 @ flag carry on character '1'
strb r6,[r1,r7] @ character -> display zone
sub r7,r7,#1 @ prev position
add r5,r5,#1 @ next bit
cmp r5,#4 @ end ?
blt 3b
5: @ loop to next byte
add r2,r2,#1
b 1b
10:
mov r6,#0
strb r6,[r1,r3] @ zéro final
100:
pop {r2-r7,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #ReScript | ReScript | Js.Array2.concat(["a", "b"], ["c", "d", "e"]) == ["a", "b", "c", "d", "e"] |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Retro | Retro | { #1 #2 #3 } { #4 #5 #6 } a:append |
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | 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.
| #C | C |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
enum { MAX_ROWS=14, MAX_NAMES=20, NAME_SZ=80 };
char *Lines[MAX_ROWS] = {
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ID |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" |QR| Opcode |AA|TC|RD|RA| Z | RCODE |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | QDCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ANCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | NSCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+",
" | ARCOUNT |",
" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
};
typedef struct {
unsigned bit3s;
unsigned mask;
unsigned data;
char A[NAME_SZ+2];
}NAME_T;
NAME_T names[MAX_NAMES];
unsigned idx_name;
enum{ID,BITS,QDCOUNT,ANCOUNT,NSCOUNT,ARCOUNT,MAX_HDR};
unsigned header[MAX_HDR]; // for test
unsigned idx_hdr;
int bit_hdr(char *pLine);
int bit_names(char *pLine);
void dump_names(void);
void make_test_hdr(void);
int main(void){
char *p1; int rv;
printf("Extract meta-data from bit-encoded text form\n");
make_test_hdr();
idx_name = 0;
for( int i=0; i<MAX_ROWS;i++ ){
p1 = Lines[i];
if( p1==NULL ) break;
if( rv = bit_hdr(Lines[i]), rv>0) continue;
if( rv = bit_names(Lines[i]),rv>0) continue;
//printf("%s, %d\n",p1, numbits );
}
dump_names();
}
int bit_hdr(char *pLine){ // count the '+--'
char *p1 = strchr(pLine,'+');
if( p1==NULL ) return 0;
int numbits=0;
for( int i=0; i<strlen(p1)-1; i+=3 ){
if( p1[i] != '+' || p1[i+1] != '-' || p1[i+2] != '-' ) return 0;
numbits++;
}
return numbits;
}
int bit_names(char *pLine){ // count the bit-group names
char *p1,*p2 = pLine, tmp[80];
unsigned sz=0, maskbitcount = 15;
while(1){
p1 = strchr(p2,'|'); if( p1==NULL ) break;
p1++;
p2 = strchr(p1,'|'); if( p2==NULL ) break;
sz = p2-p1;
tmp[sz] = 0; // set end of string
int k=0;
for(int j=0; j<sz;j++){ // strip spaces
if( p1[j] > ' ') tmp[k++] = p1[j];
}
tmp[k]= 0; sz++;
NAME_T *pn = &names[idx_name++];
strcpy(&pn->A[0], &tmp[0]);
pn->bit3s = sz/3;
if( pn->bit3s < 16 ){
for( int i=0; i<pn->bit3s; i++){
pn->mask |= 1 << maskbitcount--;
}
pn->data = header[idx_hdr] & pn->mask;
unsigned m2 = pn->mask;
while( (m2 & 1)==0 ){
m2>>=1;
pn->data >>= 1;
}
if( pn->mask == 0xf ) idx_hdr++;
}
else{
pn->data = header[idx_hdr++];
}
}
return sz;
}
void dump_names(void){ // print extracted names and bits
NAME_T *pn;
printf("-name-bits-mask-data-\n");
for( int i=0; i<MAX_NAMES; i++ ){
pn = &names[i];
if( pn->bit3s < 1 ) break;
printf("%10s %2d X%04x = %u\n",pn->A, pn->bit3s, pn->mask, pn->data);
}
puts("bye..");
}
void make_test_hdr(void){
header[ID] = 1024;
header[QDCOUNT] = 12;
header[ANCOUNT] = 34;
header[NSCOUNT] = 56;
header[ARCOUNT] = 78;
// QR OP AA TC RD RA Z RCODE
// 1 0110 1 0 1 0 000 1010
// 1011 0101 0000 1010
// B 5 0 A
header[BITS] = 0xB50A;
}
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #REXX | REXX | a.1 = 10
a.2 = 22.7
a.7 = -12 |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Ring | Ring |
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
see arr4
see nl
arr5 = arr4 + arr3
see arr5
|
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | 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.
| #C.2B.2B | C++ | #include <array>
#include <bitset>
#include <iostream>
using namespace std;
struct FieldDetails {string_view Name; int NumBits;};
// parses the ASCII diagram and returns the field name, bit sizes, and the
// total byte size
template <const char *T> consteval auto ParseDiagram()
{
// trim the ASCII diagram text
constexpr string_view rawArt(T);
constexpr auto firstBar = rawArt.find("|");
constexpr auto lastBar = rawArt.find_last_of("|");
constexpr auto art = rawArt.substr(firstBar, lastBar - firstBar);
static_assert(firstBar < lastBar, "ASCII Table has no fields");
// make an array for all of the fields
constexpr auto numFields =
count(rawArt.begin(), rawArt.end(), '|') -
count(rawArt.begin(), rawArt.end(), '\n') / 2;
array<FieldDetails, numFields> fields;
// parse the diagram
bool isValidDiagram = true;
int startDiagramIndex = 0;
int totalBits = 0;
for(int i = 0; i < numFields; )
{
auto beginningBar = art.find("|", startDiagramIndex);
auto endingBar = art.find("|", beginningBar + 1);
auto field = art.substr(beginningBar + 1, endingBar - beginningBar - 1);
if(field.find("-") == field.npos)
{
int numBits = (field.size() + 1) / 3;
auto nameStart = field.find_first_not_of(" ");
auto nameEnd = field.find_last_not_of(" ");
if (nameStart > nameEnd || nameStart == string_view::npos)
{
// the table cannot be parsed
isValidDiagram = false;
field = ""sv;
}
else
{
field = field.substr(nameStart, 1 + nameEnd - nameStart);
}
fields[i++] = FieldDetails {field, numBits};
totalBits += numBits;
}
startDiagramIndex = endingBar;
}
int numRawBytes = isValidDiagram ? (totalBits - 1) / 8 + 1 : 0;
return make_pair(fields, numRawBytes);
}
// encode the values of the fields into a raw data array
template <const char *T> auto Encode(auto inputValues)
{
constexpr auto parsedDiagram = ParseDiagram<T>();
static_assert(parsedDiagram.second > 0, "Invalid ASCII talble");
array<unsigned char, parsedDiagram.second> data;
int startBit = 0;
int i = 0;
for(auto value : inputValues)
{
const auto &field = parsedDiagram.first[i++];
int remainingValueBits = field.NumBits;
while(remainingValueBits > 0)
{
// pack the bits from an input field into the data array
auto [fieldStartByte, fieldStartBit] = div(startBit, 8);
int unusedBits = 8 - fieldStartBit;
int numBitsToEncode = min({unusedBits, 8, field.NumBits});
int divisor = 1 << (remainingValueBits - numBitsToEncode);
unsigned char bitsToEncode = value / divisor;
data[fieldStartByte] <<= numBitsToEncode;
data[fieldStartByte] |= bitsToEncode;
value %= divisor;
startBit += numBitsToEncode;
remainingValueBits -= numBitsToEncode;
}
}
return data;
}
// decode the raw data into the format of the ASCII diagram
template <const char *T> void Decode(auto data)
{
cout << "Name Bit Pattern\n";
cout << "======= ================\n";
constexpr auto parsedDiagram = ParseDiagram<T>();
static_assert(parsedDiagram.second > 0, "Invalid ASCII talble");
int startBit = 0;
for(const auto& field : parsedDiagram.first)
{
// unpack the bits from the data into a single field
auto [fieldStartByte, fieldStartBit] = div(startBit, 8);
unsigned char firstByte = data[fieldStartByte];
firstByte <<= fieldStartBit;
firstByte >>= fieldStartBit;
int64_t value = firstByte;
auto endBit = startBit + field.NumBits;
auto [fieldEndByte, fieldEndBit] = div(endBit, 8);
fieldEndByte = min(fieldEndByte, (int)(ssize(data) - 1));
for(int index = fieldStartByte + 1; index <= fieldEndByte; index++)
{
value <<= 8;
value += data[index];
}
value >>= fieldEndBit;
startBit = endBit;
cout << field.Name <<
string_view(" ", (7 - field.Name.size())) << " " <<
string_view(bitset<64>(value).to_string()).substr(64 - field.NumBits, 64) << "\n";
}
}
int main(void)
{
static constexpr char art[] = R"(
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+)";
// using the table above, encode the data below
auto rawData = Encode<art> (initializer_list<int64_t> {
30791,
0, 15, 0, 1, 1, 1, 3, 15,
21654,
57646,
7153,
27044
});
cout << "Raw encoded data in hex:\n";
for (auto v : rawData) printf("%.2X", v);
cout << "\n\n";
cout << "Decoded raw data:\n";
Decode<art>(rawData);
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #RLaB | RLaB |
>> x = [1, 2, 3]
>> y = [4, 5, 6]
// appending matrix 'y' on the right from matrix 'x' is possible if the two matrices have
// the same number of rows:
>> z1 = [x, y]
matrix columns 1 thru 6
1 2 3 4 5 6
// stacking matrix 'y' below the matrix 'x' is possible if the two matrices have
// the same number of columns:
>> z2 = [x; y]
1 2 3
4 5 6
>>
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Ruby | Ruby | arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2 # => [1, 2, 3, 4, 5, 6]
arr4.concat(arr3) # => [1, 2, 3, 4, 5, 6, 7, 8, 9] |
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | 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.
| #D | D | string makeStructFromDiagram(in string rawDiagram) pure @safe {
import std.conv: text;
import std.format: format;
import std.string: strip, splitLines, indexOf;
import std.array: empty, popFront;
static void commitCurrent(ref uint anonCount,
ref uint totalBits,
ref size_t currentBits,
ref string code,
ref string currentName) pure @safe {
if (currentBits) {
code ~= "\t";
currentName = currentName.strip;
if (currentName.empty) {
anonCount++;
currentName = "anonymous_field_" ~ anonCount.text;
}
string type;
if (currentBits == 1)
type = "bool";
else if (currentBits <= ubyte.sizeof * 8)
type = "ubyte";
else if (currentBits <= ushort.sizeof * 8)
type = "ushort";
else if (currentBits <= uint.sizeof * 8)
type = "uint";
else if (currentBits <= ulong.sizeof * 8)
type = "ulong";
//else if (currentBits <= ucent.sizeof * 8)
// type = "ucent";
else assert(0, "Too many bits for the item " ~ currentName);
immutable byteOffset = totalBits / 8;
immutable bitOffset = totalBits % 8;
// Getter:
code ~= "@property " ~ type ~ " " ~ currentName ~
"() const pure nothrow @safe {\n";
code ~= "\t\t";
if (currentBits == 1) {
code ~= format("return (_payload[%d] & (1 << (7-%d))) ? true : false;",
byteOffset, bitOffset);
} else if (currentBits < 8) {
auto mask = (1 << currentBits) - 1;
mask <<= 7 - bitOffset - currentBits + 1;
code ~= format("return (_payload[%d] & 0b%08b) >> %d;",
byteOffset, mask, 7 - bitOffset - currentBits + 1);
} else {
assert(currentBits % 8 == 0);
assert(bitOffset == 0);
code ~= type ~ " v = 0;\n\t\t";
code ~= "version(LittleEndian) {\n\t\t";
foreach (immutable i; 0 .. currentBits / 8)
code ~= "\tv |= (cast(" ~ type ~ ") _payload[" ~
text(byteOffset + i) ~ "]) << (" ~
text((currentBits / 8) - i - 1) ~
" * 8);\n\t\t";
code ~= "} else static assert(0);\n\t\t";
code ~= "return v;";
}
code ~= "\n";
code ~= "\t}\n\t";
// Setter:
code ~= "@property void " ~ currentName ~ "(in " ~ type ~
" value) pure nothrow @safe {\n";
code ~= "\t\t";
if (currentBits < 8) {
auto mask = (1 << currentBits) - 1;
mask <<= 7 - bitOffset - currentBits + 1;
code ~= format("_payload[%d] &= ~0b%08b;\n\t\t",
byteOffset, mask);
code ~= "assert(value < " ~ text(1 << currentBits) ~
");\n\t\t";
code~=format("_payload[%d] |= cast(ubyte) value << %d;",
byteOffset, 7 - bitOffset - currentBits + 1);
} else {
assert(currentBits % 8 == 0);
assert(bitOffset == 0);
code ~= "version(LittleEndian) {\n\t\t";
foreach (immutable i; 0 .. currentBits / 8)
code ~= "\t_payload[" ~ text(byteOffset + i) ~
"] = (value >> (" ~
text((currentBits / 8) - i - 1) ~
" * 8) & 0xff);\n\t\t";
code ~= "} else static assert(0);";
}
code ~= "\n";
code ~= "\t}\n";
totalBits += currentBits;
}
currentBits = 0;
currentName = null;
}
enum C : char { pipe='|', cross='+' }
enum cWidth = 3; // Width of a bit cell in the table.
immutable diagram = rawDiagram.strip;
size_t bitCountPerRow = 0, currentBits;
uint anonCount = 0, totalBits;
string currentName;
string code = "struct {\n"; // Anonymous.
foreach (line; diagram.splitLines) {
assert(!line.empty);
line = line.strip;
if (line[0] == C.cross) {
commitCurrent(anonCount, totalBits, currentBits, code, currentName);
if (bitCountPerRow == 0)
bitCountPerRow = (line.length - 1) / cWidth;
else
assert(bitCountPerRow == (line.length - 1) / cWidth);
} else {
// A field of some sort.
while (line.length > 2) {
assert(line[0] != '/',
"Variable length data not supported");
assert(line[0] == C.pipe, "Malformed table");
line.popFront;
const idx = line[0 .. $ - 1].indexOf(C.pipe);
if (idx != -1) {
const field = line[0 .. idx];
line = line[idx .. $];
commitCurrent(anonCount, totalBits, currentBits, code, currentName);
currentName = field;
currentBits = (field.length + 1) / cWidth;
commitCurrent(anonCount, totalBits, currentBits, code, currentName);
} else {
// The full row or a continuation of the last.
currentName ~= line[0 .. $ - 1];
// At this point, line does not include the first
// C.pipe, but the length will include the last.
currentBits += line.length / cWidth;
line = line[$ .. $];
}
}
}
}
// Using bytes to avoid endianness issues.
// hopefully the compiler will optimize it, otherwise
// maybe we could specialize the properties more.
code ~= "\n\tprivate ubyte[" ~ text((totalBits + 7) / 8) ~ "] _payload;\n";
return code ~ "}";
}
void main() { // Testing.
import std.stdio;
enum diagram = "
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+";
// To debug the code generation:
//pragma(msg, diagram.makeStructFromDiagram);
// Usage.
static struct Header {
mixin(diagram.makeStructFromDiagram);
}
Header h;
h.ID = 10;
h.RA = true;
h.ARCOUNT = 255;
h.Opcode = 7;
// See the byte representation to test the setter's details.
h._payload.writeln;
// Test the getters:
assert(h.ID == 10);
assert(h.RA == true);
assert(h.ARCOUNT == 255);
assert(h.Opcode == 7);
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Rust | Rust | fn main() {
let a_vec = vec![1, 2, 3, 4, 5];
let b_vec = vec![6; 5];
let c_vec = concatenate_arrays(&a_vec, &b_vec);
println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}
fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
let mut concat = x.to_vec();
concat.extend_from_slice(y);
concat
}
|
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #S-lang | S-lang | variable a = [1, 2, 3];
variable b = [4, 5, 6], c; |
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | 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.
| #Go | Go | package main
import (
"fmt"
"log"
"math/big"
"strings"
)
type result struct {
name string
size int
start int
end int
}
func (r result) String() string {
return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end)
}
func validate(diagram string) []string {
var lines []string
for _, line := range strings.Split(diagram, "\n") {
line = strings.Trim(line, " \t")
if line != "" {
lines = append(lines, line)
}
}
if len(lines) == 0 {
log.Fatal("diagram has no non-empty lines!")
}
width := len(lines[0])
cols := (width - 1) / 3
if cols != 8 && cols != 16 && cols != 32 && cols != 64 {
log.Fatal("number of columns should be 8, 16, 32 or 64")
}
if len(lines)%2 == 0 {
log.Fatal("number of non-empty lines should be odd")
}
if lines[0] != strings.Repeat("+--", cols)+"+" {
log.Fatal("incorrect header line")
}
for i, line := range lines {
if i == 0 {
continue
} else if i%2 == 0 {
if line != lines[0] {
log.Fatal("incorrect separator line")
}
} else if len(line) != width {
log.Fatal("inconsistent line widths")
} else if line[0] != '|' || line[width-1] != '|' {
log.Fatal("non-separator lines must begin and end with '|'")
}
}
return lines
}
func decode(lines []string) []result {
fmt.Println("Name Bits Start End")
fmt.Println("======= ==== ===== ===")
start := 0
width := len(lines[0])
var results []result
for i, line := range lines {
if i%2 == 0 {
continue
}
line := line[1 : width-1]
for _, name := range strings.Split(line, "|") {
size := (len(name) + 1) / 3
name = strings.TrimSpace(name)
res := result{name, size, start, start + size - 1}
results = append(results, res)
fmt.Println(res)
start += size
}
}
return results
}
func unpack(results []result, hex string) {
fmt.Println("\nTest string in hex:")
fmt.Println(hex)
fmt.Println("\nTest string in binary:")
bin := hex2bin(hex)
fmt.Println(bin)
fmt.Println("\nUnpacked:\n")
fmt.Println("Name Size Bit pattern")
fmt.Println("======= ==== ================")
for _, res := range results {
fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1])
}
}
func hex2bin(hex string) string {
z := new(big.Int)
z.SetString(hex, 16)
return fmt.Sprintf("%0*b", 4*len(hex), z)
}
func main() {
const diagram = `
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
`
lines := validate(diagram)
fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n")
for _, line := range lines {
fmt.Println(line)
}
fmt.Println("\nDecoded:\n")
results := decode(lines)
hex := "78477bbf5496e12e1bf169a4" // test string
unpack(results, hex)
} |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #SASL | SASL | (1 2 3) ++ (4 5 6) |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Scala | Scala | val arr1 = Array( 1, 2, 3 )
val arr2 = Array( 4, 5, 6 )
val arr3 = Array( 7, 8, 9 )
arr1 ++ arr2 ++ arr3
//or:
Array concat ( arr1, arr2, arr3 )
// res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9) |
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | 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.
| #Haskell | Haskell | import Text.ParserCombinators.ReadP
import Control.Monad (guard)
data Field a = Field { fieldName :: String
, fieldSize :: Int
, fieldValue :: Maybe a}
instance Show a => Show (Field a) where
show (Field n s a) = case a of
Nothing -> n ++ "\t" ++ show s
Just x -> n ++ "\t" ++ show s ++ "\t" ++ show x
newtype Data a = Data { fields :: [Field a] }
instance Show a => Show (Data a) where
show (Data fs) = "NAME\tSIZE\tVALUE\n" ++ unlines (show <$> fs)
instance Read (Data a) where
readsPrec _ = readP_to_S parseData
parseData = do n <- parseHeader
guard (n `elem` [8,16,32,64]) -- check size of the table
Data . concat <$> many1 (parseRow n)
where
parseRow n = do
fs <- char '|' *> many parseField <* char '\n'
guard $ sum (fieldSize <$> fs) == n -- check that size of all fields match the row size
m <- parseHeader
guard $ m == n -- check that all rows have the same size
return fs
parseHeader = do
char '+'
n <- length <$> many1 (string "--+")
char '\n'
return n
parseField = do
s1 <- many (char ' ')
f <- munch1 $ not . (`elem` " |")
s2 <- many (char ' ')
char '|'
let n = (length (s1 ++ f ++ s2) + 1) `div` 3
return $ Field f n Nothing
-- emulation of reading a stream of bits
readData :: Data a -> [b] -> Data [b]
readData d = Data . go (fields d)
where
go fs [] = (\f -> f {fieldValue = Nothing}) <$> fs
go (f:fs) s =
let (x, xs) = splitAt (fieldSize f) s
in f {fieldValue = Just x} : go fs xs
diagram = unlines
["+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
,"| ID |"
,"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
,"|QR| Opcode |AA|TC|RD|RA| Z | RCODE |"
,"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
,"| QDCOUNT |"
,"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
,"| ANCOUNT |"
,"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
,"| NSCOUNT |"
,"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"
,"| ARCOUNT |"
,"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"]
dataSample = concat
["011110000100011101111011101111110101010010010110",
"111000010010111000011011111100010110100110100100"]
|