Following code generates error which looks like an error in compiler, its has nothing to do with the kotlin code, or maybe I am missing something? I have JDK error on macos and some more informative error (like pasted at the end of this post) from online compiler. How can I fix it?
Code: https://pl.kotl.in/CfdXHeDyn
import kotlin.math.pow
fun calculateNumberOfContainers(data: String): Int {
val containerSizes = mutableListOf<Int>()
data.lines().forEach { containerSizes.add(it.toInt()) }
var foundCorrect = 0
val maxSubSets = (2.0).pow(20).toULong()
for (n in 0UL until maxSubSets) {
var total = 0
for (k in 0 until 20) {
val mask = 1UL shl k
if ((mask and n) != 0UL) {
total += containerSizes[k]
if (total > 150)
break
}
}
if (total == 150)
foundCorrect++
}
return foundCorrect
}
fun runcode() {
val data =
"""
33
14
18
20
45
35
16
35
1
13
18
13
50
44
48
6
24
41
30
42
""".trimIndent()
calculateNumberOfContainers(data)
}
fun main() {
runcode()
}
Error:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('#' (code 35)): was expecting double-quote to start field name
at [Source: (String)"{#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007fc646ef2eba, pid=1900, tid=0x00007fc6307f7700
#
# JRE version: OpenJDK Runtime Environment (8.0_201-b09) (build 1.8.0_201-b09)
# Java VM: OpenJDK 64-Bit Server VM (25.201-b09 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# V [libjvm.so+0x382eba]
#
# Core dump written. Default location: /var/task/core or core.1900
#
# An error report file with more information is saved as:
# /tmp/"[truncated 195 chars]; line: 1, column: 3]
at com.fasterxml.jackson.core.JsonParser._constructError (JsonParser.java:1851)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError (ParserMinimalBase.java:707)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar (ParserMinimalBase.java:632)
Update:
it works with 1.4.30, fails with 1.5.21, so its a bug in compiler
I changed from Unsigned Long to Unsigned Int and problem went away, code after changes looks as follows:
https://pl.kotl.in/XedacixZK
import kotlin.math.pow
fun calculateNumberOfContainers(data: String): Int {
val containerSizes = mutableListOf<Int>()
data.lines().forEach { containerSizes.add(it.toInt()) }
var foundCorrect = 0
val maxSubSets = (2.0).pow(20).toUInt()
for (n in 0U until maxSubSets) {
var total = 0
for (k in 0 until 20) {
val mask = 1U shl k
if ((mask and n) != 0U) {
total += containerSizes[k]
if (total > 150)
break
}
}
if (total == 150)
foundCorrect++
}
return foundCorrect
}
fun runcode() {
val data =
"""
33
14
18
20
45
35
16
35
1
13
18
13
50
44
48
6
24
41
30
42
""".trimIndent()
print(calculateNumberOfContainers(data))
}
fun main() {
runcode()
}
Related
> 1 package com.linecorp.exam
> 2
> 3 import android.os.Bundle
> 4 import android.widget.TextView
> 5 import android.app.Activity
> 6 import android.graphics.Color
> 7 import android.view.Gravity
> 8 import android.view.View
> 9 import android.view.ViewGroup
> 10 import android.widget.BaseAdapter
> 11 import android.widget.ListView
> 12
> 13 class MainActivity : Activity() {
> 14
> 15 enum class taskstate {
> 16 todo,
> 17 done
> 18 }
> 19
> 20 var tasklist = mutableListOf<Pair<String, taskstate>>()
> 21
> 22 private lateinit var myadapter: Myadapter
> 23
> 24 override fun onCreate(savedInstanceState: Bundle?) {
> 25 super.onCreate(savedInstanceState)
> 26 setContentView(R.layout.activity_main)
> 27
> 28 myadapter = Myadapter()
> 29 val listView = findViewById<ListView>(R.id.list_view)
> 30 listView.adapter = myadapter
> 31
> 32 tasklist.clear()
> 33 var i = 0
> 34 todoRepository.instance.fetch_all().forEach { t ->
> 35 tasklist.add(i++, t)
> 36 myadapter.notifyDataSetChanged()
> 37 }
> 38 }
> 39
> 40 override fun onDestroy() {
> 41 tasklist.clear()
> 42 }
> 43
> 44 inner class Myadapter : BaseAdapter() {
> 45
> 46 private lateinit var convertView: View
> 47
> 48 override fun getCount(): Int {
> 49 return tasklist.size
> 50 }
> 51
> 52 override fun getItem(position: Int): Any {
> 53 val li = tasklist.filter { it.second == taskstate.todo } +
> 54 tasklist.filter { it.second == taskstate.done }
> 55 return li[position]
> 56 }
> 57
> 58 override fun getItemId(position: Int): Long {
> 59 return 0
> 60 }
> 61
> 62 override fun getView(position: Int, convertView: View?, container: ViewGroup?): View {
> 63 this.convertView = if (convertView == null) {
> 64 layoutInflater.inflate(R.layout.list_item, container, false)
> 65 } else {
> 66 convertView
> 67 }
> 68
> 69 val i = getItem(position) as Pair<String, taskstate>
> 70 this.convertView.findViewById<TextView>(R.id.item_label)
> 71 .apply {
> 72 when (i.second) {
> 73 taskstate.todo -> {
> 74 setText("TODO")
> 75 setBackgroundColor(Color.YELLOW)
> 76 }
> 77 else -> {
> 78 setText("DONE")
> 79 }
> 80 }
> 81 }
> 82 this.convertView.findViewById<TextView>(R.id.item_text)
> 83 .setText(i.first)
> 84
> 85 return convertView!!
> 86 }
> 87 }
> 88 }`enter code here`
This was a question I got when I appeared for an test. Unfortunately I failed :) The question was how to improve this Kotlin Android code and add necessary comments if needed. (please dont consider this line ipsum dfgsdndd gfnjfn vjfnvkf fjnvkfv vnkdkvd dndk. sds dshdsd shdahd sdiauhd basudsua saudhaus sahdsuahd ashdoahsd shdoahd ashdosahd asdhoaishd )
The problem here is you are returning total if s1<s2 while that's not the case. Even if you find one such case, that's not the end of string, you should continue processing. Instead of returning, you should increment i to i+2 as you have already processed i+1. Since you can't do such increment in between a for loop, so you will have to go with a while loop.
fun romanToInt(s: String): Int {
val map = mapOf('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000)
var total = 0
var i = 0
while (i < s.length) {
val current = map[s[i]]!!
val next = if (i != s.lastIndex) map[s[i + 1]]!! else 0
if (current >= next) {
total += current
i++
} else {
total += next - current
i += 2
}
}
return total
}
I'm writing a function that allows you to remove certain numbers from an int arraylist.
My code
for (i in 1 until 4) {
divider = setDivider(i)
for(index in 0 until numbers.size){
if(index <= numbers.size){
if (numbers[index] % divider == 0 && !isDone) {
numbers.removeAt(index)
}
}else{
isDone = true
}
}
if(isDone)
break
}
the function to set the divider
fun setDivider(divider: Int): Int {
when (divider) {
1 -> return 2
2 -> return 3
3 -> return 5
4 -> return 7
}
return 8
}
I do not know why the ide is giving me the error Index 9 out of bounds for length 9.
Author explained in the comments that the goal is to remove all numbers that are divisible by 2, 3, 5 and 7.
It can be achieved much easier by utilizing ready to use functions from stdlib:
val dividers = listOf(2, 3, 5, 7)
numbers.removeAll { num ->
dividers.any { num % it == 0 }
}
It removes elements that satisfy the provided condition (is divisible) for any of provided dividers.
Also, it is often cleaner to not modify a collection in-place, but to create an entirely new collection:
val numbers2 = numbers.filterNot { num ->
dividers.any { num % it == 0 }
}
For a given number n, determine whether it contains different digits.
For example, 54 and 323 consist of different digits and 111 and 0 are the same.
you could try this
fun areDigitsDistinct(n:Int) = "$n".toCharArray().distinct().count() > 1
Try this:
fun hasDifferent(number: Int): Boolean {
val stringNumber = number.toString()
if (stringNumber.length == 1) return false
for (char in stringNumber) {
if (char != stringNumber[0]) return true
}
return false
}
Doesn't require convertion to String, doesn't require processing of all digits:
fun sameDigits(number: Int): Boolean {
val veryLastDigit = number % 10
var x = number / 10
while (x > 0) {
val lastDigit = x % 10
if (lastDigit != veryLastDigit) return false
x /= 10
}
return true
}
If you need to make it work with negative numbers too, change part before while-loop to this:
val _number = number.absoluteValue
val veryLastDigit = _number % 10
var x = _number / 10
I want to scan a line of integers from stdin into a slice of integers. Each integer is separated by whitespace. Ther would be as many as N integers of user input. I'm trying not to use a for loop. For example,
1 15 16 17
So far, this is my function to perform the task,
var array []int
func read(b int) {
if b == 0 {
return
}
fmt.Scanf("%d", &array)
read(b - 1)
}
The idea is to read from the input, 1 15 16 17, and make it into a slice with value [1 15 16 17]
After compiling, I got the error,
Runtime error
For example,
package main
import "fmt"
var a []int
func read(b int) {
if b == 0 {
return
}
var i int
_, err := fmt.Scanf("%d", &i)
if err != nil {
return
}
a = append(a, i)
read(b - 1)
}
func main() {
read(4)
fmt.Println(a)
}
Input:
1 15 16 17<Enter>
Output:
[1 15 16 17]
Not recursive, but just reading integers until stdin is closed or something that can't be converted to an integer is read.
package main
import "fmt"
func main() {
var array []int
var i int
for {
_, err := fmt.Scan(&i)
if err != nil {
break
}
array = append(array, i)
fmt.Println("read number", i, "from stdin, array ", array)
}
}
I'm using this RFID module for Arduino Ethernet R3 and I need to retrieve from the Software Serial the card (TAG) ID that is written outside the tag.
The module's datasheet says that 14 bytes are sent to the Arduino. The first is the header, the last the footer, the 2 bytes before the footer are the checksum, and the other 10 bytes are the ASCII data that contains the tag ID.
How can I recreate the ID of the card, and control the checksum? For example with a tag that has this ID: 0013530444, the Arduino response is:
I received: 2
I received: 51
I received: 67
I received: 48
I received: 48
I received: 67
I received: 69
I received: 55
I received: 53
I received: 52
I received: 67
I received: 67
I received: 66
I received: 3
But I've no idea how to print on the screen the ID read by the Arduino. How to calculate the checksum?
http://www.seeedstudio.com/wiki/index.php?title=125Khz_RFID_module_-_UART
Can anyone help me?
Here's a walkthrough of how to calculate the checksum.
Take your card number (this is just directly quoted from your text)
I received: 2
I received: 51
I received: 67
I received: 48
I received: 48
I received: 67
I received: 69
I received: 55
I received: 53
I received: 52
I received: 67
I received: 67
I received: 66
I received: 3
This would give you a number that is equivalent to the following:
2 51 67 48 48 67 69 55 53 52 67 67 66 3
The first numer (2) indicates that this is the beginning of a request.
The last number (3) indicates that this is the end of a request.
2 51 67 48 48 67 69 55 53 52 67 67 66 3
For the purposes of calculating the checksum, we are going to remove these two numbers. So your new number is now:
51 67 48 48 67 69 55 53 52 67 67 66
The last two numbers that you have are your checksum. The remaining numbers are your card number. So:
Your card number is:
51 67 48 48 67 69 55 53 52 67
And your checksum is:
67 66
Next you need to convert your Card Number and your Checksum to ASCII values:
Your card number is:
3 C 0 0 C E 7 5 4 C
And your checksum is:
C B
Next, grab each number into pairs:
Your card number is:
3C 00 CE 75 4C
And your checksum is:
CB
Then you need to treat each pair as a HEXIDECIMAL value and do an XOR against them. So basically you need to prove the following:
3C ^ 00 ^ CE ^ 75 ^ 4C == CB
(3C ^ 00) = 3C
3C ^ CE ^ 75 ^ 4C == CB
(3C ^ CE) = F2
F2 ^ 75 ^ 4C == CB
(3C ^ CE) = 87
87 ^ 4C == CB
(87 ^ 4C) = CB
CB == CB
Because CB == CB, this is a valid transaction.
No doubt someone else can come up with a better approach than this, but there should be enough pseudo code here for you to write it yourself.
I found this blog which has an implementation in Arduino, I've adapted it to work in Java and results are good. Since there are a lot of bitwise operations - I used http://www.miniwebtool.com/bitwise-calculator/ to try to understand what's going on. I understand all of it except (val | (tempbyte << 4)), I mean I understand what the statement does, I just struggle to see how that produces the result I want.
void loop () {
byte i = 0;
byte val = 0;
byte code[6];
byte checksum = 0;
byte bytesread = 0;
byte tempbyte = 0;
if(Serial.available() > 0) {
if((val = Serial.read()) == 2) {
// check for header
bytesread = 0;
while (bytesread < 12) {
// read 10 digit code + 2 digit checksum
if( Serial.available() > 0) {
val = Serial.read();
if((val == 0x0D)||(val == 0x0A)||(val == 0x03)||(val == 0x02)) {
// if header or stop bytes before the 10 digit reading
break;
// stop reading
}
// Do Ascii/Hex conversion:
if ((val >= '0') && (val <= '9')) {
val = val - '0';
} else if ((val >= 'A') && (val <= 'F')) {
val = 10 + val - 'A';
}
// Every two hex-digits, add byte to code:
if (bytesread & 1 == 1) {
// make some space for this hex-digit by
// shifting the previous hex-digit with 4 bits to the left:
code[bytesread >> 1] = (val | (tempbyte << 4));
if (bytesread >> 1 != 5) {
// If we're at the checksum byte,
checksum ^= code[bytesread >> 1];
// Calculate the checksum... (XOR)
};
} else {
tempbyte = val;
// Store the first hex digit first...
};
bytesread++;
// ready to read next digit
}
}
// Output to Serial:
if (bytesread == 12) {
// removed code for clarity
LCD.print("Check:");
LCD.print(code[5], HEX);
LCD.print(code[5] == checksum ? "-passed" : "-error");
}
bytesread = 0;
}
}
}
My Java/Android port is listening over a BluetoothSocket. I'm using the code from BlueTerm as the base, this code goes in the ConnectedThread. Apologies for all silly comments, but I'm still learning Java).
//assume you have checksum as int and code as int array. it will overflow if bytes are used like above example
public void run() {
Log.d(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
Log.d(TAG, "Running");
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
for (int i = 0; i < bytes; i++) {
Log.d(TAG, "Reading: " + i + " of " + bytes + " from input stream");
byte b = buffer[i];
try {
if(bytesread >= 0) {
//just printing ASCII
char printableB = (char) b;
if (b < 32 || b > 126) printableB = ' ';
Log.d(TAG, "'" + Character.toString(printableB) + "' (" + Integer.toString(b) + ")");
if((b == 0x0D)||(b == 0x0A)||(b == 0x03)||(b == 0x02)) {
// if header or stop bytes before the 10 digit reading
Log.e(TAG, i + " Unexpected header while processing character " + Integer.toString(b));
} else {
// Do ASCII/Hex conversion
if ((b >= '0') && (b <= '9')) {
b = (byte) (b - '0');
} else if ((b >= 'A') && (b <= 'F')) {
b = (byte) (10 + b - 'A');
}
if ((bytesread & 1) == 1) {
//if isOdd(bytesread)
// make some space for this hex-digit by shifting the previous hex-digit with 4 bits to the left:
code[bytesread >> 1] = (b | (tempbyte << 4));
if (bytesread >> 1 != 5) {
// If we're not at the checksum byte,
checksum ^= code[bytesread >> 1];
// Calculate the checksum... (XOR)
}
} else {
// Store the first hex digit first
tempbyte = b;
}
}
bytesread++;
} else if(b == 2) {
bytesread = 0;
Log.d(TAG, "Header found!");
}
if(bytesread == 12) {
String check = (code[5] == checksum ? "-passed" : "-error");
String r = "";
for(int j = 0; j < 5; j++){
r += Integer.toString(code[i]);
}
Log.d(TAG, "Check:" + Integer.toString(code[5]) + check);
init();
} else if(bytesread > 12){
Log.e(TAG, "Too many bytes!");
}
} catch (Exception e) {
Log.e(TAG, i + " Exception while processing character " + Integer.toString(b), e);
}
}
String a = buffer.toString();
a = "";
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
Log.i(TAG, "END mConnectedThread");
}