How to convert array of ints to string? - arrays

I need convert array of ints to string. Following code doing it, but in result I am getting unwanted symbols [ ]
import std.stdio;
import std.conv;
void main()
{
int [] x = [1,3,4,6];
string s = to!string(x);
writeln(s);
}
output: [1, 3, 4, 6]
How I can remove brackets without hack with replace?

You can do it for example like this:
import std.stdio;
import std.conv;
import std.algorithm;
void main()
{
int [] x = [1,3,4,6];
writeln(x.map!(to!string).joiner(", "));
}

You can use std.format
import std.format;
import std.stdio;
void main()
{
auto res = format("%(%s, %)", [1,2,3,4,5]);
writeln(res); // output: 1, 2, 3, 4, 5
}

Related

Why this code doesn't work in Kotlin Playground or other IDEs?

import kotlin.collections.maxByOrNull
import kotlin.test.*
fun main() {
var inputArray = mutableListOf(3, 6, -2, -5, 7, 3)
solution(inputArray)
}
fun solution(inputArray: MutableList<Int>): Int {
return inputArray.zipWithNext(Int::times).maxOrNull() ?: 0
}
I tried to test this answer in my browser but I can't.
Your code is working but you are not using the result of solution method.
fun main() {
var inputArray = mutableListOf(3, 6, -2, -5, 7, 3)
val output = solution(inputArray)
// do something with output. At least print it to see
println("output is $output") // output is 21
}
fun solution(inputArray: MutableList<Int>): Int {
return inputArray.zipWithNext(Int::times).maxOrNull() ?: 0
}

How to avoid "unconstrained generic constant" with dependent associated constants in traits?

I am in the process of writing a trait with two associated constants: the first is a usize, and the other is an array of usize where with a length equal to the first constant. Essentially, my trait is equivalent to the following:
#![feature(const_trait_impl)]
#![feature(generic_const_exprs)]
trait Foo {
const SIZE: usize;
const ARR: [usize; Self::SIZE];
}
struct S;
impl const Foo for S {
const SIZE: usize = 2;
const ARR: [usize; Self::SIZE] = [1, 2];
}
fn main() {
const TEST: &[usize; 2] = &S::ARR;
println!("{:?}", TEST);
}
As of the current nightly build, this trait definition produces the following error:
error: unconstrained generic constant
--> src\main.rs:6:5
|
6 | const ARR: [usize; Self::SIZE];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: try adding a `where` bound using this expression: `where [(); Self::SIZE]:`
Unfortunately, the suggested fix is not useful because any where bound involving Self::SIZE would be infinitely recursive. I was ready to give up until I discovered an alternative that seems to work:
#![feature(const_trait_impl)]
#![feature(generic_const_exprs)]
trait Bar {
const SIZE: usize;
fn arr() -> [usize; Self::SIZE];
}
struct S;
impl const Bar for S {
const SIZE: usize = 2;
fn arr() -> [usize; Self::SIZE] {
[1,2]
}
}
fn main() {
const TEST: &[usize; 2] = &S::arr();
println!("{:?}", TEST);
}
I am rather perplexed by this discrepancy, all things considered. Is there any way around it, or is it mostly just a matter of waiting for const language support to improve?
You can do as follows
trait Foo<const N : usize>{
const ARR : [usize; N];
}
struct S;
impl Foo<2> for S{
const ARR : [usize; 2] = [1, 2];
}
impl Foo<3> for S{
const ARR : [usize; 3] = [1, 2, 3];
}
fn main(){
const TEST : &[usize; 2] = &S::ARR;
println!("{:?}", TEST); // [1, 2]
const TEST2 : &[usize; 3] = &S::ARR;
println!("{:?}", TEST2); // [1, 2, 3]
}

Read JSON questions file - JAVA game

I have the following JSON file with questions and answer options.
And the code I used trying to print the questions.
{
"GameName": "millionaire game",
"level": 1,
"questions": [
{
"question1": "What is the minimum of players in a footbal game?",
"options1": [
8,
10,
9,
7
],
"answer1": "7"
},
{
"question2": "Who scored maximum goal footbal game?",
"options2": [
"Jhon",
"Pitty",
"Richard",
"Mike"
],
"answer2": "Mike"
},
{
"question3": "What is the maximum of players in a footbal game?",
"options3": [
8,
10,
9,
7
],
"answer3": "7"
}
]
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Random;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.*;
public class readJson {
public static void main(String[] args) throws JSONException {
String first = "jsonPerguntas2.json";
try {
String content = new String((Files.readAllBytes(Paths.get(first))));
JSONObject o = new JSONObject(content);
JSONArray firstQuestion = o.getJSONArray("question1");
//System.out.println(conteudo);
for (int i=0; i<firstQuestion.length(); i++){
System.out.println(firstQuestion.get(i));
}
} catch (IOException e) {
}
}
}
I have this code to read the file. But it always return the same error:
Exception in thread "main" org.json.JSONException: JSONObject["question1"] not found.
at org.json.JSONObject.get(JSONObject.java:454)
at org.json.JSONObject.getJSONArray(JSONObject.java:535)
at TrabPraticoJava.TesteLerJson.main(TesteLerJson.java:37)
C:\Users\José Dias\Documents\NetBeansProjects\TrabPraticoJava\nbproject\build-impl.xml:1341: The following error occurred while executing this line:
C:\Users\José Dias\Documents\NetBeansProjects\TrabPraticoJava\nbproject\build-impl.xml:936: Java returned: 1
BUILD FAILED (total time: 0 seconds)
If I change the line JSONArray firstQuestion = o.getJSONArray("question1"); to JSONArray firstQuestion = o.getJSONArray("questions"); it actually prints the all file but I want to print the questions separately.
Can someone help me out?
Thanks in advance
Try this:
JSONArray questions = o.getJSONArray("questions");
for (int i = 0; i < questions.length(); i++) {
JSONObject question = recs.getJSONObject(i);
System.out.println(question.getInt("question"+i+1));
}

How to tell TypeScript that I'm returning an array of arrays of the input type?

I have a function that chunks arrays:
const chunkArray = (inputArray: any[], chunks: number) => {
const chunkedArray = [];
let i = 0;
const n = inputArray.length;
while (i < n) {
chunkedArray.push(inputArray.slice(i, (i += chunks)));
}
return chunkedArray;
};
export default chunkArray;
I would like my linter to know for a given input array, what the output array looks like. For example for
const chunkedArrays = chunkArray([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
my linter should now, that chunkedArrays is an array of arrays of numbers. Currently it says it's an array of arrays of any.
How can I achieve that?
You need to add a generic type parameter to your function. The type parameter will capture the actual type of the elements in the input array and then you can use this generic type to specify how it relates to your result:
const chunkArray = <T>(inputArray: T[], chunks: number) => {
const chunkedArray: T[][] = []; // use T as the type for chunkedArray
let i = 0;
const n = inputArray.length;
while (i < n) {
chunkedArray.push(inputArray.slice(i, (i += chunks)));
}
return chunkedArray;
};
const chunkedArrays = chunkArray([1, 2, 3, 4, 5], 2); // number[][]
const chunkedArraysString = chunkArray(["1", "2", "3", "4", "5"], 2); // string[][]

TypeScript/React how does scan operator work where currentvalue = function interface?

I have a scan operator with the following arguments:
.scan(function (acc:Message[], x: (msg: Message[]) => Message[]){ return x(acc); }, initialMessages)
my question is what return x(acc) returns actually? how does the accumulator function work in this particular case?
I am quite new to TypeScript and lambda expressions, so any help is much appreciated.
In this case the type of x(acc) would be Message[]. You can tell this from the signature of the 2nd argument x, which returns Message[].
Usually scan() accepts a function (acc, val) => ... with accumulator and value. and emits the returned value. In this case the emitted value val entering the scan operator is a closure. it's a bit unusual, but perfectly fine. An example which outputs
[ 1, 2, 3 ]
[ 3, 4, 5 ]
[ 4, 5, 6 ]
...would be:
import { Observable } from 'rxjs/Rx';
type Message = number;
function scanFn(acc: Message[], x: (msg: Message[]) => Message[]): Message[] {
return x(acc);
}
function mapFn(val: Message): (msg: Message[]) => Message[] {
return x => x.map((y, i) => val + i);
}
Observable.from([1, 3, 4])
.map(mapFn)
.scan(scanFn, [1, 2, 3])
.subscribe(console.log);

Resources